]> 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.3.  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 65536.  This a limit
219 ** imposed by the use of 16-bit offsets within each page.
220 **
221 ** Earlier versions of SQLite allowed the user to change this value at
222 ** compile time. This is no longer permitted, on the grounds that it creates
223 ** a library that is technically incompatible with an SQLite library 
224 ** compiled with a different limit. If a process operating on a database 
225 ** with a page-size of 65536 bytes crashes, then an instance of SQLite 
226 ** compiled with the default page-size limit will not be able to rollback 
227 ** the aborted transaction. This could lead to database corruption.
228 */
229 #ifdef SQLITE_MAX_PAGE_SIZE
230 # undef SQLITE_MAX_PAGE_SIZE
231 #endif
232 #define SQLITE_MAX_PAGE_SIZE 65536
233
234
235 /*
236 ** The default size of a database page.
237 */
238 #ifndef SQLITE_DEFAULT_PAGE_SIZE
239 # define SQLITE_DEFAULT_PAGE_SIZE 1024
240 #endif
241 #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
242 # undef SQLITE_DEFAULT_PAGE_SIZE
243 # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
244 #endif
245
246 /*
247 ** Ordinarily, if no value is explicitly provided, SQLite creates databases
248 ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
249 ** device characteristics (sector-size and atomic write() support),
250 ** SQLite may choose a larger value. This constant is the maximum value
251 ** SQLite will choose on its own.
252 */
253 #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
254 # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
255 #endif
256 #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
257 # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
258 # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
259 #endif
260
261
262 /*
263 ** Maximum number of pages in one database file.
264 **
265 ** This is really just the default value for the max_page_count pragma.
266 ** This value can be lowered (or raised) at run-time using that the
267 ** max_page_count macro.
268 */
269 #ifndef SQLITE_MAX_PAGE_COUNT
270 # define SQLITE_MAX_PAGE_COUNT 1073741823
271 #endif
272
273 /*
274 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
275 ** operator.
276 */
277 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
278 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
279 #endif
280
281 /*
282 ** Maximum depth of recursion for triggers.
283 **
284 ** A value of 1 means that a trigger program will not be able to itself
285 ** fire any triggers. A value of 0 means that no trigger programs at all 
286 ** may be executed.
287 */
288 #ifndef SQLITE_MAX_TRIGGER_DEPTH
289 # define SQLITE_MAX_TRIGGER_DEPTH 1000
290 #endif
291
292 /************** End of sqliteLimit.h *****************************************/
293 /************** Continuing where we left off in sqliteInt.h ******************/
294
295 /* Disable nuisance warnings on Borland compilers */
296 #if defined(__BORLANDC__)
297 #pragma warn -rch /* unreachable code */
298 #pragma warn -ccc /* Condition is always true or false */
299 #pragma warn -aus /* Assigned value is never used */
300 #pragma warn -csu /* Comparing signed and unsigned */
301 #pragma warn -spa /* Suspicious pointer arithmetic */
302 #endif
303
304 /* Needed for various definitions... */
305 #ifndef _GNU_SOURCE
306 # define _GNU_SOURCE
307 #endif
308
309 /*
310 ** Include standard header files as necessary
311 */
312 #ifdef HAVE_STDINT_H
313 #include <stdint.h>
314 #endif
315 #ifdef HAVE_INTTYPES_H
316 #include <inttypes.h>
317 #endif
318
319 /*
320 ** The number of samples of an index that SQLite takes in order to 
321 ** construct a histogram of the table content when running ANALYZE
322 ** and with SQLITE_ENABLE_STAT2
323 */
324 #define SQLITE_INDEX_SAMPLES 10
325
326 /*
327 ** The following macros are used to cast pointers to integers and
328 ** integers to pointers.  The way you do this varies from one compiler
329 ** to the next, so we have developed the following set of #if statements
330 ** to generate appropriate macros for a wide range of compilers.
331 **
332 ** The correct "ANSI" way to do this is to use the intptr_t type. 
333 ** Unfortunately, that typedef is not available on all compilers, or
334 ** if it is available, it requires an #include of specific headers
335 ** that vary from one machine to the next.
336 **
337 ** Ticket #3860:  The llvm-gcc-4.2 compiler from Apple chokes on
338 ** the ((void*)&((char*)0)[X]) construct.  But MSVC chokes on ((void*)(X)).
339 ** So we have to define the macros in different ways depending on the
340 ** compiler.
341 */
342 #if defined(__PTRDIFF_TYPE__)  /* This case should work for GCC */
343 # define SQLITE_INT_TO_PTR(X)  ((void*)(__PTRDIFF_TYPE__)(X))
344 # define SQLITE_PTR_TO_INT(X)  ((int)(__PTRDIFF_TYPE__)(X))
345 #elif !defined(__GNUC__)       /* Works for compilers other than LLVM */
346 # define SQLITE_INT_TO_PTR(X)  ((void*)&((char*)0)[X])
347 # define SQLITE_PTR_TO_INT(X)  ((int)(((char*)X)-(char*)0))
348 #elif defined(HAVE_STDINT_H)   /* Use this case if we have ANSI headers */
349 # define SQLITE_INT_TO_PTR(X)  ((void*)(intptr_t)(X))
350 # define SQLITE_PTR_TO_INT(X)  ((int)(intptr_t)(X))
351 #else                          /* Generates a warning - but it always works */
352 # define SQLITE_INT_TO_PTR(X)  ((void*)(X))
353 # define SQLITE_PTR_TO_INT(X)  ((int)(X))
354 #endif
355
356 /*
357 ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
358 ** 0 means mutexes are permanently disable and the library is never
359 ** threadsafe.  1 means the library is serialized which is the highest
360 ** level of threadsafety.  2 means the libary is multithreaded - multiple
361 ** threads can use SQLite as long as no two threads try to use the same
362 ** database connection at the same time.
363 **
364 ** Older versions of SQLite used an optional THREADSAFE macro.
365 ** We support that for legacy.
366 */
367 #if !defined(SQLITE_THREADSAFE)
368 #if defined(THREADSAFE)
369 # define SQLITE_THREADSAFE THREADSAFE
370 #else
371 # define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
372 #endif
373 #endif
374
375 /*
376 ** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
377 ** It determines whether or not the features related to 
378 ** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can
379 ** be overridden at runtime using the sqlite3_config() API.
380 */
381 #if !defined(SQLITE_DEFAULT_MEMSTATUS)
382 # define SQLITE_DEFAULT_MEMSTATUS 1
383 #endif
384
385 /*
386 ** Exactly one of the following macros must be defined in order to
387 ** specify which memory allocation subsystem to use.
388 **
389 **     SQLITE_SYSTEM_MALLOC          // Use normal system malloc()
390 **     SQLITE_MEMDEBUG               // Debugging version of system malloc()
391 **
392 ** (Historical note:  There used to be several other options, but we've
393 ** pared it down to just these two.)
394 **
395 ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
396 ** the default.
397 */
398 #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)>1
399 # error "At most one of the following compile-time configuration options\
400  is allows: SQLITE_SYSTEM_MALLOC, SQLITE_MEMDEBUG"
401 #endif
402 #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)==0
403 # define SQLITE_SYSTEM_MALLOC 1
404 #endif
405
406 /*
407 ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
408 ** sizes of memory allocations below this value where possible.
409 */
410 #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
411 # define SQLITE_MALLOC_SOFT_LIMIT 1024
412 #endif
413
414 /*
415 ** We need to define _XOPEN_SOURCE as follows in order to enable
416 ** recursive mutexes on most Unix systems.  But Mac OS X is different.
417 ** The _XOPEN_SOURCE define causes problems for Mac OS X we are told,
418 ** so it is omitted there.  See ticket #2673.
419 **
420 ** Later we learn that _XOPEN_SOURCE is poorly or incorrectly
421 ** implemented on some systems.  So we avoid defining it at all
422 ** if it is already defined or if it is unneeded because we are
423 ** not doing a threadsafe build.  Ticket #2681.
424 **
425 ** See also ticket #2741.
426 */
427 #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__) && SQLITE_THREADSAFE
428 #  define _XOPEN_SOURCE 500  /* Needed to enable pthread recursive mutexes */
429 #endif
430
431 /*
432 ** The TCL headers are only needed when compiling the TCL bindings.
433 */
434 #if defined(SQLITE_TCL) || defined(TCLSH)
435 # include <tcl.h>
436 #endif
437
438 /*
439 ** Many people are failing to set -DNDEBUG=1 when compiling SQLite.
440 ** Setting NDEBUG makes the code smaller and run faster.  So the following
441 ** lines are added to automatically set NDEBUG unless the -DSQLITE_DEBUG=1
442 ** option is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
443 ** feature.
444 */
445 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
446 # define NDEBUG 1
447 #endif
448
449 /*
450 ** The testcase() macro is used to aid in coverage testing.  When 
451 ** doing coverage testing, the condition inside the argument to
452 ** testcase() must be evaluated both true and false in order to
453 ** get full branch coverage.  The testcase() macro is inserted
454 ** to help ensure adequate test coverage in places where simple
455 ** condition/decision coverage is inadequate.  For example, testcase()
456 ** can be used to make sure boundary values are tested.  For
457 ** bitmask tests, testcase() can be used to make sure each bit
458 ** is significant and used at least once.  On switch statements
459 ** where multiple cases go to the same block of code, testcase()
460 ** can insure that all cases are evaluated.
461 **
462 */
463 #ifdef SQLITE_COVERAGE_TEST
464 SQLITE_PRIVATE   void sqlite3Coverage(int);
465 # define testcase(X)  if( X ){ sqlite3Coverage(__LINE__); }
466 #else
467 # define testcase(X)
468 #endif
469
470 /*
471 ** The TESTONLY macro is used to enclose variable declarations or
472 ** other bits of code that are needed to support the arguments
473 ** within testcase() and assert() macros.
474 */
475 #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
476 # define TESTONLY(X)  X
477 #else
478 # define TESTONLY(X)
479 #endif
480
481 /*
482 ** Sometimes we need a small amount of code such as a variable initialization
483 ** to setup for a later assert() statement.  We do not want this code to
484 ** appear when assert() is disabled.  The following macro is therefore
485 ** used to contain that setup code.  The "VVA" acronym stands for
486 ** "Verification, Validation, and Accreditation".  In other words, the
487 ** code within VVA_ONLY() will only run during verification processes.
488 */
489 #ifndef NDEBUG
490 # define VVA_ONLY(X)  X
491 #else
492 # define VVA_ONLY(X)
493 #endif
494
495 /*
496 ** The ALWAYS and NEVER macros surround boolean expressions which 
497 ** are intended to always be true or false, respectively.  Such
498 ** expressions could be omitted from the code completely.  But they
499 ** are included in a few cases in order to enhance the resilience
500 ** of SQLite to unexpected behavior - to make the code "self-healing"
501 ** or "ductile" rather than being "brittle" and crashing at the first
502 ** hint of unplanned behavior.
503 **
504 ** In other words, ALWAYS and NEVER are added for defensive code.
505 **
506 ** When doing coverage testing ALWAYS and NEVER are hard-coded to
507 ** be true and false so that the unreachable code then specify will
508 ** not be counted as untested code.
509 */
510 #if defined(SQLITE_COVERAGE_TEST)
511 # define ALWAYS(X)      (1)
512 # define NEVER(X)       (0)
513 #elif !defined(NDEBUG)
514 # define ALWAYS(X)      ((X)?1:(assert(0),0))
515 # define NEVER(X)       ((X)?(assert(0),1):0)
516 #else
517 # define ALWAYS(X)      (X)
518 # define NEVER(X)       (X)
519 #endif
520
521 /*
522 ** Return true (non-zero) if the input is a integer that is too large
523 ** to fit in 32-bits.  This macro is used inside of various testcase()
524 ** macros to verify that we have tested SQLite for large-file support.
525 */
526 #define IS_BIG_INT(X)  (((X)&~(i64)0xffffffff)!=0)
527
528 /*
529 ** The macro unlikely() is a hint that surrounds a boolean
530 ** expression that is usually false.  Macro likely() surrounds
531 ** a boolean expression that is usually true.  GCC is able to
532 ** use these hints to generate better code, sometimes.
533 */
534 #if defined(__GNUC__) && 0
535 # define likely(X)    __builtin_expect((X),1)
536 # define unlikely(X)  __builtin_expect((X),0)
537 #else
538 # define likely(X)    !!(X)
539 # define unlikely(X)  !!(X)
540 #endif
541
542 /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
543 /************** Begin file sqlite3.h *****************************************/
544 /*
545 ** 2001 September 15
546 **
547 ** The author disclaims copyright to this source code.  In place of
548 ** a legal notice, here is a blessing:
549 **
550 **    May you do good and not evil.
551 **    May you find forgiveness for yourself and forgive others.
552 **    May you share freely, never taking more than you give.
553 **
554 *************************************************************************
555 ** This header file defines the interface that the SQLite library
556 ** presents to client programs.  If a C-function, structure, datatype,
557 ** or constant definition does not appear in this file, then it is
558 ** not a published API of SQLite, is subject to change without
559 ** notice, and should not be referenced by programs that use SQLite.
560 **
561 ** Some of the definitions that are in this file are marked as
562 ** "experimental".  Experimental interfaces are normally new
563 ** features recently added to SQLite.  We do not anticipate changes
564 ** to experimental interfaces but reserve the right to make minor changes
565 ** if experience from use "in the wild" suggest such changes are prudent.
566 **
567 ** The official C-language API documentation for SQLite is derived
568 ** from comments in this file.  This file is the authoritative source
569 ** on how SQLite interfaces are suppose to operate.
570 **
571 ** The name of this file under configuration management is "sqlite.h.in".
572 ** The makefile makes some minor changes to this file (such as inserting
573 ** the version number) and changes its name to "sqlite3.h" as
574 ** part of the build process.
575 */
576 #ifndef _SQLITE3_H_
577 #define _SQLITE3_H_
578 #include <stdarg.h>     /* Needed for the definition of va_list */
579
580 /*
581 ** Make sure we can call this stuff from C++.
582 */
583 #if 0
584 extern "C" {
585 #endif
586
587
588 /*
589 ** Add the ability to override 'extern'
590 */
591 #ifndef SQLITE_EXTERN
592 # define SQLITE_EXTERN extern
593 #endif
594
595 #ifndef SQLITE_API
596 # define SQLITE_API
597 #endif
598
599
600 /*
601 ** These no-op macros are used in front of interfaces to mark those
602 ** interfaces as either deprecated or experimental.  New applications
603 ** should not use deprecated interfaces - they are support for backwards
604 ** compatibility only.  Application writers should be aware that
605 ** experimental interfaces are subject to change in point releases.
606 **
607 ** These macros used to resolve to various kinds of compiler magic that
608 ** would generate warning messages when they were used.  But that
609 ** compiler magic ended up generating such a flurry of bug reports
610 ** that we have taken it all out and gone back to using simple
611 ** noop macros.
612 */
613 #define SQLITE_DEPRECATED
614 #define SQLITE_EXPERIMENTAL
615
616 /*
617 ** Ensure these symbols were not defined by some previous header file.
618 */
619 #ifdef SQLITE_VERSION
620 # undef SQLITE_VERSION
621 #endif
622 #ifdef SQLITE_VERSION_NUMBER
623 # undef SQLITE_VERSION_NUMBER
624 #endif
625
626 /*
627 ** CAPI3REF: Compile-Time Library Version Numbers
628 **
629 ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
630 ** evaluates to a string literal that is the SQLite version in the
631 ** format "X.Y.Z" where X is the major version number (always 3 for
632 ** SQLite3) and Y is the minor version number and Z is the release number.)^
633 ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
634 ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
635 ** numbers used in [SQLITE_VERSION].)^
636 ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
637 ** be larger than the release from which it is derived.  Either Y will
638 ** be held constant and Z will be incremented or else Y will be incremented
639 ** and Z will be reset to zero.
640 **
641 ** Since version 3.6.18, SQLite source code has been stored in the
642 ** <a href="http://www.fossil-scm.org/">Fossil configuration management
643 ** system</a>.  ^The SQLITE_SOURCE_ID macro evaluates to
644 ** a string which identifies a particular check-in of SQLite
645 ** within its configuration management system.  ^The SQLITE_SOURCE_ID
646 ** string contains the date and time of the check-in (UTC) and an SHA1
647 ** hash of the entire source tree.
648 **
649 ** See also: [sqlite3_libversion()],
650 ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
651 ** [sqlite_version()] and [sqlite_source_id()].
652 */
653 #define SQLITE_VERSION        "3.7.3"
654 #define SQLITE_VERSION_NUMBER 3007003
655 #define SQLITE_SOURCE_ID      "2010-10-08 02:34:02 2677848087c9c090efb17c1893e77d6136a9111d"
656
657 /*
658 ** CAPI3REF: Run-Time Library Version Numbers
659 ** KEYWORDS: sqlite3_version, sqlite3_sourceid
660 **
661 ** These interfaces provide the same information as the [SQLITE_VERSION],
662 ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
663 ** but are associated with the library instead of the header file.  ^(Cautious
664 ** programmers might include assert() statements in their application to
665 ** verify that values returned by these interfaces match the macros in
666 ** the header, and thus insure that the application is
667 ** compiled with matching library and header files.
668 **
669 ** <blockquote><pre>
670 ** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
671 ** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
672 ** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
673 ** </pre></blockquote>)^
674 **
675 ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
676 ** macro.  ^The sqlite3_libversion() function returns a pointer to the
677 ** to the sqlite3_version[] string constant.  The sqlite3_libversion()
678 ** function is provided for use in DLLs since DLL users usually do not have
679 ** direct access to string constants within the DLL.  ^The
680 ** sqlite3_libversion_number() function returns an integer equal to
681 ** [SQLITE_VERSION_NUMBER].  ^The sqlite3_sourceid() function returns 
682 ** a pointer to a string constant whose value is the same as the 
683 ** [SQLITE_SOURCE_ID] C preprocessor macro.
684 **
685 ** See also: [sqlite_version()] and [sqlite_source_id()].
686 */
687 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
688 SQLITE_API const char *sqlite3_libversion(void);
689 SQLITE_API const char *sqlite3_sourceid(void);
690 SQLITE_API int sqlite3_libversion_number(void);
691
692 /*
693 ** CAPI3REF: Run-Time Library Compilation Options Diagnostics
694 **
695 ** ^The sqlite3_compileoption_used() function returns 0 or 1 
696 ** indicating whether the specified option was defined at 
697 ** compile time.  ^The SQLITE_ prefix may be omitted from the 
698 ** option name passed to sqlite3_compileoption_used().  
699 **
700 ** ^The sqlite3_compileoption_get() function allows iterating
701 ** over the list of options that were defined at compile time by
702 ** returning the N-th compile time option string.  ^If N is out of range,
703 ** sqlite3_compileoption_get() returns a NULL pointer.  ^The SQLITE_ 
704 ** prefix is omitted from any strings returned by 
705 ** sqlite3_compileoption_get().
706 **
707 ** ^Support for the diagnostic functions sqlite3_compileoption_used()
708 ** and sqlite3_compileoption_get() may be omitted by specifying the 
709 ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
710 **
711 ** See also: SQL functions [sqlite_compileoption_used()] and
712 ** [sqlite_compileoption_get()] and the [compile_options pragma].
713 */
714 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
715 SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
716 SQLITE_API const char *sqlite3_compileoption_get(int N);
717 #endif
718
719 /*
720 ** CAPI3REF: Test To See If The Library Is Threadsafe
721 **
722 ** ^The sqlite3_threadsafe() function returns zero if and only if
723 ** SQLite was compiled mutexing code omitted due to the
724 ** [SQLITE_THREADSAFE] compile-time option being set to 0.
725 **
726 ** SQLite can be compiled with or without mutexes.  When
727 ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
728 ** are enabled and SQLite is threadsafe.  When the
729 ** [SQLITE_THREADSAFE] macro is 0, 
730 ** the mutexes are omitted.  Without the mutexes, it is not safe
731 ** to use SQLite concurrently from more than one thread.
732 **
733 ** Enabling mutexes incurs a measurable performance penalty.
734 ** So if speed is of utmost importance, it makes sense to disable
735 ** the mutexes.  But for maximum safety, mutexes should be enabled.
736 ** ^The default behavior is for mutexes to be enabled.
737 **
738 ** This interface can be used by an application to make sure that the
739 ** version of SQLite that it is linking against was compiled with
740 ** the desired setting of the [SQLITE_THREADSAFE] macro.
741 **
742 ** This interface only reports on the compile-time mutex setting
743 ** of the [SQLITE_THREADSAFE] flag.  If SQLite is compiled with
744 ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
745 ** can be fully or partially disabled using a call to [sqlite3_config()]
746 ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
747 ** or [SQLITE_CONFIG_MUTEX].  ^(The return value of the
748 ** sqlite3_threadsafe() function shows only the compile-time setting of
749 ** thread safety, not any run-time changes to that setting made by
750 ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
751 ** is unchanged by calls to sqlite3_config().)^
752 **
753 ** See the [threading mode] documentation for additional information.
754 */
755 SQLITE_API int sqlite3_threadsafe(void);
756
757 /*
758 ** CAPI3REF: Database Connection Handle
759 ** KEYWORDS: {database connection} {database connections}
760 **
761 ** Each open SQLite database is represented by a pointer to an instance of
762 ** the opaque structure named "sqlite3".  It is useful to think of an sqlite3
763 ** pointer as an object.  The [sqlite3_open()], [sqlite3_open16()], and
764 ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
765 ** is its destructor.  There are many other interfaces (such as
766 ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
767 ** [sqlite3_busy_timeout()] to name but three) that are methods on an
768 ** sqlite3 object.
769 */
770 typedef struct sqlite3 sqlite3;
771
772 /*
773 ** CAPI3REF: 64-Bit Integer Types
774 ** KEYWORDS: sqlite_int64 sqlite_uint64
775 **
776 ** Because there is no cross-platform way to specify 64-bit integer types
777 ** SQLite includes typedefs for 64-bit signed and unsigned integers.
778 **
779 ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
780 ** The sqlite_int64 and sqlite_uint64 types are supported for backwards
781 ** compatibility only.
782 **
783 ** ^The sqlite3_int64 and sqlite_int64 types can store integer values
784 ** between -9223372036854775808 and +9223372036854775807 inclusive.  ^The
785 ** sqlite3_uint64 and sqlite_uint64 types can store integer values 
786 ** between 0 and +18446744073709551615 inclusive.
787 */
788 #ifdef SQLITE_INT64_TYPE
789   typedef SQLITE_INT64_TYPE sqlite_int64;
790   typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
791 #elif defined(_MSC_VER) || defined(__BORLANDC__)
792   typedef __int64 sqlite_int64;
793   typedef unsigned __int64 sqlite_uint64;
794 #else
795   typedef long long int sqlite_int64;
796   typedef unsigned long long int sqlite_uint64;
797 #endif
798 typedef sqlite_int64 sqlite3_int64;
799 typedef sqlite_uint64 sqlite3_uint64;
800
801 /*
802 ** If compiling for a processor that lacks floating point support,
803 ** substitute integer for floating-point.
804 */
805 #ifdef SQLITE_OMIT_FLOATING_POINT
806 # define double sqlite3_int64
807 #endif
808
809 /*
810 ** CAPI3REF: Closing A Database Connection
811 **
812 ** ^The sqlite3_close() routine is the destructor for the [sqlite3] object.
813 ** ^Calls to sqlite3_close() return SQLITE_OK if the [sqlite3] object is
814 ** successfully destroyed and all associated resources are deallocated.
815 **
816 ** Applications must [sqlite3_finalize | finalize] all [prepared statements]
817 ** and [sqlite3_blob_close | close] all [BLOB handles] associated with
818 ** the [sqlite3] object prior to attempting to close the object.  ^If
819 ** sqlite3_close() is called on a [database connection] that still has
820 ** outstanding [prepared statements] or [BLOB handles], then it returns
821 ** SQLITE_BUSY.
822 **
823 ** ^If [sqlite3_close()] is invoked while a transaction is open,
824 ** the transaction is automatically rolled back.
825 **
826 ** The C parameter to [sqlite3_close(C)] must be either a NULL
827 ** pointer or an [sqlite3] object pointer obtained
828 ** from [sqlite3_open()], [sqlite3_open16()], or
829 ** [sqlite3_open_v2()], and not previously closed.
830 ** ^Calling sqlite3_close() with a NULL pointer argument is a 
831 ** harmless no-op.
832 */
833 SQLITE_API int sqlite3_close(sqlite3 *);
834
835 /*
836 ** The type for a callback function.
837 ** This is legacy and deprecated.  It is included for historical
838 ** compatibility and is not documented.
839 */
840 typedef int (*sqlite3_callback)(void*,int,char**, char**);
841
842 /*
843 ** CAPI3REF: One-Step Query Execution Interface
844 **
845 ** The sqlite3_exec() interface is a convenience wrapper around
846 ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
847 ** that allows an application to run multiple statements of SQL
848 ** without having to use a lot of C code. 
849 **
850 ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
851 ** semicolon-separate SQL statements passed into its 2nd argument,
852 ** in the context of the [database connection] passed in as its 1st
853 ** argument.  ^If the callback function of the 3rd argument to
854 ** sqlite3_exec() is not NULL, then it is invoked for each result row
855 ** coming out of the evaluated SQL statements.  ^The 4th argument to
856 ** to sqlite3_exec() is relayed through to the 1st argument of each
857 ** callback invocation.  ^If the callback pointer to sqlite3_exec()
858 ** is NULL, then no callback is ever invoked and result rows are
859 ** ignored.
860 **
861 ** ^If an error occurs while evaluating the SQL statements passed into
862 ** sqlite3_exec(), then execution of the current statement stops and
863 ** subsequent statements are skipped.  ^If the 5th parameter to sqlite3_exec()
864 ** is not NULL then any error message is written into memory obtained
865 ** from [sqlite3_malloc()] and passed back through the 5th parameter.
866 ** To avoid memory leaks, the application should invoke [sqlite3_free()]
867 ** on error message strings returned through the 5th parameter of
868 ** of sqlite3_exec() after the error message string is no longer needed.
869 ** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
870 ** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
871 ** NULL before returning.
872 **
873 ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
874 ** routine returns SQLITE_ABORT without invoking the callback again and
875 ** without running any subsequent SQL statements.
876 **
877 ** ^The 2nd argument to the sqlite3_exec() callback function is the
878 ** number of columns in the result.  ^The 3rd argument to the sqlite3_exec()
879 ** callback is an array of pointers to strings obtained as if from
880 ** [sqlite3_column_text()], one for each column.  ^If an element of a
881 ** result row is NULL then the corresponding string pointer for the
882 ** sqlite3_exec() callback is a NULL pointer.  ^The 4th argument to the
883 ** sqlite3_exec() callback is an array of pointers to strings where each
884 ** entry represents the name of corresponding result column as obtained
885 ** from [sqlite3_column_name()].
886 **
887 ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
888 ** to an empty string, or a pointer that contains only whitespace and/or 
889 ** SQL comments, then no SQL statements are evaluated and the database
890 ** is not changed.
891 **
892 ** Restrictions:
893 **
894 ** <ul>
895 ** <li> The application must insure that the 1st parameter to sqlite3_exec()
896 **      is a valid and open [database connection].
897 ** <li> The application must not close [database connection] specified by
898 **      the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
899 ** <li> The application must not modify the SQL statement text passed into
900 **      the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
901 ** </ul>
902 */
903 SQLITE_API int sqlite3_exec(
904   sqlite3*,                                  /* An open database */
905   const char *sql,                           /* SQL to be evaluated */
906   int (*callback)(void*,int,char**,char**),  /* Callback function */
907   void *,                                    /* 1st argument to callback */
908   char **errmsg                              /* Error msg written here */
909 );
910
911 /*
912 ** CAPI3REF: Result Codes
913 ** KEYWORDS: SQLITE_OK {error code} {error codes}
914 ** KEYWORDS: {result code} {result codes}
915 **
916 ** Many SQLite functions return an integer result code from the set shown
917 ** here in order to indicates success or failure.
918 **
919 ** New error codes may be added in future versions of SQLite.
920 **
921 ** See also: [SQLITE_IOERR_READ | extended result codes]
922 */
923 #define SQLITE_OK           0   /* Successful result */
924 /* beginning-of-error-codes */
925 #define SQLITE_ERROR        1   /* SQL error or missing database */
926 #define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */
927 #define SQLITE_PERM         3   /* Access permission denied */
928 #define SQLITE_ABORT        4   /* Callback routine requested an abort */
929 #define SQLITE_BUSY         5   /* The database file is locked */
930 #define SQLITE_LOCKED       6   /* A table in the database is locked */
931 #define SQLITE_NOMEM        7   /* A malloc() failed */
932 #define SQLITE_READONLY     8   /* Attempt to write a readonly database */
933 #define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/
934 #define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
935 #define SQLITE_CORRUPT     11   /* The database disk image is malformed */
936 #define SQLITE_NOTFOUND    12   /* NOT USED. Table or record not found */
937 #define SQLITE_FULL        13   /* Insertion failed because database is full */
938 #define SQLITE_CANTOPEN    14   /* Unable to open the database file */
939 #define SQLITE_PROTOCOL    15   /* Database lock protocol error */
940 #define SQLITE_EMPTY       16   /* Database is empty */
941 #define SQLITE_SCHEMA      17   /* The database schema changed */
942 #define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
943 #define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */
944 #define SQLITE_MISMATCH    20   /* Data type mismatch */
945 #define SQLITE_MISUSE      21   /* Library used incorrectly */
946 #define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
947 #define SQLITE_AUTH        23   /* Authorization denied */
948 #define SQLITE_FORMAT      24   /* Auxiliary database format error */
949 #define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
950 #define SQLITE_NOTADB      26   /* File opened that is not a database file */
951 #define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
952 #define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
953 /* end-of-error-codes */
954
955 /*
956 ** CAPI3REF: Extended Result Codes
957 ** KEYWORDS: {extended error code} {extended error codes}
958 ** KEYWORDS: {extended result code} {extended result codes}
959 **
960 ** In its default configuration, SQLite API routines return one of 26 integer
961 ** [SQLITE_OK | result codes].  However, experience has shown that many of
962 ** these result codes are too coarse-grained.  They do not provide as
963 ** much information about problems as programmers might like.  In an effort to
964 ** address this, newer versions of SQLite (version 3.3.8 and later) include
965 ** support for additional result codes that provide more detailed information
966 ** about errors. The extended result codes are enabled or disabled
967 ** on a per database connection basis using the
968 ** [sqlite3_extended_result_codes()] API.
969 **
970 ** Some of the available extended result codes are listed here.
971 ** One may expect the number of extended result codes will be expand
972 ** over time.  Software that uses extended result codes should expect
973 ** to see new result codes in future releases of SQLite.
974 **
975 ** The SQLITE_OK result code will never be extended.  It will always
976 ** be exactly zero.
977 */
978 #define SQLITE_IOERR_READ              (SQLITE_IOERR | (1<<8))
979 #define SQLITE_IOERR_SHORT_READ        (SQLITE_IOERR | (2<<8))
980 #define SQLITE_IOERR_WRITE             (SQLITE_IOERR | (3<<8))
981 #define SQLITE_IOERR_FSYNC             (SQLITE_IOERR | (4<<8))
982 #define SQLITE_IOERR_DIR_FSYNC         (SQLITE_IOERR | (5<<8))
983 #define SQLITE_IOERR_TRUNCATE          (SQLITE_IOERR | (6<<8))
984 #define SQLITE_IOERR_FSTAT             (SQLITE_IOERR | (7<<8))
985 #define SQLITE_IOERR_UNLOCK            (SQLITE_IOERR | (8<<8))
986 #define SQLITE_IOERR_RDLOCK            (SQLITE_IOERR | (9<<8))
987 #define SQLITE_IOERR_DELETE            (SQLITE_IOERR | (10<<8))
988 #define SQLITE_IOERR_BLOCKED           (SQLITE_IOERR | (11<<8))
989 #define SQLITE_IOERR_NOMEM             (SQLITE_IOERR | (12<<8))
990 #define SQLITE_IOERR_ACCESS            (SQLITE_IOERR | (13<<8))
991 #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
992 #define SQLITE_IOERR_LOCK              (SQLITE_IOERR | (15<<8))
993 #define SQLITE_IOERR_CLOSE             (SQLITE_IOERR | (16<<8))
994 #define SQLITE_IOERR_DIR_CLOSE         (SQLITE_IOERR | (17<<8))
995 #define SQLITE_IOERR_SHMOPEN           (SQLITE_IOERR | (18<<8))
996 #define SQLITE_IOERR_SHMSIZE           (SQLITE_IOERR | (19<<8))
997 #define SQLITE_IOERR_SHMLOCK           (SQLITE_IOERR | (20<<8))
998 #define SQLITE_LOCKED_SHAREDCACHE      (SQLITE_LOCKED |  (1<<8))
999 #define SQLITE_BUSY_RECOVERY           (SQLITE_BUSY   |  (1<<8))
1000 #define SQLITE_CANTOPEN_NOTEMPDIR      (SQLITE_CANTOPEN | (1<<8))
1001
1002 /*
1003 ** CAPI3REF: Flags For File Open Operations
1004 **
1005 ** These bit values are intended for use in the
1006 ** 3rd parameter to the [sqlite3_open_v2()] interface and
1007 ** in the 4th parameter to the xOpen method of the
1008 ** [sqlite3_vfs] object.
1009 */
1010 #define SQLITE_OPEN_READONLY         0x00000001  /* Ok for sqlite3_open_v2() */
1011 #define SQLITE_OPEN_READWRITE        0x00000002  /* Ok for sqlite3_open_v2() */
1012 #define SQLITE_OPEN_CREATE           0x00000004  /* Ok for sqlite3_open_v2() */
1013 #define SQLITE_OPEN_DELETEONCLOSE    0x00000008  /* VFS only */
1014 #define SQLITE_OPEN_EXCLUSIVE        0x00000010  /* VFS only */
1015 #define SQLITE_OPEN_AUTOPROXY        0x00000020  /* VFS only */
1016 #define SQLITE_OPEN_MAIN_DB          0x00000100  /* VFS only */
1017 #define SQLITE_OPEN_TEMP_DB          0x00000200  /* VFS only */
1018 #define SQLITE_OPEN_TRANSIENT_DB     0x00000400  /* VFS only */
1019 #define SQLITE_OPEN_MAIN_JOURNAL     0x00000800  /* VFS only */
1020 #define SQLITE_OPEN_TEMP_JOURNAL     0x00001000  /* VFS only */
1021 #define SQLITE_OPEN_SUBJOURNAL       0x00002000  /* VFS only */
1022 #define SQLITE_OPEN_MASTER_JOURNAL   0x00004000  /* VFS only */
1023 #define SQLITE_OPEN_NOMUTEX          0x00008000  /* Ok for sqlite3_open_v2() */
1024 #define SQLITE_OPEN_FULLMUTEX        0x00010000  /* Ok for sqlite3_open_v2() */
1025 #define SQLITE_OPEN_SHAREDCACHE      0x00020000  /* Ok for sqlite3_open_v2() */
1026 #define SQLITE_OPEN_PRIVATECACHE     0x00040000  /* Ok for sqlite3_open_v2() */
1027 #define SQLITE_OPEN_WAL              0x00080000  /* VFS only */
1028
1029 /*
1030 ** CAPI3REF: Device Characteristics
1031 **
1032 ** The xDeviceCharacteristics method of the [sqlite3_io_methods]
1033 ** object returns an integer which is a vector of the these
1034 ** bit values expressing I/O characteristics of the mass storage
1035 ** device that holds the file that the [sqlite3_io_methods]
1036 ** refers to.
1037 **
1038 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
1039 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
1040 ** mean that writes of blocks that are nnn bytes in size and
1041 ** are aligned to an address which is an integer multiple of
1042 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
1043 ** that when data is appended to a file, the data is appended
1044 ** first then the size of the file is extended, never the other
1045 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
1046 ** information is written to disk in the same order as calls
1047 ** to xWrite().
1048 */
1049 #define SQLITE_IOCAP_ATOMIC                 0x00000001
1050 #define SQLITE_IOCAP_ATOMIC512              0x00000002
1051 #define SQLITE_IOCAP_ATOMIC1K               0x00000004
1052 #define SQLITE_IOCAP_ATOMIC2K               0x00000008
1053 #define SQLITE_IOCAP_ATOMIC4K               0x00000010
1054 #define SQLITE_IOCAP_ATOMIC8K               0x00000020
1055 #define SQLITE_IOCAP_ATOMIC16K              0x00000040
1056 #define SQLITE_IOCAP_ATOMIC32K              0x00000080
1057 #define SQLITE_IOCAP_ATOMIC64K              0x00000100
1058 #define SQLITE_IOCAP_SAFE_APPEND            0x00000200
1059 #define SQLITE_IOCAP_SEQUENTIAL             0x00000400
1060 #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN  0x00000800
1061
1062 /*
1063 ** CAPI3REF: File Locking Levels
1064 **
1065 ** SQLite uses one of these integer values as the second
1066 ** argument to calls it makes to the xLock() and xUnlock() methods
1067 ** of an [sqlite3_io_methods] object.
1068 */
1069 #define SQLITE_LOCK_NONE          0
1070 #define SQLITE_LOCK_SHARED        1
1071 #define SQLITE_LOCK_RESERVED      2
1072 #define SQLITE_LOCK_PENDING       3
1073 #define SQLITE_LOCK_EXCLUSIVE     4
1074
1075 /*
1076 ** CAPI3REF: Synchronization Type Flags
1077 **
1078 ** When SQLite invokes the xSync() method of an
1079 ** [sqlite3_io_methods] object it uses a combination of
1080 ** these integer values as the second argument.
1081 **
1082 ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
1083 ** sync operation only needs to flush data to mass storage.  Inode
1084 ** information need not be flushed. If the lower four bits of the flag
1085 ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
1086 ** If the lower four bits equal SQLITE_SYNC_FULL, that means
1087 ** to use Mac OS X style fullsync instead of fsync().
1088 */
1089 #define SQLITE_SYNC_NORMAL        0x00002
1090 #define SQLITE_SYNC_FULL          0x00003
1091 #define SQLITE_SYNC_DATAONLY      0x00010
1092
1093 /*
1094 ** CAPI3REF: OS Interface Open File Handle
1095 **
1096 ** An [sqlite3_file] object represents an open file in the 
1097 ** [sqlite3_vfs | OS interface layer].  Individual OS interface
1098 ** implementations will
1099 ** want to subclass this object by appending additional fields
1100 ** for their own use.  The pMethods entry is a pointer to an
1101 ** [sqlite3_io_methods] object that defines methods for performing
1102 ** I/O operations on the open file.
1103 */
1104 typedef struct sqlite3_file sqlite3_file;
1105 struct sqlite3_file {
1106   const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
1107 };
1108
1109 /*
1110 ** CAPI3REF: OS Interface File Virtual Methods Object
1111 **
1112 ** Every file opened by the [sqlite3_vfs] xOpen method populates an
1113 ** [sqlite3_file] object (or, more commonly, a subclass of the
1114 ** [sqlite3_file] object) with a pointer to an instance of this object.
1115 ** This object defines the methods used to perform various operations
1116 ** against the open file represented by the [sqlite3_file] object.
1117 **
1118 ** If the xOpen method sets the sqlite3_file.pMethods element 
1119 ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
1120 ** may be invoked even if the xOpen reported that it failed.  The
1121 ** only way to prevent a call to xClose following a failed xOpen
1122 ** is for the xOpen to set the sqlite3_file.pMethods element to NULL.
1123 **
1124 ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
1125 ** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().
1126 ** The second choice is a Mac OS X style fullsync.  The [SQLITE_SYNC_DATAONLY]
1127 ** flag may be ORed in to indicate that only the data of the file
1128 ** and not its inode needs to be synced.
1129 **
1130 ** The integer values to xLock() and xUnlock() are one of
1131 ** <ul>
1132 ** <li> [SQLITE_LOCK_NONE],
1133 ** <li> [SQLITE_LOCK_SHARED],
1134 ** <li> [SQLITE_LOCK_RESERVED],
1135 ** <li> [SQLITE_LOCK_PENDING], or
1136 ** <li> [SQLITE_LOCK_EXCLUSIVE].
1137 ** </ul>
1138 ** xLock() increases the lock. xUnlock() decreases the lock.
1139 ** The xCheckReservedLock() method checks whether any database connection,
1140 ** either in this process or in some other process, is holding a RESERVED,
1141 ** PENDING, or EXCLUSIVE lock on the file.  It returns true
1142 ** if such a lock exists and false otherwise.
1143 **
1144 ** The xFileControl() method is a generic interface that allows custom
1145 ** VFS implementations to directly control an open file using the
1146 ** [sqlite3_file_control()] interface.  The second "op" argument is an
1147 ** integer opcode.  The third argument is a generic pointer intended to
1148 ** point to a structure that may contain arguments or space in which to
1149 ** write return values.  Potential uses for xFileControl() might be
1150 ** functions to enable blocking locks with timeouts, to change the
1151 ** locking strategy (for example to use dot-file locks), to inquire
1152 ** about the status of a lock, or to break stale locks.  The SQLite
1153 ** core reserves all opcodes less than 100 for its own use.
1154 ** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
1155 ** Applications that define a custom xFileControl method should use opcodes
1156 ** greater than 100 to avoid conflicts.
1157 **
1158 ** The xSectorSize() method returns the sector size of the
1159 ** device that underlies the file.  The sector size is the
1160 ** minimum write that can be performed without disturbing
1161 ** other bytes in the file.  The xDeviceCharacteristics()
1162 ** method returns a bit vector describing behaviors of the
1163 ** underlying device:
1164 **
1165 ** <ul>
1166 ** <li> [SQLITE_IOCAP_ATOMIC]
1167 ** <li> [SQLITE_IOCAP_ATOMIC512]
1168 ** <li> [SQLITE_IOCAP_ATOMIC1K]
1169 ** <li> [SQLITE_IOCAP_ATOMIC2K]
1170 ** <li> [SQLITE_IOCAP_ATOMIC4K]
1171 ** <li> [SQLITE_IOCAP_ATOMIC8K]
1172 ** <li> [SQLITE_IOCAP_ATOMIC16K]
1173 ** <li> [SQLITE_IOCAP_ATOMIC32K]
1174 ** <li> [SQLITE_IOCAP_ATOMIC64K]
1175 ** <li> [SQLITE_IOCAP_SAFE_APPEND]
1176 ** <li> [SQLITE_IOCAP_SEQUENTIAL]
1177 ** </ul>
1178 **
1179 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
1180 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
1181 ** mean that writes of blocks that are nnn bytes in size and
1182 ** are aligned to an address which is an integer multiple of
1183 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
1184 ** that when data is appended to a file, the data is appended
1185 ** first then the size of the file is extended, never the other
1186 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
1187 ** information is written to disk in the same order as calls
1188 ** to xWrite().
1189 **
1190 ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
1191 ** in the unread portions of the buffer with zeros.  A VFS that
1192 ** fails to zero-fill short reads might seem to work.  However,
1193 ** failure to zero-fill short reads will eventually lead to
1194 ** database corruption.
1195 */
1196 typedef struct sqlite3_io_methods sqlite3_io_methods;
1197 struct sqlite3_io_methods {
1198   int iVersion;
1199   int (*xClose)(sqlite3_file*);
1200   int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
1201   int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
1202   int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
1203   int (*xSync)(sqlite3_file*, int flags);
1204   int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
1205   int (*xLock)(sqlite3_file*, int);
1206   int (*xUnlock)(sqlite3_file*, int);
1207   int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
1208   int (*xFileControl)(sqlite3_file*, int op, void *pArg);
1209   int (*xSectorSize)(sqlite3_file*);
1210   int (*xDeviceCharacteristics)(sqlite3_file*);
1211   /* Methods above are valid for version 1 */
1212   int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
1213   int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
1214   void (*xShmBarrier)(sqlite3_file*);
1215   int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
1216   /* Methods above are valid for version 2 */
1217   /* Additional methods may be added in future releases */
1218 };
1219
1220 /*
1221 ** CAPI3REF: Standard File Control Opcodes
1222 **
1223 ** These integer constants are opcodes for the xFileControl method
1224 ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
1225 ** interface.
1226 **
1227 ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
1228 ** opcode causes the xFileControl method to write the current state of
1229 ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
1230 ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
1231 ** into an integer that the pArg argument points to. This capability
1232 ** is used during testing and only needs to be supported when SQLITE_TEST
1233 ** is defined.
1234 **
1235 ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
1236 ** layer a hint of how large the database file will grow to be during the
1237 ** current transaction.  This hint is not guaranteed to be accurate but it
1238 ** is often close.  The underlying VFS might choose to preallocate database
1239 ** file space based on this hint in order to help writes to the database
1240 ** file run faster.
1241 **
1242 ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
1243 ** extends and truncates the database file in chunks of a size specified
1244 ** by the user. The fourth argument to [sqlite3_file_control()] should 
1245 ** point to an integer (type int) containing the new chunk-size to use
1246 ** for the nominated database. Allocating database file space in large
1247 ** chunks (say 1MB at a time), may reduce file-system fragmentation and
1248 ** improve performance on some systems.
1249 */
1250 #define SQLITE_FCNTL_LOCKSTATE        1
1251 #define SQLITE_GET_LOCKPROXYFILE      2
1252 #define SQLITE_SET_LOCKPROXYFILE      3
1253 #define SQLITE_LAST_ERRNO             4
1254 #define SQLITE_FCNTL_SIZE_HINT        5
1255 #define SQLITE_FCNTL_CHUNK_SIZE       6
1256
1257 /*
1258 ** CAPI3REF: Mutex Handle
1259 **
1260 ** The mutex module within SQLite defines [sqlite3_mutex] to be an
1261 ** abstract type for a mutex object.  The SQLite core never looks
1262 ** at the internal representation of an [sqlite3_mutex].  It only
1263 ** deals with pointers to the [sqlite3_mutex] object.
1264 **
1265 ** Mutexes are created using [sqlite3_mutex_alloc()].
1266 */
1267 typedef struct sqlite3_mutex sqlite3_mutex;
1268
1269 /*
1270 ** CAPI3REF: OS Interface Object
1271 **
1272 ** An instance of the sqlite3_vfs object defines the interface between
1273 ** the SQLite core and the underlying operating system.  The "vfs"
1274 ** in the name of the object stands for "virtual file system".
1275 **
1276 ** The value of the iVersion field is initially 1 but may be larger in
1277 ** future versions of SQLite.  Additional fields may be appended to this
1278 ** object when the iVersion value is increased.  Note that the structure
1279 ** of the sqlite3_vfs object changes in the transaction between
1280 ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
1281 ** modified.
1282 **
1283 ** The szOsFile field is the size of the subclassed [sqlite3_file]
1284 ** structure used by this VFS.  mxPathname is the maximum length of
1285 ** a pathname in this VFS.
1286 **
1287 ** Registered sqlite3_vfs objects are kept on a linked list formed by
1288 ** the pNext pointer.  The [sqlite3_vfs_register()]
1289 ** and [sqlite3_vfs_unregister()] interfaces manage this list
1290 ** in a thread-safe way.  The [sqlite3_vfs_find()] interface
1291 ** searches the list.  Neither the application code nor the VFS
1292 ** implementation should use the pNext pointer.
1293 **
1294 ** The pNext field is the only field in the sqlite3_vfs
1295 ** structure that SQLite will ever modify.  SQLite will only access
1296 ** or modify this field while holding a particular static mutex.
1297 ** The application should never modify anything within the sqlite3_vfs
1298 ** object once the object has been registered.
1299 **
1300 ** The zName field holds the name of the VFS module.  The name must
1301 ** be unique across all VFS modules.
1302 **
1303 ** ^SQLite guarantees that the zFilename parameter to xOpen
1304 ** is either a NULL pointer or string obtained
1305 ** from xFullPathname() with an optional suffix added.
1306 ** ^If a suffix is added to the zFilename parameter, it will
1307 ** consist of a single "-" character followed by no more than
1308 ** 10 alphanumeric and/or "-" characters.
1309 ** ^SQLite further guarantees that
1310 ** the string will be valid and unchanged until xClose() is
1311 ** called. Because of the previous sentence,
1312 ** the [sqlite3_file] can safely store a pointer to the
1313 ** filename if it needs to remember the filename for some reason.
1314 ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
1315 ** must invent its own temporary name for the file.  ^Whenever the 
1316 ** xFilename parameter is NULL it will also be the case that the
1317 ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
1318 **
1319 ** The flags argument to xOpen() includes all bits set in
1320 ** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
1321 ** or [sqlite3_open16()] is used, then flags includes at least
1322 ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. 
1323 ** If xOpen() opens a file read-only then it sets *pOutFlags to
1324 ** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be set.
1325 **
1326 ** ^(SQLite will also add one of the following flags to the xOpen()
1327 ** call, depending on the object being opened:
1328 **
1329 ** <ul>
1330 ** <li>  [SQLITE_OPEN_MAIN_DB]
1331 ** <li>  [SQLITE_OPEN_MAIN_JOURNAL]
1332 ** <li>  [SQLITE_OPEN_TEMP_DB]
1333 ** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
1334 ** <li>  [SQLITE_OPEN_TRANSIENT_DB]
1335 ** <li>  [SQLITE_OPEN_SUBJOURNAL]
1336 ** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
1337 ** <li>  [SQLITE_OPEN_WAL]
1338 ** </ul>)^
1339 **
1340 ** The file I/O implementation can use the object type flags to
1341 ** change the way it deals with files.  For example, an application
1342 ** that does not care about crash recovery or rollback might make
1343 ** the open of a journal file a no-op.  Writes to this journal would
1344 ** also be no-ops, and any attempt to read the journal would return
1345 ** SQLITE_IOERR.  Or the implementation might recognize that a database
1346 ** file will be doing page-aligned sector reads and writes in a random
1347 ** order and set up its I/O subsystem accordingly.
1348 **
1349 ** SQLite might also add one of the following flags to the xOpen method:
1350 **
1351 ** <ul>
1352 ** <li> [SQLITE_OPEN_DELETEONCLOSE]
1353 ** <li> [SQLITE_OPEN_EXCLUSIVE]
1354 ** </ul>
1355 **
1356 ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
1357 ** deleted when it is closed.  ^The [SQLITE_OPEN_DELETEONCLOSE]
1358 ** will be set for TEMP databases and their journals, transient
1359 ** databases, and subjournals.
1360 **
1361 ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
1362 ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
1363 ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
1364 ** API.  The SQLITE_OPEN_EXCLUSIVE flag, when paired with the 
1365 ** SQLITE_OPEN_CREATE, is used to indicate that file should always
1366 ** be created, and that it is an error if it already exists.
1367 ** It is <i>not</i> used to indicate the file should be opened 
1368 ** for exclusive access.
1369 **
1370 ** ^At least szOsFile bytes of memory are allocated by SQLite
1371 ** to hold the  [sqlite3_file] structure passed as the third
1372 ** argument to xOpen.  The xOpen method does not have to
1373 ** allocate the structure; it should just fill it in.  Note that
1374 ** the xOpen method must set the sqlite3_file.pMethods to either
1375 ** a valid [sqlite3_io_methods] object or to NULL.  xOpen must do
1376 ** this even if the open fails.  SQLite expects that the sqlite3_file.pMethods
1377 ** element will be valid after xOpen returns regardless of the success
1378 ** or failure of the xOpen call.
1379 **
1380 ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
1381 ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
1382 ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
1383 ** to test whether a file is at least readable.   The file can be a
1384 ** directory.
1385 **
1386 ** ^SQLite will always allocate at least mxPathname+1 bytes for the
1387 ** output buffer xFullPathname.  The exact size of the output buffer
1388 ** is also passed as a parameter to both  methods. If the output buffer
1389 ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
1390 ** handled as a fatal error by SQLite, vfs implementations should endeavor
1391 ** to prevent this by setting mxPathname to a sufficiently large value.
1392 **
1393 ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
1394 ** interfaces are not strictly a part of the filesystem, but they are
1395 ** included in the VFS structure for completeness.
1396 ** The xRandomness() function attempts to return nBytes bytes
1397 ** of good-quality randomness into zOut.  The return value is
1398 ** the actual number of bytes of randomness obtained.
1399 ** The xSleep() method causes the calling thread to sleep for at
1400 ** least the number of microseconds given.  ^The xCurrentTime()
1401 ** method returns a Julian Day Number for the current date and time as
1402 ** a floating point value.
1403 ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
1404 ** Day Number multipled by 86400000 (the number of milliseconds in 
1405 ** a 24-hour day).  
1406 ** ^SQLite will use the xCurrentTimeInt64() method to get the current
1407 ** date and time if that method is available (if iVersion is 2 or 
1408 ** greater and the function pointer is not NULL) and will fall back
1409 ** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
1410 */
1411 typedef struct sqlite3_vfs sqlite3_vfs;
1412 struct sqlite3_vfs {
1413   int iVersion;            /* Structure version number (currently 2) */
1414   int szOsFile;            /* Size of subclassed sqlite3_file */
1415   int mxPathname;          /* Maximum file pathname length */
1416   sqlite3_vfs *pNext;      /* Next registered VFS */
1417   const char *zName;       /* Name of this virtual file system */
1418   void *pAppData;          /* Pointer to application-specific data */
1419   int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
1420                int flags, int *pOutFlags);
1421   int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
1422   int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
1423   int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
1424   void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
1425   void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
1426   void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
1427   void (*xDlClose)(sqlite3_vfs*, void*);
1428   int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
1429   int (*xSleep)(sqlite3_vfs*, int microseconds);
1430   int (*xCurrentTime)(sqlite3_vfs*, double*);
1431   int (*xGetLastError)(sqlite3_vfs*, int, char *);
1432   /*
1433   ** The methods above are in version 1 of the sqlite_vfs object
1434   ** definition.  Those that follow are added in version 2 or later
1435   */
1436   int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
1437   /*
1438   ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
1439   ** New fields may be appended in figure versions.  The iVersion
1440   ** value will increment whenever this happens. 
1441   */
1442 };
1443
1444 /*
1445 ** CAPI3REF: Flags for the xAccess VFS method
1446 **
1447 ** These integer constants can be used as the third parameter to
1448 ** the xAccess method of an [sqlite3_vfs] object.  They determine
1449 ** what kind of permissions the xAccess method is looking for.
1450 ** With SQLITE_ACCESS_EXISTS, the xAccess method
1451 ** simply checks whether the file exists.
1452 ** With SQLITE_ACCESS_READWRITE, the xAccess method
1453 ** checks whether the named directory is both readable and writable
1454 ** (in other words, if files can be added, removed, and renamed within
1455 ** the directory).
1456 ** The SQLITE_ACCESS_READWRITE constant is currently used only by the
1457 ** [temp_store_directory pragma], though this could change in a future
1458 ** release of SQLite.
1459 ** With SQLITE_ACCESS_READ, the xAccess method
1460 ** checks whether the file is readable.  The SQLITE_ACCESS_READ constant is
1461 ** currently unused, though it might be used in a future release of
1462 ** SQLite.
1463 */
1464 #define SQLITE_ACCESS_EXISTS    0
1465 #define SQLITE_ACCESS_READWRITE 1   /* Used by PRAGMA temp_store_directory */
1466 #define SQLITE_ACCESS_READ      2   /* Unused */
1467
1468 /*
1469 ** CAPI3REF: Flags for the xShmLock VFS method
1470 **
1471 ** These integer constants define the various locking operations
1472 ** allowed by the xShmLock method of [sqlite3_io_methods].  The
1473 ** following are the only legal combinations of flags to the
1474 ** xShmLock method:
1475 **
1476 ** <ul>
1477 ** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
1478 ** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
1479 ** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
1480 ** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
1481 ** </ul>
1482 **
1483 ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
1484 ** was given no the corresponding lock.  
1485 **
1486 ** The xShmLock method can transition between unlocked and SHARED or
1487 ** between unlocked and EXCLUSIVE.  It cannot transition between SHARED
1488 ** and EXCLUSIVE.
1489 */
1490 #define SQLITE_SHM_UNLOCK       1
1491 #define SQLITE_SHM_LOCK         2
1492 #define SQLITE_SHM_SHARED       4
1493 #define SQLITE_SHM_EXCLUSIVE    8
1494
1495 /*
1496 ** CAPI3REF: Maximum xShmLock index
1497 **
1498 ** The xShmLock method on [sqlite3_io_methods] may use values
1499 ** between 0 and this upper bound as its "offset" argument.
1500 ** The SQLite core will never attempt to acquire or release a
1501 ** lock outside of this range
1502 */
1503 #define SQLITE_SHM_NLOCK        8
1504
1505
1506 /*
1507 ** CAPI3REF: Initialize The SQLite Library
1508 **
1509 ** ^The sqlite3_initialize() routine initializes the
1510 ** SQLite library.  ^The sqlite3_shutdown() routine
1511 ** deallocates any resources that were allocated by sqlite3_initialize().
1512 ** These routines are designed to aid in process initialization and
1513 ** shutdown on embedded systems.  Workstation applications using
1514 ** SQLite normally do not need to invoke either of these routines.
1515 **
1516 ** A call to sqlite3_initialize() is an "effective" call if it is
1517 ** the first time sqlite3_initialize() is invoked during the lifetime of
1518 ** the process, or if it is the first time sqlite3_initialize() is invoked
1519 ** following a call to sqlite3_shutdown().  ^(Only an effective call
1520 ** of sqlite3_initialize() does any initialization.  All other calls
1521 ** are harmless no-ops.)^
1522 **
1523 ** A call to sqlite3_shutdown() is an "effective" call if it is the first
1524 ** call to sqlite3_shutdown() since the last sqlite3_initialize().  ^(Only
1525 ** an effective call to sqlite3_shutdown() does any deinitialization.
1526 ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
1527 **
1528 ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
1529 ** is not.  The sqlite3_shutdown() interface must only be called from a
1530 ** single thread.  All open [database connections] must be closed and all
1531 ** other SQLite resources must be deallocated prior to invoking
1532 ** sqlite3_shutdown().
1533 **
1534 ** Among other things, ^sqlite3_initialize() will invoke
1535 ** sqlite3_os_init().  Similarly, ^sqlite3_shutdown()
1536 ** will invoke sqlite3_os_end().
1537 **
1538 ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
1539 ** ^If for some reason, sqlite3_initialize() is unable to initialize
1540 ** the library (perhaps it is unable to allocate a needed resource such
1541 ** as a mutex) it returns an [error code] other than [SQLITE_OK].
1542 **
1543 ** ^The sqlite3_initialize() routine is called internally by many other
1544 ** SQLite interfaces so that an application usually does not need to
1545 ** invoke sqlite3_initialize() directly.  For example, [sqlite3_open()]
1546 ** calls sqlite3_initialize() so the SQLite library will be automatically
1547 ** initialized when [sqlite3_open()] is called if it has not be initialized
1548 ** already.  ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
1549 ** compile-time option, then the automatic calls to sqlite3_initialize()
1550 ** are omitted and the application must call sqlite3_initialize() directly
1551 ** prior to using any other SQLite interface.  For maximum portability,
1552 ** it is recommended that applications always invoke sqlite3_initialize()
1553 ** directly prior to using any other SQLite interface.  Future releases
1554 ** of SQLite may require this.  In other words, the behavior exhibited
1555 ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
1556 ** default behavior in some future release of SQLite.
1557 **
1558 ** The sqlite3_os_init() routine does operating-system specific
1559 ** initialization of the SQLite library.  The sqlite3_os_end()
1560 ** routine undoes the effect of sqlite3_os_init().  Typical tasks
1561 ** performed by these routines include allocation or deallocation
1562 ** of static resources, initialization of global variables,
1563 ** setting up a default [sqlite3_vfs] module, or setting up
1564 ** a default configuration using [sqlite3_config()].
1565 **
1566 ** The application should never invoke either sqlite3_os_init()
1567 ** or sqlite3_os_end() directly.  The application should only invoke
1568 ** sqlite3_initialize() and sqlite3_shutdown().  The sqlite3_os_init()
1569 ** interface is called automatically by sqlite3_initialize() and
1570 ** sqlite3_os_end() is called by sqlite3_shutdown().  Appropriate
1571 ** implementations for sqlite3_os_init() and sqlite3_os_end()
1572 ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
1573 ** When [custom builds | built for other platforms]
1574 ** (using the [SQLITE_OS_OTHER=1] compile-time
1575 ** option) the application must supply a suitable implementation for
1576 ** sqlite3_os_init() and sqlite3_os_end().  An application-supplied
1577 ** implementation of sqlite3_os_init() or sqlite3_os_end()
1578 ** must return [SQLITE_OK] on success and some other [error code] upon
1579 ** failure.
1580 */
1581 SQLITE_API int sqlite3_initialize(void);
1582 SQLITE_API int sqlite3_shutdown(void);
1583 SQLITE_API int sqlite3_os_init(void);
1584 SQLITE_API int sqlite3_os_end(void);
1585
1586 /*
1587 ** CAPI3REF: Configuring The SQLite Library
1588 **
1589 ** The sqlite3_config() interface is used to make global configuration
1590 ** changes to SQLite in order to tune SQLite to the specific needs of
1591 ** the application.  The default configuration is recommended for most
1592 ** applications and so this routine is usually not necessary.  It is
1593 ** provided to support rare applications with unusual needs.
1594 **
1595 ** The sqlite3_config() interface is not threadsafe.  The application
1596 ** must insure that no other SQLite interfaces are invoked by other
1597 ** threads while sqlite3_config() is running.  Furthermore, sqlite3_config()
1598 ** may only be invoked prior to library initialization using
1599 ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
1600 ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
1601 ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
1602 ** Note, however, that ^sqlite3_config() can be called as part of the
1603 ** implementation of an application-defined [sqlite3_os_init()].
1604 **
1605 ** The first argument to sqlite3_config() is an integer
1606 ** [SQLITE_CONFIG_SINGLETHREAD | configuration option] that determines
1607 ** what property of SQLite is to be configured.  Subsequent arguments
1608 ** vary depending on the [SQLITE_CONFIG_SINGLETHREAD | configuration option]
1609 ** in the first argument.
1610 **
1611 ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
1612 ** ^If the option is unknown or SQLite is unable to set the option
1613 ** then this routine returns a non-zero [error code].
1614 */
1615 SQLITE_API int sqlite3_config(int, ...);
1616
1617 /*
1618 ** CAPI3REF: Configure database connections
1619 **
1620 ** The sqlite3_db_config() interface is used to make configuration
1621 ** changes to a [database connection].  The interface is similar to
1622 ** [sqlite3_config()] except that the changes apply to a single
1623 ** [database connection] (specified in the first argument).  The
1624 ** sqlite3_db_config() interface should only be used immediately after
1625 ** the database connection is created using [sqlite3_open()],
1626 ** [sqlite3_open16()], or [sqlite3_open_v2()].  
1627 **
1628 ** The second argument to sqlite3_db_config(D,V,...)  is the
1629 ** configuration verb - an integer code that indicates what
1630 ** aspect of the [database connection] is being configured.
1631 ** The only choice for this value is [SQLITE_DBCONFIG_LOOKASIDE].
1632 ** New verbs are likely to be added in future releases of SQLite.
1633 ** Additional arguments depend on the verb.
1634 **
1635 ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
1636 ** the call is considered successful.
1637 */
1638 SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
1639
1640 /*
1641 ** CAPI3REF: Memory Allocation Routines
1642 **
1643 ** An instance of this object defines the interface between SQLite
1644 ** and low-level memory allocation routines.
1645 **
1646 ** This object is used in only one place in the SQLite interface.
1647 ** A pointer to an instance of this object is the argument to
1648 ** [sqlite3_config()] when the configuration option is
1649 ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].  
1650 ** By creating an instance of this object
1651 ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
1652 ** during configuration, an application can specify an alternative
1653 ** memory allocation subsystem for SQLite to use for all of its
1654 ** dynamic memory needs.
1655 **
1656 ** Note that SQLite comes with several [built-in memory allocators]
1657 ** that are perfectly adequate for the overwhelming majority of applications
1658 ** and that this object is only useful to a tiny minority of applications
1659 ** with specialized memory allocation requirements.  This object is
1660 ** also used during testing of SQLite in order to specify an alternative
1661 ** memory allocator that simulates memory out-of-memory conditions in
1662 ** order to verify that SQLite recovers gracefully from such
1663 ** conditions.
1664 **
1665 ** The xMalloc and xFree methods must work like the
1666 ** malloc() and free() functions from the standard C library.
1667 ** The xRealloc method must work like realloc() from the standard C library
1668 ** with the exception that if the second argument to xRealloc is zero,
1669 ** xRealloc must be a no-op - it must not perform any allocation or
1670 ** deallocation.  ^SQLite guarantees that the second argument to
1671 ** xRealloc is always a value returned by a prior call to xRoundup.
1672 ** And so in cases where xRoundup always returns a positive number,
1673 ** xRealloc can perform exactly as the standard library realloc() and
1674 ** still be in compliance with this specification.
1675 **
1676 ** xSize should return the allocated size of a memory allocation
1677 ** previously obtained from xMalloc or xRealloc.  The allocated size
1678 ** is always at least as big as the requested size but may be larger.
1679 **
1680 ** The xRoundup method returns what would be the allocated size of
1681 ** a memory allocation given a particular requested size.  Most memory
1682 ** allocators round up memory allocations at least to the next multiple
1683 ** of 8.  Some allocators round up to a larger multiple or to a power of 2.
1684 ** Every memory allocation request coming in through [sqlite3_malloc()]
1685 ** or [sqlite3_realloc()] first calls xRoundup.  If xRoundup returns 0, 
1686 ** that causes the corresponding memory allocation to fail.
1687 **
1688 ** The xInit method initializes the memory allocator.  (For example,
1689 ** it might allocate any require mutexes or initialize internal data
1690 ** structures.  The xShutdown method is invoked (indirectly) by
1691 ** [sqlite3_shutdown()] and should deallocate any resources acquired
1692 ** by xInit.  The pAppData pointer is used as the only parameter to
1693 ** xInit and xShutdown.
1694 **
1695 ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
1696 ** the xInit method, so the xInit method need not be threadsafe.  The
1697 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
1698 ** not need to be threadsafe either.  For all other methods, SQLite
1699 ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
1700 ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
1701 ** it is by default) and so the methods are automatically serialized.
1702 ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
1703 ** methods must be threadsafe or else make their own arrangements for
1704 ** serialization.
1705 **
1706 ** SQLite will never invoke xInit() more than once without an intervening
1707 ** call to xShutdown().
1708 */
1709 typedef struct sqlite3_mem_methods sqlite3_mem_methods;
1710 struct sqlite3_mem_methods {
1711   void *(*xMalloc)(int);         /* Memory allocation function */
1712   void (*xFree)(void*);          /* Free a prior allocation */
1713   void *(*xRealloc)(void*,int);  /* Resize an allocation */
1714   int (*xSize)(void*);           /* Return the size of an allocation */
1715   int (*xRoundup)(int);          /* Round up request size to allocation size */
1716   int (*xInit)(void*);           /* Initialize the memory allocator */
1717   void (*xShutdown)(void*);      /* Deinitialize the memory allocator */
1718   void *pAppData;                /* Argument to xInit() and xShutdown() */
1719 };
1720
1721 /*
1722 ** CAPI3REF: Configuration Options
1723 **
1724 ** These constants are the available integer configuration options that
1725 ** can be passed as the first argument to the [sqlite3_config()] interface.
1726 **
1727 ** New configuration options may be added in future releases of SQLite.
1728 ** Existing configuration options might be discontinued.  Applications
1729 ** should check the return code from [sqlite3_config()] to make sure that
1730 ** the call worked.  The [sqlite3_config()] interface will return a
1731 ** non-zero [error code] if a discontinued or unsupported configuration option
1732 ** is invoked.
1733 **
1734 ** <dl>
1735 ** <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
1736 ** <dd>There are no arguments to this option.  ^This option sets the
1737 ** [threading mode] to Single-thread.  In other words, it disables
1738 ** all mutexing and puts SQLite into a mode where it can only be used
1739 ** by a single thread.   ^If SQLite is compiled with
1740 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1741 ** it is not possible to change the [threading mode] from its default
1742 ** value of Single-thread and so [sqlite3_config()] will return 
1743 ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
1744 ** configuration option.</dd>
1745 **
1746 ** <dt>SQLITE_CONFIG_MULTITHREAD</dt>
1747 ** <dd>There are no arguments to this option.  ^This option sets the
1748 ** [threading mode] to Multi-thread.  In other words, it disables
1749 ** mutexing on [database connection] and [prepared statement] objects.
1750 ** The application is responsible for serializing access to
1751 ** [database connections] and [prepared statements].  But other mutexes
1752 ** are enabled so that SQLite will be safe to use in a multi-threaded
1753 ** environment as long as no two threads attempt to use the same
1754 ** [database connection] at the same time.  ^If SQLite is compiled with
1755 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1756 ** it is not possible to set the Multi-thread [threading mode] and
1757 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1758 ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
1759 **
1760 ** <dt>SQLITE_CONFIG_SERIALIZED</dt>
1761 ** <dd>There are no arguments to this option.  ^This option sets the
1762 ** [threading mode] to Serialized. In other words, this option enables
1763 ** all mutexes including the recursive
1764 ** mutexes on [database connection] and [prepared statement] objects.
1765 ** In this mode (which is the default when SQLite is compiled with
1766 ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
1767 ** to [database connections] and [prepared statements] so that the
1768 ** application is free to use the same [database connection] or the
1769 ** same [prepared statement] in different threads at the same time.
1770 ** ^If SQLite is compiled with
1771 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1772 ** it is not possible to set the Serialized [threading mode] and
1773 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1774 ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
1775 **
1776 ** <dt>SQLITE_CONFIG_MALLOC</dt>
1777 ** <dd> ^(This option takes a single argument which is a pointer to an
1778 ** instance of the [sqlite3_mem_methods] structure.  The argument specifies
1779 ** alternative low-level memory allocation routines to be used in place of
1780 ** the memory allocation routines built into SQLite.)^ ^SQLite makes
1781 ** its own private copy of the content of the [sqlite3_mem_methods] structure
1782 ** before the [sqlite3_config()] call returns.</dd>
1783 **
1784 ** <dt>SQLITE_CONFIG_GETMALLOC</dt>
1785 ** <dd> ^(This option takes a single argument which is a pointer to an
1786 ** instance of the [sqlite3_mem_methods] structure.  The [sqlite3_mem_methods]
1787 ** structure is filled with the currently defined memory allocation routines.)^
1788 ** This option can be used to overload the default memory allocation
1789 ** routines with a wrapper that simulations memory allocation failure or
1790 ** tracks memory usage, for example. </dd>
1791 **
1792 ** <dt>SQLITE_CONFIG_MEMSTATUS</dt>
1793 ** <dd> ^This option takes single argument of type int, interpreted as a 
1794 ** boolean, which enables or disables the collection of memory allocation 
1795 ** statistics. ^(When memory allocation statistics are disabled, the 
1796 ** following SQLite interfaces become non-operational:
1797 **   <ul>
1798 **   <li> [sqlite3_memory_used()]
1799 **   <li> [sqlite3_memory_highwater()]
1800 **   <li> [sqlite3_soft_heap_limit64()]
1801 **   <li> [sqlite3_status()]
1802 **   </ul>)^
1803 ** ^Memory allocation statistics are enabled by default unless SQLite is
1804 ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
1805 ** allocation statistics are disabled by default.
1806 ** </dd>
1807 **
1808 ** <dt>SQLITE_CONFIG_SCRATCH</dt>
1809 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
1810 ** scratch memory.  There are three arguments:  A pointer an 8-byte
1811 ** aligned memory buffer from which the scrach allocations will be
1812 ** drawn, the size of each scratch allocation (sz),
1813 ** and the maximum number of scratch allocations (N).  The sz
1814 ** argument must be a multiple of 16.
1815 ** The first argument must be a pointer to an 8-byte aligned buffer
1816 ** of at least sz*N bytes of memory.
1817 ** ^SQLite will use no more than two scratch buffers per thread.  So
1818 ** N should be set to twice the expected maximum number of threads.
1819 ** ^SQLite will never require a scratch buffer that is more than 6
1820 ** times the database page size. ^If SQLite needs needs additional
1821 ** scratch memory beyond what is provided by this configuration option, then 
1822 ** [sqlite3_malloc()] will be used to obtain the memory needed.</dd>
1823 **
1824 ** <dt>SQLITE_CONFIG_PAGECACHE</dt>
1825 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
1826 ** the database page cache with the default page cache implemenation.  
1827 ** This configuration should not be used if an application-define page
1828 ** cache implementation is loaded using the SQLITE_CONFIG_PCACHE option.
1829 ** There are three arguments to this option: A pointer to 8-byte aligned
1830 ** memory, the size of each page buffer (sz), and the number of pages (N).
1831 ** The sz argument should be the size of the largest database page
1832 ** (a power of two between 512 and 32768) plus a little extra for each
1833 ** page header.  ^The page header size is 20 to 40 bytes depending on
1834 ** the host architecture.  ^It is harmless, apart from the wasted memory,
1835 ** to make sz a little too large.  The first
1836 ** argument should point to an allocation of at least sz*N bytes of memory.
1837 ** ^SQLite will use the memory provided by the first argument to satisfy its
1838 ** memory needs for the first N pages that it adds to cache.  ^If additional
1839 ** page cache memory is needed beyond what is provided by this option, then
1840 ** SQLite goes to [sqlite3_malloc()] for the additional storage space.
1841 ** The pointer in the first argument must
1842 ** be aligned to an 8-byte boundary or subsequent behavior of SQLite
1843 ** will be undefined.</dd>
1844 **
1845 ** <dt>SQLITE_CONFIG_HEAP</dt>
1846 ** <dd> ^This option specifies a static memory buffer that SQLite will use
1847 ** for all of its dynamic memory allocation needs beyond those provided
1848 ** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE].
1849 ** There are three arguments: An 8-byte aligned pointer to the memory,
1850 ** the number of bytes in the memory buffer, and the minimum allocation size.
1851 ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
1852 ** to using its default memory allocator (the system malloc() implementation),
1853 ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC].  ^If the
1854 ** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or
1855 ** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory
1856 ** allocator is engaged to handle all of SQLites memory allocation needs.
1857 ** The first pointer (the memory pointer) must be aligned to an 8-byte
1858 ** boundary or subsequent behavior of SQLite will be undefined.</dd>
1859 **
1860 ** <dt>SQLITE_CONFIG_MUTEX</dt>
1861 ** <dd> ^(This option takes a single argument which is a pointer to an
1862 ** instance of the [sqlite3_mutex_methods] structure.  The argument specifies
1863 ** alternative low-level mutex routines to be used in place
1864 ** the mutex routines built into SQLite.)^  ^SQLite makes a copy of the
1865 ** content of the [sqlite3_mutex_methods] structure before the call to
1866 ** [sqlite3_config()] returns. ^If SQLite is compiled with
1867 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1868 ** the entire mutexing subsystem is omitted from the build and hence calls to
1869 ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
1870 ** return [SQLITE_ERROR].</dd>
1871 **
1872 ** <dt>SQLITE_CONFIG_GETMUTEX</dt>
1873 ** <dd> ^(This option takes a single argument which is a pointer to an
1874 ** instance of the [sqlite3_mutex_methods] structure.  The
1875 ** [sqlite3_mutex_methods]
1876 ** structure is filled with the currently defined mutex routines.)^
1877 ** This option can be used to overload the default mutex allocation
1878 ** routines with a wrapper used to track mutex usage for performance
1879 ** profiling or testing, for example.   ^If SQLite is compiled with
1880 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1881 ** the entire mutexing subsystem is omitted from the build and hence calls to
1882 ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
1883 ** return [SQLITE_ERROR].</dd>
1884 **
1885 ** <dt>SQLITE_CONFIG_LOOKASIDE</dt>
1886 ** <dd> ^(This option takes two arguments that determine the default
1887 ** memory allocation for the lookaside memory allocator on each
1888 ** [database connection].  The first argument is the
1889 ** size of each lookaside buffer slot and the second is the number of
1890 ** slots allocated to each database connection.)^  ^(This option sets the
1891 ** <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
1892 ** verb to [sqlite3_db_config()] can be used to change the lookaside
1893 ** configuration on individual connections.)^ </dd>
1894 **
1895 ** <dt>SQLITE_CONFIG_PCACHE</dt>
1896 ** <dd> ^(This option takes a single argument which is a pointer to
1897 ** an [sqlite3_pcache_methods] object.  This object specifies the interface
1898 ** to a custom page cache implementation.)^  ^SQLite makes a copy of the
1899 ** object and uses it for page cache memory allocations.</dd>
1900 **
1901 ** <dt>SQLITE_CONFIG_GETPCACHE</dt>
1902 ** <dd> ^(This option takes a single argument which is a pointer to an
1903 ** [sqlite3_pcache_methods] object.  SQLite copies of the current
1904 ** page cache implementation into that object.)^ </dd>
1905 **
1906 ** <dt>SQLITE_CONFIG_LOG</dt>
1907 ** <dd> ^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
1908 ** function with a call signature of void(*)(void*,int,const char*), 
1909 ** and a pointer to void. ^If the function pointer is not NULL, it is
1910 ** invoked by [sqlite3_log()] to process each logging event.  ^If the
1911 ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
1912 ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
1913 ** passed through as the first parameter to the application-defined logger
1914 ** function whenever that function is invoked.  ^The second parameter to
1915 ** the logger function is a copy of the first parameter to the corresponding
1916 ** [sqlite3_log()] call and is intended to be a [result code] or an
1917 ** [extended result code].  ^The third parameter passed to the logger is
1918 ** log message after formatting via [sqlite3_snprintf()].
1919 ** The SQLite logging interface is not reentrant; the logger function
1920 ** supplied by the application must not invoke any SQLite interface.
1921 ** In a multi-threaded application, the application-defined logger
1922 ** function must be threadsafe. </dd>
1923 **
1924 ** </dl>
1925 */
1926 #define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */
1927 #define SQLITE_CONFIG_MULTITHREAD   2  /* nil */
1928 #define SQLITE_CONFIG_SERIALIZED    3  /* nil */
1929 #define SQLITE_CONFIG_MALLOC        4  /* sqlite3_mem_methods* */
1930 #define SQLITE_CONFIG_GETMALLOC     5  /* sqlite3_mem_methods* */
1931 #define SQLITE_CONFIG_SCRATCH       6  /* void*, int sz, int N */
1932 #define SQLITE_CONFIG_PAGECACHE     7  /* void*, int sz, int N */
1933 #define SQLITE_CONFIG_HEAP          8  /* void*, int nByte, int min */
1934 #define SQLITE_CONFIG_MEMSTATUS     9  /* boolean */
1935 #define SQLITE_CONFIG_MUTEX        10  /* sqlite3_mutex_methods* */
1936 #define SQLITE_CONFIG_GETMUTEX     11  /* sqlite3_mutex_methods* */
1937 /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */ 
1938 #define SQLITE_CONFIG_LOOKASIDE    13  /* int int */
1939 #define SQLITE_CONFIG_PCACHE       14  /* sqlite3_pcache_methods* */
1940 #define SQLITE_CONFIG_GETPCACHE    15  /* sqlite3_pcache_methods* */
1941 #define SQLITE_CONFIG_LOG          16  /* xFunc, void* */
1942
1943 /*
1944 ** CAPI3REF: Database Connection Configuration Options
1945 **
1946 ** These constants are the available integer configuration options that
1947 ** can be passed as the second argument to the [sqlite3_db_config()] interface.
1948 **
1949 ** New configuration options may be added in future releases of SQLite.
1950 ** Existing configuration options might be discontinued.  Applications
1951 ** should check the return code from [sqlite3_db_config()] to make sure that
1952 ** the call worked.  ^The [sqlite3_db_config()] interface will return a
1953 ** non-zero [error code] if a discontinued or unsupported configuration option
1954 ** is invoked.
1955 **
1956 ** <dl>
1957 ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
1958 ** <dd> ^This option takes three additional arguments that determine the 
1959 ** [lookaside memory allocator] configuration for the [database connection].
1960 ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
1961 ** pointer to an memory buffer to use for lookaside memory.
1962 ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
1963 ** may be NULL in which case SQLite will allocate the
1964 ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
1965 ** size of each lookaside buffer slot.  ^The third argument is the number of
1966 ** slots.  The size of the buffer in the first argument must be greater than
1967 ** or equal to the product of the second and third arguments.  The buffer
1968 ** must be aligned to an 8-byte boundary.  ^If the second argument to
1969 ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
1970 ** rounded down to the next smaller multiple of 8.  ^(The lookaside memory
1971 ** configuration for a database connection can only be changed when that
1972 ** connection is not currently using lookaside memory, or in other words
1973 ** when the "current value" returned by
1974 ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
1975 ** Any attempt to change the lookaside memory configuration when lookaside
1976 ** memory is in use leaves the configuration unchanged and returns 
1977 ** [SQLITE_BUSY].)^</dd>
1978 **
1979 ** </dl>
1980 */
1981 #define SQLITE_DBCONFIG_LOOKASIDE    1001  /* void* int int */
1982
1983
1984 /*
1985 ** CAPI3REF: Enable Or Disable Extended Result Codes
1986 **
1987 ** ^The sqlite3_extended_result_codes() routine enables or disables the
1988 ** [extended result codes] feature of SQLite. ^The extended result
1989 ** codes are disabled by default for historical compatibility.
1990 */
1991 SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
1992
1993 /*
1994 ** CAPI3REF: Last Insert Rowid
1995 **
1996 ** ^Each entry in an SQLite table has a unique 64-bit signed
1997 ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
1998 ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
1999 ** names are not also used by explicitly declared columns. ^If
2000 ** the table has a column of type [INTEGER PRIMARY KEY] then that column
2001 ** is another alias for the rowid.
2002 **
2003 ** ^This routine returns the [rowid] of the most recent
2004 ** successful [INSERT] into the database from the [database connection]
2005 ** in the first argument.  ^If no successful [INSERT]s
2006 ** have ever occurred on that database connection, zero is returned.
2007 **
2008 ** ^(If an [INSERT] occurs within a trigger, then the [rowid] of the inserted
2009 ** row is returned by this routine as long as the trigger is running.
2010 ** But once the trigger terminates, the value returned by this routine
2011 ** reverts to the last value inserted before the trigger fired.)^
2012 **
2013 ** ^An [INSERT] that fails due to a constraint violation is not a
2014 ** successful [INSERT] and does not change the value returned by this
2015 ** routine.  ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
2016 ** and INSERT OR ABORT make no changes to the return value of this
2017 ** routine when their insertion fails.  ^(When INSERT OR REPLACE
2018 ** encounters a constraint violation, it does not fail.  The
2019 ** INSERT continues to completion after deleting rows that caused
2020 ** the constraint problem so INSERT OR REPLACE will always change
2021 ** the return value of this interface.)^
2022 **
2023 ** ^For the purposes of this routine, an [INSERT] is considered to
2024 ** be successful even if it is subsequently rolled back.
2025 **
2026 ** This function is accessible to SQL statements via the
2027 ** [last_insert_rowid() SQL function].
2028 **
2029 ** If a separate thread performs a new [INSERT] on the same
2030 ** database connection while the [sqlite3_last_insert_rowid()]
2031 ** function is running and thus changes the last insert [rowid],
2032 ** then the value returned by [sqlite3_last_insert_rowid()] is
2033 ** unpredictable and might not equal either the old or the new
2034 ** last insert [rowid].
2035 */
2036 SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
2037
2038 /*
2039 ** CAPI3REF: Count The Number Of Rows Modified
2040 **
2041 ** ^This function returns the number of database rows that were changed
2042 ** or inserted or deleted by the most recently completed SQL statement
2043 ** on the [database connection] specified by the first parameter.
2044 ** ^(Only changes that are directly specified by the [INSERT], [UPDATE],
2045 ** or [DELETE] statement are counted.  Auxiliary changes caused by
2046 ** triggers or [foreign key actions] are not counted.)^ Use the
2047 ** [sqlite3_total_changes()] function to find the total number of changes
2048 ** including changes caused by triggers and foreign key actions.
2049 **
2050 ** ^Changes to a view that are simulated by an [INSTEAD OF trigger]
2051 ** are not counted.  Only real table changes are counted.
2052 **
2053 ** ^(A "row change" is a change to a single row of a single table
2054 ** caused by an INSERT, DELETE, or UPDATE statement.  Rows that
2055 ** are changed as side effects of [REPLACE] constraint resolution,
2056 ** rollback, ABORT processing, [DROP TABLE], or by any other
2057 ** mechanisms do not count as direct row changes.)^
2058 **
2059 ** A "trigger context" is a scope of execution that begins and
2060 ** ends with the script of a [CREATE TRIGGER | trigger]. 
2061 ** Most SQL statements are
2062 ** evaluated outside of any trigger.  This is the "top level"
2063 ** trigger context.  If a trigger fires from the top level, a
2064 ** new trigger context is entered for the duration of that one
2065 ** trigger.  Subtriggers create subcontexts for their duration.
2066 **
2067 ** ^Calling [sqlite3_exec()] or [sqlite3_step()] recursively does
2068 ** not create a new trigger context.
2069 **
2070 ** ^This function returns the number of direct row changes in the
2071 ** most recent INSERT, UPDATE, or DELETE statement within the same
2072 ** trigger context.
2073 **
2074 ** ^Thus, when called from the top level, this function returns the
2075 ** number of changes in the most recent INSERT, UPDATE, or DELETE
2076 ** that also occurred at the top level.  ^(Within the body of a trigger,
2077 ** the sqlite3_changes() interface can be called to find the number of
2078 ** changes in the most recently completed INSERT, UPDATE, or DELETE
2079 ** statement within the body of the same trigger.
2080 ** However, the number returned does not include changes
2081 ** caused by subtriggers since those have their own context.)^
2082 **
2083 ** See also the [sqlite3_total_changes()] interface, the
2084 ** [count_changes pragma], and the [changes() SQL function].
2085 **
2086 ** If a separate thread makes changes on the same database connection
2087 ** while [sqlite3_changes()] is running then the value returned
2088 ** is unpredictable and not meaningful.
2089 */
2090 SQLITE_API int sqlite3_changes(sqlite3*);
2091
2092 /*
2093 ** CAPI3REF: Total Number Of Rows Modified
2094 **
2095 ** ^This function returns the number of row changes caused by [INSERT],
2096 ** [UPDATE] or [DELETE] statements since the [database connection] was opened.
2097 ** ^(The count returned by sqlite3_total_changes() includes all changes
2098 ** from all [CREATE TRIGGER | trigger] contexts and changes made by
2099 ** [foreign key actions]. However,
2100 ** the count does not include changes used to implement [REPLACE] constraints,
2101 ** do rollbacks or ABORT processing, or [DROP TABLE] processing.  The
2102 ** count does not include rows of views that fire an [INSTEAD OF trigger],
2103 ** though if the INSTEAD OF trigger makes changes of its own, those changes 
2104 ** are counted.)^
2105 ** ^The sqlite3_total_changes() function counts the changes as soon as
2106 ** the statement that makes them is completed (when the statement handle
2107 ** is passed to [sqlite3_reset()] or [sqlite3_finalize()]).
2108 **
2109 ** See also the [sqlite3_changes()] interface, the
2110 ** [count_changes pragma], and the [total_changes() SQL function].
2111 **
2112 ** If a separate thread makes changes on the same database connection
2113 ** while [sqlite3_total_changes()] is running then the value
2114 ** returned is unpredictable and not meaningful.
2115 */
2116 SQLITE_API int sqlite3_total_changes(sqlite3*);
2117
2118 /*
2119 ** CAPI3REF: Interrupt A Long-Running Query
2120 **
2121 ** ^This function causes any pending database operation to abort and
2122 ** return at its earliest opportunity. This routine is typically
2123 ** called in response to a user action such as pressing "Cancel"
2124 ** or Ctrl-C where the user wants a long query operation to halt
2125 ** immediately.
2126 **
2127 ** ^It is safe to call this routine from a thread different from the
2128 ** thread that is currently running the database operation.  But it
2129 ** is not safe to call this routine with a [database connection] that
2130 ** is closed or might close before sqlite3_interrupt() returns.
2131 **
2132 ** ^If an SQL operation is very nearly finished at the time when
2133 ** sqlite3_interrupt() is called, then it might not have an opportunity
2134 ** to be interrupted and might continue to completion.
2135 **
2136 ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
2137 ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
2138 ** that is inside an explicit transaction, then the entire transaction
2139 ** will be rolled back automatically.
2140 **
2141 ** ^The sqlite3_interrupt(D) call is in effect until all currently running
2142 ** SQL statements on [database connection] D complete.  ^Any new SQL statements
2143 ** that are started after the sqlite3_interrupt() call and before the 
2144 ** running statements reaches zero are interrupted as if they had been
2145 ** running prior to the sqlite3_interrupt() call.  ^New SQL statements
2146 ** that are started after the running statement count reaches zero are
2147 ** not effected by the sqlite3_interrupt().
2148 ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
2149 ** SQL statements is a no-op and has no effect on SQL statements
2150 ** that are started after the sqlite3_interrupt() call returns.
2151 **
2152 ** If the database connection closes while [sqlite3_interrupt()]
2153 ** is running then bad things will likely happen.
2154 */
2155 SQLITE_API void sqlite3_interrupt(sqlite3*);
2156
2157 /*
2158 ** CAPI3REF: Determine If An SQL Statement Is Complete
2159 **
2160 ** These routines are useful during command-line input to determine if the
2161 ** currently entered text seems to form a complete SQL statement or
2162 ** if additional input is needed before sending the text into
2163 ** SQLite for parsing.  ^These routines return 1 if the input string
2164 ** appears to be a complete SQL statement.  ^A statement is judged to be
2165 ** complete if it ends with a semicolon token and is not a prefix of a
2166 ** well-formed CREATE TRIGGER statement.  ^Semicolons that are embedded within
2167 ** string literals or quoted identifier names or comments are not
2168 ** independent tokens (they are part of the token in which they are
2169 ** embedded) and thus do not count as a statement terminator.  ^Whitespace
2170 ** and comments that follow the final semicolon are ignored.
2171 **
2172 ** ^These routines return 0 if the statement is incomplete.  ^If a
2173 ** memory allocation fails, then SQLITE_NOMEM is returned.
2174 **
2175 ** ^These routines do not parse the SQL statements thus
2176 ** will not detect syntactically incorrect SQL.
2177 **
2178 ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior 
2179 ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
2180 ** automatically by sqlite3_complete16().  If that initialization fails,
2181 ** then the return value from sqlite3_complete16() will be non-zero
2182 ** regardless of whether or not the input SQL is complete.)^
2183 **
2184 ** The input to [sqlite3_complete()] must be a zero-terminated
2185 ** UTF-8 string.
2186 **
2187 ** The input to [sqlite3_complete16()] must be a zero-terminated
2188 ** UTF-16 string in native byte order.
2189 */
2190 SQLITE_API int sqlite3_complete(const char *sql);
2191 SQLITE_API int sqlite3_complete16(const void *sql);
2192
2193 /*
2194 ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
2195 **
2196 ** ^This routine sets a callback function that might be invoked whenever
2197 ** an attempt is made to open a database table that another thread
2198 ** or process has locked.
2199 **
2200 ** ^If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]
2201 ** is returned immediately upon encountering the lock.  ^If the busy callback
2202 ** is not NULL, then the callback might be invoked with two arguments.
2203 **
2204 ** ^The first argument to the busy handler is a copy of the void* pointer which
2205 ** is the third argument to sqlite3_busy_handler().  ^The second argument to
2206 ** the busy handler callback is the number of times that the busy handler has
2207 ** been invoked for this locking event.  ^If the
2208 ** busy callback returns 0, then no additional attempts are made to
2209 ** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
2210 ** ^If the callback returns non-zero, then another attempt
2211 ** is made to open the database for reading and the cycle repeats.
2212 **
2213 ** The presence of a busy handler does not guarantee that it will be invoked
2214 ** when there is lock contention. ^If SQLite determines that invoking the busy
2215 ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
2216 ** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler.
2217 ** Consider a scenario where one process is holding a read lock that
2218 ** it is trying to promote to a reserved lock and
2219 ** a second process is holding a reserved lock that it is trying
2220 ** to promote to an exclusive lock.  The first process cannot proceed
2221 ** because it is blocked by the second and the second process cannot
2222 ** proceed because it is blocked by the first.  If both processes
2223 ** invoke the busy handlers, neither will make any progress.  Therefore,
2224 ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
2225 ** will induce the first process to release its read lock and allow
2226 ** the second process to proceed.
2227 **
2228 ** ^The default busy callback is NULL.
2229 **
2230 ** ^The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
2231 ** when SQLite is in the middle of a large transaction where all the
2232 ** changes will not fit into the in-memory cache.  SQLite will
2233 ** already hold a RESERVED lock on the database file, but it needs
2234 ** to promote this lock to EXCLUSIVE so that it can spill cache
2235 ** pages into the database file without harm to concurrent
2236 ** readers.  ^If it is unable to promote the lock, then the in-memory
2237 ** cache will be left in an inconsistent state and so the error
2238 ** code is promoted from the relatively benign [SQLITE_BUSY] to
2239 ** the more severe [SQLITE_IOERR_BLOCKED].  ^This error code promotion
2240 ** forces an automatic rollback of the changes.  See the
2241 ** <a href="/cvstrac/wiki?p=CorruptionFollowingBusyError">
2242 ** CorruptionFollowingBusyError</a> wiki page for a discussion of why
2243 ** this is important.
2244 **
2245 ** ^(There can only be a single busy handler defined for each
2246 ** [database connection].  Setting a new busy handler clears any
2247 ** previously set handler.)^  ^Note that calling [sqlite3_busy_timeout()]
2248 ** will also set or clear the busy handler.
2249 **
2250 ** The busy callback should not take any actions which modify the
2251 ** database connection that invoked the busy handler.  Any such actions
2252 ** result in undefined behavior.
2253 ** 
2254 ** A busy handler must not close the database connection
2255 ** or [prepared statement] that invoked the busy handler.
2256 */
2257 SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
2258
2259 /*
2260 ** CAPI3REF: Set A Busy Timeout
2261 **
2262 ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
2263 ** for a specified amount of time when a table is locked.  ^The handler
2264 ** will sleep multiple times until at least "ms" milliseconds of sleeping
2265 ** have accumulated.  ^After at least "ms" milliseconds of sleeping,
2266 ** the handler returns 0 which causes [sqlite3_step()] to return
2267 ** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
2268 **
2269 ** ^Calling this routine with an argument less than or equal to zero
2270 ** turns off all busy handlers.
2271 **
2272 ** ^(There can only be a single busy handler for a particular
2273 ** [database connection] any any given moment.  If another busy handler
2274 ** was defined  (using [sqlite3_busy_handler()]) prior to calling
2275 ** this routine, that other busy handler is cleared.)^
2276 */
2277 SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
2278
2279 /*
2280 ** CAPI3REF: Convenience Routines For Running Queries
2281 **
2282 ** This is a legacy interface that is preserved for backwards compatibility.
2283 ** Use of this interface is not recommended.
2284 **
2285 ** Definition: A <b>result table</b> is memory data structure created by the
2286 ** [sqlite3_get_table()] interface.  A result table records the
2287 ** complete query results from one or more queries.
2288 **
2289 ** The table conceptually has a number of rows and columns.  But
2290 ** these numbers are not part of the result table itself.  These
2291 ** numbers are obtained separately.  Let N be the number of rows
2292 ** and M be the number of columns.
2293 **
2294 ** A result table is an array of pointers to zero-terminated UTF-8 strings.
2295 ** There are (N+1)*M elements in the array.  The first M pointers point
2296 ** to zero-terminated strings that  contain the names of the columns.
2297 ** The remaining entries all point to query results.  NULL values result
2298 ** in NULL pointers.  All other values are in their UTF-8 zero-terminated
2299 ** string representation as returned by [sqlite3_column_text()].
2300 **
2301 ** A result table might consist of one or more memory allocations.
2302 ** It is not safe to pass a result table directly to [sqlite3_free()].
2303 ** A result table should be deallocated using [sqlite3_free_table()].
2304 **
2305 ** ^(As an example of the result table format, suppose a query result
2306 ** is as follows:
2307 **
2308 ** <blockquote><pre>
2309 **        Name        | Age
2310 **        -----------------------
2311 **        Alice       | 43
2312 **        Bob         | 28
2313 **        Cindy       | 21
2314 ** </pre></blockquote>
2315 **
2316 ** There are two column (M==2) and three rows (N==3).  Thus the
2317 ** result table has 8 entries.  Suppose the result table is stored
2318 ** in an array names azResult.  Then azResult holds this content:
2319 **
2320 ** <blockquote><pre>
2321 **        azResult&#91;0] = "Name";
2322 **        azResult&#91;1] = "Age";
2323 **        azResult&#91;2] = "Alice";
2324 **        azResult&#91;3] = "43";
2325 **        azResult&#91;4] = "Bob";
2326 **        azResult&#91;5] = "28";
2327 **        azResult&#91;6] = "Cindy";
2328 **        azResult&#91;7] = "21";
2329 ** </pre></blockquote>)^
2330 **
2331 ** ^The sqlite3_get_table() function evaluates one or more
2332 ** semicolon-separated SQL statements in the zero-terminated UTF-8
2333 ** string of its 2nd parameter and returns a result table to the
2334 ** pointer given in its 3rd parameter.
2335 **
2336 ** After the application has finished with the result from sqlite3_get_table(),
2337 ** it must pass the result table pointer to sqlite3_free_table() in order to
2338 ** release the memory that was malloced.  Because of the way the
2339 ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
2340 ** function must not try to call [sqlite3_free()] directly.  Only
2341 ** [sqlite3_free_table()] is able to release the memory properly and safely.
2342 **
2343 ** The sqlite3_get_table() interface is implemented as a wrapper around
2344 ** [sqlite3_exec()].  The sqlite3_get_table() routine does not have access
2345 ** to any internal data structures of SQLite.  It uses only the public
2346 ** interface defined here.  As a consequence, errors that occur in the
2347 ** wrapper layer outside of the internal [sqlite3_exec()] call are not
2348 ** reflected in subsequent calls to [sqlite3_errcode()] or
2349 ** [sqlite3_errmsg()].
2350 */
2351 SQLITE_API int sqlite3_get_table(
2352   sqlite3 *db,          /* An open database */
2353   const char *zSql,     /* SQL to be evaluated */
2354   char ***pazResult,    /* Results of the query */
2355   int *pnRow,           /* Number of result rows written here */
2356   int *pnColumn,        /* Number of result columns written here */
2357   char **pzErrmsg       /* Error msg written here */
2358 );
2359 SQLITE_API void sqlite3_free_table(char **result);
2360
2361 /*
2362 ** CAPI3REF: Formatted String Printing Functions
2363 **
2364 ** These routines are work-alikes of the "printf()" family of functions
2365 ** from the standard C library.
2366 **
2367 ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
2368 ** results into memory obtained from [sqlite3_malloc()].
2369 ** The strings returned by these two routines should be
2370 ** released by [sqlite3_free()].  ^Both routines return a
2371 ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
2372 ** memory to hold the resulting string.
2373 **
2374 ** ^(In sqlite3_snprintf() routine is similar to "snprintf()" from
2375 ** the standard C library.  The result is written into the
2376 ** buffer supplied as the second parameter whose size is given by
2377 ** the first parameter. Note that the order of the
2378 ** first two parameters is reversed from snprintf().)^  This is an
2379 ** historical accident that cannot be fixed without breaking
2380 ** backwards compatibility.  ^(Note also that sqlite3_snprintf()
2381 ** returns a pointer to its buffer instead of the number of
2382 ** characters actually written into the buffer.)^  We admit that
2383 ** the number of characters written would be a more useful return
2384 ** value but we cannot change the implementation of sqlite3_snprintf()
2385 ** now without breaking compatibility.
2386 **
2387 ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
2388 ** guarantees that the buffer is always zero-terminated.  ^The first
2389 ** parameter "n" is the total size of the buffer, including space for
2390 ** the zero terminator.  So the longest string that can be completely
2391 ** written will be n-1 characters.
2392 **
2393 ** These routines all implement some additional formatting
2394 ** options that are useful for constructing SQL statements.
2395 ** All of the usual printf() formatting options apply.  In addition, there
2396 ** is are "%q", "%Q", and "%z" options.
2397 **
2398 ** ^(The %q option works like %s in that it substitutes a null-terminated
2399 ** string from the argument list.  But %q also doubles every '\'' character.
2400 ** %q is designed for use inside a string literal.)^  By doubling each '\''
2401 ** character it escapes that character and allows it to be inserted into
2402 ** the string.
2403 **
2404 ** For example, assume the string variable zText contains text as follows:
2405 **
2406 ** <blockquote><pre>
2407 **  char *zText = "It's a happy day!";
2408 ** </pre></blockquote>
2409 **
2410 ** One can use this text in an SQL statement as follows:
2411 **
2412 ** <blockquote><pre>
2413 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
2414 **  sqlite3_exec(db, zSQL, 0, 0, 0);
2415 **  sqlite3_free(zSQL);
2416 ** </pre></blockquote>
2417 **
2418 ** Because the %q format string is used, the '\'' character in zText
2419 ** is escaped and the SQL generated is as follows:
2420 **
2421 ** <blockquote><pre>
2422 **  INSERT INTO table1 VALUES('It''s a happy day!')
2423 ** </pre></blockquote>
2424 **
2425 ** This is correct.  Had we used %s instead of %q, the generated SQL
2426 ** would have looked like this:
2427 **
2428 ** <blockquote><pre>
2429 **  INSERT INTO table1 VALUES('It's a happy day!');
2430 ** </pre></blockquote>
2431 **
2432 ** This second example is an SQL syntax error.  As a general rule you should
2433 ** always use %q instead of %s when inserting text into a string literal.
2434 **
2435 ** ^(The %Q option works like %q except it also adds single quotes around
2436 ** the outside of the total string.  Additionally, if the parameter in the
2437 ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
2438 ** single quotes).)^  So, for example, one could say:
2439 **
2440 ** <blockquote><pre>
2441 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
2442 **  sqlite3_exec(db, zSQL, 0, 0, 0);
2443 **  sqlite3_free(zSQL);
2444 ** </pre></blockquote>
2445 **
2446 ** The code above will render a correct SQL statement in the zSQL
2447 ** variable even if the zText variable is a NULL pointer.
2448 **
2449 ** ^(The "%z" formatting option works like "%s" but with the
2450 ** addition that after the string has been read and copied into
2451 ** the result, [sqlite3_free()] is called on the input string.)^
2452 */
2453 SQLITE_API char *sqlite3_mprintf(const char*,...);
2454 SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
2455 SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
2456
2457 /*
2458 ** CAPI3REF: Memory Allocation Subsystem
2459 **
2460 ** The SQLite core uses these three routines for all of its own
2461 ** internal memory allocation needs. "Core" in the previous sentence
2462 ** does not include operating-system specific VFS implementation.  The
2463 ** Windows VFS uses native malloc() and free() for some operations.
2464 **
2465 ** ^The sqlite3_malloc() routine returns a pointer to a block
2466 ** of memory at least N bytes in length, where N is the parameter.
2467 ** ^If sqlite3_malloc() is unable to obtain sufficient free
2468 ** memory, it returns a NULL pointer.  ^If the parameter N to
2469 ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
2470 ** a NULL pointer.
2471 **
2472 ** ^Calling sqlite3_free() with a pointer previously returned
2473 ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
2474 ** that it might be reused.  ^The sqlite3_free() routine is
2475 ** a no-op if is called with a NULL pointer.  Passing a NULL pointer
2476 ** to sqlite3_free() is harmless.  After being freed, memory
2477 ** should neither be read nor written.  Even reading previously freed
2478 ** memory might result in a segmentation fault or other severe error.
2479 ** Memory corruption, a segmentation fault, or other severe error
2480 ** might result if sqlite3_free() is called with a non-NULL pointer that
2481 ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
2482 **
2483 ** ^(The sqlite3_realloc() interface attempts to resize a
2484 ** prior memory allocation to be at least N bytes, where N is the
2485 ** second parameter.  The memory allocation to be resized is the first
2486 ** parameter.)^ ^ If the first parameter to sqlite3_realloc()
2487 ** is a NULL pointer then its behavior is identical to calling
2488 ** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
2489 ** ^If the second parameter to sqlite3_realloc() is zero or
2490 ** negative then the behavior is exactly the same as calling
2491 ** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
2492 ** ^sqlite3_realloc() returns a pointer to a memory allocation
2493 ** of at least N bytes in size or NULL if sufficient memory is unavailable.
2494 ** ^If M is the size of the prior allocation, then min(N,M) bytes
2495 ** of the prior allocation are copied into the beginning of buffer returned
2496 ** by sqlite3_realloc() and the prior allocation is freed.
2497 ** ^If sqlite3_realloc() returns NULL, then the prior allocation
2498 ** is not freed.
2499 **
2500 ** ^The memory returned by sqlite3_malloc() and sqlite3_realloc()
2501 ** is always aligned to at least an 8 byte boundary, or to a
2502 ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
2503 ** option is used.
2504 **
2505 ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
2506 ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
2507 ** implementation of these routines to be omitted.  That capability
2508 ** is no longer provided.  Only built-in memory allocators can be used.
2509 **
2510 ** The Windows OS interface layer calls
2511 ** the system malloc() and free() directly when converting
2512 ** filenames between the UTF-8 encoding used by SQLite
2513 ** and whatever filename encoding is used by the particular Windows
2514 ** installation.  Memory allocation errors are detected, but
2515 ** they are reported back as [SQLITE_CANTOPEN] or
2516 ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
2517 **
2518 ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
2519 ** must be either NULL or else pointers obtained from a prior
2520 ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
2521 ** not yet been released.
2522 **
2523 ** The application must not read or write any part of
2524 ** a block of memory after it has been released using
2525 ** [sqlite3_free()] or [sqlite3_realloc()].
2526 */
2527 SQLITE_API void *sqlite3_malloc(int);
2528 SQLITE_API void *sqlite3_realloc(void*, int);
2529 SQLITE_API void sqlite3_free(void*);
2530
2531 /*
2532 ** CAPI3REF: Memory Allocator Statistics
2533 **
2534 ** SQLite provides these two interfaces for reporting on the status
2535 ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
2536 ** routines, which form the built-in memory allocation subsystem.
2537 **
2538 ** ^The [sqlite3_memory_used()] routine returns the number of bytes
2539 ** of memory currently outstanding (malloced but not freed).
2540 ** ^The [sqlite3_memory_highwater()] routine returns the maximum
2541 ** value of [sqlite3_memory_used()] since the high-water mark
2542 ** was last reset.  ^The values returned by [sqlite3_memory_used()] and
2543 ** [sqlite3_memory_highwater()] include any overhead
2544 ** added by SQLite in its implementation of [sqlite3_malloc()],
2545 ** but not overhead added by the any underlying system library
2546 ** routines that [sqlite3_malloc()] may call.
2547 **
2548 ** ^The memory high-water mark is reset to the current value of
2549 ** [sqlite3_memory_used()] if and only if the parameter to
2550 ** [sqlite3_memory_highwater()] is true.  ^The value returned
2551 ** by [sqlite3_memory_highwater(1)] is the high-water mark
2552 ** prior to the reset.
2553 */
2554 SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
2555 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
2556
2557 /*
2558 ** CAPI3REF: Pseudo-Random Number Generator
2559 **
2560 ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
2561 ** select random [ROWID | ROWIDs] when inserting new records into a table that
2562 ** already uses the largest possible [ROWID].  The PRNG is also used for
2563 ** the build-in random() and randomblob() SQL functions.  This interface allows
2564 ** applications to access the same PRNG for other purposes.
2565 **
2566 ** ^A call to this routine stores N bytes of randomness into buffer P.
2567 **
2568 ** ^The first time this routine is invoked (either internally or by
2569 ** the application) the PRNG is seeded using randomness obtained
2570 ** from the xRandomness method of the default [sqlite3_vfs] object.
2571 ** ^On all subsequent invocations, the pseudo-randomness is generated
2572 ** internally and without recourse to the [sqlite3_vfs] xRandomness
2573 ** method.
2574 */
2575 SQLITE_API void sqlite3_randomness(int N, void *P);
2576
2577 /*
2578 ** CAPI3REF: Compile-Time Authorization Callbacks
2579 **
2580 ** ^This routine registers a authorizer callback with a particular
2581 ** [database connection], supplied in the first argument.
2582 ** ^The authorizer callback is invoked as SQL statements are being compiled
2583 ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
2584 ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()].  ^At various
2585 ** points during the compilation process, as logic is being created
2586 ** to perform various actions, the authorizer callback is invoked to
2587 ** see if those actions are allowed.  ^The authorizer callback should
2588 ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
2589 ** specific action but allow the SQL statement to continue to be
2590 ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
2591 ** rejected with an error.  ^If the authorizer callback returns
2592 ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
2593 ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
2594 ** the authorizer will fail with an error message.
2595 **
2596 ** When the callback returns [SQLITE_OK], that means the operation
2597 ** requested is ok.  ^When the callback returns [SQLITE_DENY], the
2598 ** [sqlite3_prepare_v2()] or equivalent call that triggered the
2599 ** authorizer will fail with an error message explaining that
2600 ** access is denied. 
2601 **
2602 ** ^The first parameter to the authorizer callback is a copy of the third
2603 ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
2604 ** to the callback is an integer [SQLITE_COPY | action code] that specifies
2605 ** the particular action to be authorized. ^The third through sixth parameters
2606 ** to the callback are zero-terminated strings that contain additional
2607 ** details about the action to be authorized.
2608 **
2609 ** ^If the action code is [SQLITE_READ]
2610 ** and the callback returns [SQLITE_IGNORE] then the
2611 ** [prepared statement] statement is constructed to substitute
2612 ** a NULL value in place of the table column that would have
2613 ** been read if [SQLITE_OK] had been returned.  The [SQLITE_IGNORE]
2614 ** return can be used to deny an untrusted user access to individual
2615 ** columns of a table.
2616 ** ^If the action code is [SQLITE_DELETE] and the callback returns
2617 ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
2618 ** [truncate optimization] is disabled and all rows are deleted individually.
2619 **
2620 ** An authorizer is used when [sqlite3_prepare | preparing]
2621 ** SQL statements from an untrusted source, to ensure that the SQL statements
2622 ** do not try to access data they are not allowed to see, or that they do not
2623 ** try to execute malicious statements that damage the database.  For
2624 ** example, an application may allow a user to enter arbitrary
2625 ** SQL queries for evaluation by a database.  But the application does
2626 ** not want the user to be able to make arbitrary changes to the
2627 ** database.  An authorizer could then be put in place while the
2628 ** user-entered SQL is being [sqlite3_prepare | prepared] that
2629 ** disallows everything except [SELECT] statements.
2630 **
2631 ** Applications that need to process SQL from untrusted sources
2632 ** might also consider lowering resource limits using [sqlite3_limit()]
2633 ** and limiting database size using the [max_page_count] [PRAGMA]
2634 ** in addition to using an authorizer.
2635 **
2636 ** ^(Only a single authorizer can be in place on a database connection
2637 ** at a time.  Each call to sqlite3_set_authorizer overrides the
2638 ** previous call.)^  ^Disable the authorizer by installing a NULL callback.
2639 ** The authorizer is disabled by default.
2640 **
2641 ** The authorizer callback must not do anything that will modify
2642 ** the database connection that invoked the authorizer callback.
2643 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2644 ** database connections for the meaning of "modify" in this paragraph.
2645 **
2646 ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
2647 ** statement might be re-prepared during [sqlite3_step()] due to a 
2648 ** schema change.  Hence, the application should ensure that the
2649 ** correct authorizer callback remains in place during the [sqlite3_step()].
2650 **
2651 ** ^Note that the authorizer callback is invoked only during
2652 ** [sqlite3_prepare()] or its variants.  Authorization is not
2653 ** performed during statement evaluation in [sqlite3_step()], unless
2654 ** as stated in the previous paragraph, sqlite3_step() invokes
2655 ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
2656 */
2657 SQLITE_API int sqlite3_set_authorizer(
2658   sqlite3*,
2659   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
2660   void *pUserData
2661 );
2662
2663 /*
2664 ** CAPI3REF: Authorizer Return Codes
2665 **
2666 ** The [sqlite3_set_authorizer | authorizer callback function] must
2667 ** return either [SQLITE_OK] or one of these two constants in order
2668 ** to signal SQLite whether or not the action is permitted.  See the
2669 ** [sqlite3_set_authorizer | authorizer documentation] for additional
2670 ** information.
2671 */
2672 #define SQLITE_DENY   1   /* Abort the SQL statement with an error */
2673 #define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
2674
2675 /*
2676 ** CAPI3REF: Authorizer Action Codes
2677 **
2678 ** The [sqlite3_set_authorizer()] interface registers a callback function
2679 ** that is invoked to authorize certain SQL statement actions.  The
2680 ** second parameter to the callback is an integer code that specifies
2681 ** what action is being authorized.  These are the integer action codes that
2682 ** the authorizer callback may be passed.
2683 **
2684 ** These action code values signify what kind of operation is to be
2685 ** authorized.  The 3rd and 4th parameters to the authorization
2686 ** callback function will be parameters or NULL depending on which of these
2687 ** codes is used as the second parameter.  ^(The 5th parameter to the
2688 ** authorizer callback is the name of the database ("main", "temp",
2689 ** etc.) if applicable.)^  ^The 6th parameter to the authorizer callback
2690 ** is the name of the inner-most trigger or view that is responsible for
2691 ** the access attempt or NULL if this access attempt is directly from
2692 ** top-level SQL code.
2693 */
2694 /******************************************* 3rd ************ 4th ***********/
2695 #define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
2696 #define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
2697 #define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
2698 #define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
2699 #define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
2700 #define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
2701 #define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
2702 #define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
2703 #define SQLITE_DELETE                9   /* Table Name      NULL            */
2704 #define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
2705 #define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
2706 #define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
2707 #define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
2708 #define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
2709 #define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
2710 #define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
2711 #define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
2712 #define SQLITE_INSERT               18   /* Table Name      NULL            */
2713 #define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
2714 #define SQLITE_READ                 20   /* Table Name      Column Name     */
2715 #define SQLITE_SELECT               21   /* NULL            NULL            */
2716 #define SQLITE_TRANSACTION          22   /* Operation       NULL            */
2717 #define SQLITE_UPDATE               23   /* Table Name      Column Name     */
2718 #define SQLITE_ATTACH               24   /* Filename        NULL            */
2719 #define SQLITE_DETACH               25   /* Database Name   NULL            */
2720 #define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
2721 #define SQLITE_REINDEX              27   /* Index Name      NULL            */
2722 #define SQLITE_ANALYZE              28   /* Table Name      NULL            */
2723 #define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
2724 #define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
2725 #define SQLITE_FUNCTION             31   /* NULL            Function Name   */
2726 #define SQLITE_SAVEPOINT            32   /* Operation       Savepoint Name  */
2727 #define SQLITE_COPY                  0   /* No longer used */
2728
2729 /*
2730 ** CAPI3REF: Tracing And Profiling Functions
2731 **
2732 ** These routines register callback functions that can be used for
2733 ** tracing and profiling the execution of SQL statements.
2734 **
2735 ** ^The callback function registered by sqlite3_trace() is invoked at
2736 ** various times when an SQL statement is being run by [sqlite3_step()].
2737 ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
2738 ** SQL statement text as the statement first begins executing.
2739 ** ^(Additional sqlite3_trace() callbacks might occur
2740 ** as each triggered subprogram is entered.  The callbacks for triggers
2741 ** contain a UTF-8 SQL comment that identifies the trigger.)^
2742 **
2743 ** ^The callback function registered by sqlite3_profile() is invoked
2744 ** as each SQL statement finishes.  ^The profile callback contains
2745 ** the original statement text and an estimate of wall-clock time
2746 ** of how long that statement took to run.  ^The profile callback
2747 ** time is in units of nanoseconds, however the current implementation
2748 ** is only capable of millisecond resolution so the six least significant
2749 ** digits in the time are meaningless.  Future versions of SQLite
2750 ** might provide greater resolution on the profiler callback.  The
2751 ** sqlite3_profile() function is considered experimental and is
2752 ** subject to change in future versions of SQLite.
2753 */
2754 SQLITE_API void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
2755 SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,
2756    void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
2757
2758 /*
2759 ** CAPI3REF: Query Progress Callbacks
2760 **
2761 ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
2762 ** function X to be invoked periodically during long running calls to
2763 ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
2764 ** database connection D.  An example use for this
2765 ** interface is to keep a GUI updated during a large query.
2766 **
2767 ** ^The parameter P is passed through as the only parameter to the 
2768 ** callback function X.  ^The parameter N is the number of 
2769 ** [virtual machine instructions] that are evaluated between successive
2770 ** invocations of the callback X.
2771 **
2772 ** ^Only a single progress handler may be defined at one time per
2773 ** [database connection]; setting a new progress handler cancels the
2774 ** old one.  ^Setting parameter X to NULL disables the progress handler.
2775 ** ^The progress handler is also disabled by setting N to a value less
2776 ** than 1.
2777 **
2778 ** ^If the progress callback returns non-zero, the operation is
2779 ** interrupted.  This feature can be used to implement a
2780 ** "Cancel" button on a GUI progress dialog box.
2781 **
2782 ** The progress handler callback must not do anything that will modify
2783 ** the database connection that invoked the progress handler.
2784 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2785 ** database connections for the meaning of "modify" in this paragraph.
2786 **
2787 */
2788 SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
2789
2790 /*
2791 ** CAPI3REF: Opening A New Database Connection
2792 **
2793 ** ^These routines open an SQLite database file whose name is given by the
2794 ** filename argument. ^The filename argument is interpreted as UTF-8 for
2795 ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
2796 ** order for sqlite3_open16(). ^(A [database connection] handle is usually
2797 ** returned in *ppDb, even if an error occurs.  The only exception is that
2798 ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
2799 ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
2800 ** object.)^ ^(If the database is opened (and/or created) successfully, then
2801 ** [SQLITE_OK] is returned.  Otherwise an [error code] is returned.)^ ^The
2802 ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
2803 ** an English language description of the error following a failure of any
2804 ** of the sqlite3_open() routines.
2805 **
2806 ** ^The default encoding for the database will be UTF-8 if
2807 ** sqlite3_open() or sqlite3_open_v2() is called and
2808 ** UTF-16 in the native byte order if sqlite3_open16() is used.
2809 **
2810 ** Whether or not an error occurs when it is opened, resources
2811 ** associated with the [database connection] handle should be released by
2812 ** passing it to [sqlite3_close()] when it is no longer required.
2813 **
2814 ** The sqlite3_open_v2() interface works like sqlite3_open()
2815 ** except that it accepts two additional parameters for additional control
2816 ** over the new database connection.  ^(The flags parameter to
2817 ** sqlite3_open_v2() can take one of
2818 ** the following three values, optionally combined with the 
2819 ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
2820 ** and/or [SQLITE_OPEN_PRIVATECACHE] flags:)^
2821 **
2822 ** <dl>
2823 ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
2824 ** <dd>The database is opened in read-only mode.  If the database does not
2825 ** already exist, an error is returned.</dd>)^
2826 **
2827 ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
2828 ** <dd>The database is opened for reading and writing if possible, or reading
2829 ** only if the file is write protected by the operating system.  In either
2830 ** case the database must already exist, otherwise an error is returned.</dd>)^
2831 **
2832 ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
2833 ** <dd>The database is opened for reading and writing, and is creates it if
2834 ** it does not already exist. This is the behavior that is always used for
2835 ** sqlite3_open() and sqlite3_open16().</dd>)^
2836 ** </dl>
2837 **
2838 ** If the 3rd parameter to sqlite3_open_v2() is not one of the
2839 ** combinations shown above or one of the combinations shown above combined
2840 ** with the [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX],
2841 ** [SQLITE_OPEN_SHAREDCACHE] and/or [SQLITE_OPEN_PRIVATECACHE] flags,
2842 ** then the behavior is undefined.
2843 **
2844 ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
2845 ** opens in the multi-thread [threading mode] as long as the single-thread
2846 ** mode has not been set at compile-time or start-time.  ^If the
2847 ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
2848 ** in the serialized [threading mode] unless single-thread was
2849 ** previously selected at compile-time or start-time.
2850 ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
2851 ** eligible to use [shared cache mode], regardless of whether or not shared
2852 ** cache is enabled using [sqlite3_enable_shared_cache()].  ^The
2853 ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
2854 ** participate in [shared cache mode] even if it is enabled.
2855 **
2856 ** ^If the filename is ":memory:", then a private, temporary in-memory database
2857 ** is created for the connection.  ^This in-memory database will vanish when
2858 ** the database connection is closed.  Future versions of SQLite might
2859 ** make use of additional special filenames that begin with the ":" character.
2860 ** It is recommended that when a database filename actually does begin with
2861 ** a ":" character you should prefix the filename with a pathname such as
2862 ** "./" to avoid ambiguity.
2863 **
2864 ** ^If the filename is an empty string, then a private, temporary
2865 ** on-disk database will be created.  ^This private database will be
2866 ** automatically deleted as soon as the database connection is closed.
2867 **
2868 ** ^The fourth parameter to sqlite3_open_v2() is the name of the
2869 ** [sqlite3_vfs] object that defines the operating system interface that
2870 ** the new database connection should use.  ^If the fourth parameter is
2871 ** a NULL pointer then the default [sqlite3_vfs] object is used.
2872 **
2873 ** <b>Note to Windows users:</b>  The encoding used for the filename argument
2874 ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
2875 ** codepage is currently defined.  Filenames containing international
2876 ** characters must be converted to UTF-8 prior to passing them into
2877 ** sqlite3_open() or sqlite3_open_v2().
2878 */
2879 SQLITE_API int sqlite3_open(
2880   const char *filename,   /* Database filename (UTF-8) */
2881   sqlite3 **ppDb          /* OUT: SQLite db handle */
2882 );
2883 SQLITE_API int sqlite3_open16(
2884   const void *filename,   /* Database filename (UTF-16) */
2885   sqlite3 **ppDb          /* OUT: SQLite db handle */
2886 );
2887 SQLITE_API int sqlite3_open_v2(
2888   const char *filename,   /* Database filename (UTF-8) */
2889   sqlite3 **ppDb,         /* OUT: SQLite db handle */
2890   int flags,              /* Flags */
2891   const char *zVfs        /* Name of VFS module to use */
2892 );
2893
2894 /*
2895 ** CAPI3REF: Error Codes And Messages
2896 **
2897 ** ^The sqlite3_errcode() interface returns the numeric [result code] or
2898 ** [extended result code] for the most recent failed sqlite3_* API call
2899 ** associated with a [database connection]. If a prior API call failed
2900 ** but the most recent API call succeeded, the return value from
2901 ** sqlite3_errcode() is undefined.  ^The sqlite3_extended_errcode()
2902 ** interface is the same except that it always returns the 
2903 ** [extended result code] even when extended result codes are
2904 ** disabled.
2905 **
2906 ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
2907 ** text that describes the error, as either UTF-8 or UTF-16 respectively.
2908 ** ^(Memory to hold the error message string is managed internally.
2909 ** The application does not need to worry about freeing the result.
2910 ** However, the error string might be overwritten or deallocated by
2911 ** subsequent calls to other SQLite interface functions.)^
2912 **
2913 ** When the serialized [threading mode] is in use, it might be the
2914 ** case that a second error occurs on a separate thread in between
2915 ** the time of the first error and the call to these interfaces.
2916 ** When that happens, the second error will be reported since these
2917 ** interfaces always report the most recent result.  To avoid
2918 ** this, each thread can obtain exclusive use of the [database connection] D
2919 ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
2920 ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
2921 ** all calls to the interfaces listed here are completed.
2922 **
2923 ** If an interface fails with SQLITE_MISUSE, that means the interface
2924 ** was invoked incorrectly by the application.  In that case, the
2925 ** error code and message may or may not be set.
2926 */
2927 SQLITE_API int sqlite3_errcode(sqlite3 *db);
2928 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
2929 SQLITE_API const char *sqlite3_errmsg(sqlite3*);
2930 SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
2931
2932 /*
2933 ** CAPI3REF: SQL Statement Object
2934 ** KEYWORDS: {prepared statement} {prepared statements}
2935 **
2936 ** An instance of this object represents a single SQL statement.
2937 ** This object is variously known as a "prepared statement" or a
2938 ** "compiled SQL statement" or simply as a "statement".
2939 **
2940 ** The life of a statement object goes something like this:
2941 **
2942 ** <ol>
2943 ** <li> Create the object using [sqlite3_prepare_v2()] or a related
2944 **      function.
2945 ** <li> Bind values to [host parameters] using the sqlite3_bind_*()
2946 **      interfaces.
2947 ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
2948 ** <li> Reset the statement using [sqlite3_reset()] then go back
2949 **      to step 2.  Do this zero or more times.
2950 ** <li> Destroy the object using [sqlite3_finalize()].
2951 ** </ol>
2952 **
2953 ** Refer to documentation on individual methods above for additional
2954 ** information.
2955 */
2956 typedef struct sqlite3_stmt sqlite3_stmt;
2957
2958 /*
2959 ** CAPI3REF: Run-time Limits
2960 **
2961 ** ^(This interface allows the size of various constructs to be limited
2962 ** on a connection by connection basis.  The first parameter is the
2963 ** [database connection] whose limit is to be set or queried.  The
2964 ** second parameter is one of the [limit categories] that define a
2965 ** class of constructs to be size limited.  The third parameter is the
2966 ** new limit for that construct.)^
2967 **
2968 ** ^If the new limit is a negative number, the limit is unchanged.
2969 ** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a 
2970 ** [limits | hard upper bound]
2971 ** set at compile-time by a C preprocessor macro called
2972 ** [limits | SQLITE_MAX_<i>NAME</i>].
2973 ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
2974 ** ^Attempts to increase a limit above its hard upper bound are
2975 ** silently truncated to the hard upper bound.
2976 **
2977 ** ^Regardless of whether or not the limit was changed, the 
2978 ** [sqlite3_limit()] interface returns the prior value of the limit.
2979 ** ^Hence, to find the current value of a limit without changing it,
2980 ** simply invoke this interface with the third parameter set to -1.
2981 **
2982 ** Run-time limits are intended for use in applications that manage
2983 ** both their own internal database and also databases that are controlled
2984 ** by untrusted external sources.  An example application might be a
2985 ** web browser that has its own databases for storing history and
2986 ** separate databases controlled by JavaScript applications downloaded
2987 ** off the Internet.  The internal databases can be given the
2988 ** large, default limits.  Databases managed by external sources can
2989 ** be given much smaller limits designed to prevent a denial of service
2990 ** attack.  Developers might also want to use the [sqlite3_set_authorizer()]
2991 ** interface to further control untrusted SQL.  The size of the database
2992 ** created by an untrusted script can be contained using the
2993 ** [max_page_count] [PRAGMA].
2994 **
2995 ** New run-time limit categories may be added in future releases.
2996 */
2997 SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
2998
2999 /*
3000 ** CAPI3REF: Run-Time Limit Categories
3001 ** KEYWORDS: {limit category} {*limit categories}
3002 **
3003 ** These constants define various performance limits
3004 ** that can be lowered at run-time using [sqlite3_limit()].
3005 ** The synopsis of the meanings of the various limits is shown below.
3006 ** Additional information is available at [limits | Limits in SQLite].
3007 **
3008 ** <dl>
3009 ** ^(<dt>SQLITE_LIMIT_LENGTH</dt>
3010 ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
3011 **
3012 ** ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
3013 ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
3014 **
3015 ** ^(<dt>SQLITE_LIMIT_COLUMN</dt>
3016 ** <dd>The maximum number of columns in a table definition or in the
3017 ** result set of a [SELECT] or the maximum number of columns in an index
3018 ** or in an ORDER BY or GROUP BY clause.</dd>)^
3019 **
3020 ** ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
3021 ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
3022 **
3023 ** ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
3024 ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
3025 **
3026 ** ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
3027 ** <dd>The maximum number of instructions in a virtual machine program
3028 ** used to implement an SQL statement.  This limit is not currently
3029 ** enforced, though that might be added in some future release of
3030 ** SQLite.</dd>)^
3031 **
3032 ** ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
3033 ** <dd>The maximum number of arguments on a function.</dd>)^
3034 **
3035 ** ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
3036 ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
3037 **
3038 ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
3039 ** <dd>The maximum length of the pattern argument to the [LIKE] or
3040 ** [GLOB] operators.</dd>)^
3041 **
3042 ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
3043 ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
3044 **
3045 ** ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
3046 ** <dd>The maximum depth of recursion for triggers.</dd>)^
3047 ** </dl>
3048 */
3049 #define SQLITE_LIMIT_LENGTH                    0
3050 #define SQLITE_LIMIT_SQL_LENGTH                1
3051 #define SQLITE_LIMIT_COLUMN                    2
3052 #define SQLITE_LIMIT_EXPR_DEPTH                3
3053 #define SQLITE_LIMIT_COMPOUND_SELECT           4
3054 #define SQLITE_LIMIT_VDBE_OP                   5
3055 #define SQLITE_LIMIT_FUNCTION_ARG              6
3056 #define SQLITE_LIMIT_ATTACHED                  7
3057 #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH       8
3058 #define SQLITE_LIMIT_VARIABLE_NUMBER           9
3059 #define SQLITE_LIMIT_TRIGGER_DEPTH            10
3060
3061 /*
3062 ** CAPI3REF: Compiling An SQL Statement
3063 ** KEYWORDS: {SQL statement compiler}
3064 **
3065 ** To execute an SQL query, it must first be compiled into a byte-code
3066 ** program using one of these routines.
3067 **
3068 ** The first argument, "db", is a [database connection] obtained from a
3069 ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
3070 ** [sqlite3_open16()].  The database connection must not have been closed.
3071 **
3072 ** The second argument, "zSql", is the statement to be compiled, encoded
3073 ** as either UTF-8 or UTF-16.  The sqlite3_prepare() and sqlite3_prepare_v2()
3074 ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
3075 ** use UTF-16.
3076 **
3077 ** ^If the nByte argument is less than zero, then zSql is read up to the
3078 ** first zero terminator. ^If nByte is non-negative, then it is the maximum
3079 ** number of  bytes read from zSql.  ^When nByte is non-negative, the
3080 ** zSql string ends at either the first '\000' or '\u0000' character or
3081 ** the nByte-th byte, whichever comes first. If the caller knows
3082 ** that the supplied string is nul-terminated, then there is a small
3083 ** performance advantage to be gained by passing an nByte parameter that
3084 ** is equal to the number of bytes in the input string <i>including</i>
3085 ** the nul-terminator bytes.
3086 **
3087 ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
3088 ** past the end of the first SQL statement in zSql.  These routines only
3089 ** compile the first statement in zSql, so *pzTail is left pointing to
3090 ** what remains uncompiled.
3091 **
3092 ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
3093 ** executed using [sqlite3_step()].  ^If there is an error, *ppStmt is set
3094 ** to NULL.  ^If the input text contains no SQL (if the input is an empty
3095 ** string or a comment) then *ppStmt is set to NULL.
3096 ** The calling procedure is responsible for deleting the compiled
3097 ** SQL statement using [sqlite3_finalize()] after it has finished with it.
3098 ** ppStmt may not be NULL.
3099 **
3100 ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
3101 ** otherwise an [error code] is returned.
3102 **
3103 ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
3104 ** recommended for all new programs. The two older interfaces are retained
3105 ** for backwards compatibility, but their use is discouraged.
3106 ** ^In the "v2" interfaces, the prepared statement
3107 ** that is returned (the [sqlite3_stmt] object) contains a copy of the
3108 ** original SQL text. This causes the [sqlite3_step()] interface to
3109 ** behave differently in three ways:
3110 **
3111 ** <ol>
3112 ** <li>
3113 ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
3114 ** always used to do, [sqlite3_step()] will automatically recompile the SQL
3115 ** statement and try to run it again.
3116 ** </li>
3117 **
3118 ** <li>
3119 ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
3120 ** [error codes] or [extended error codes].  ^The legacy behavior was that
3121 ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
3122 ** and the application would have to make a second call to [sqlite3_reset()]
3123 ** in order to find the underlying cause of the problem. With the "v2" prepare
3124 ** interfaces, the underlying reason for the error is returned immediately.
3125 ** </li>
3126 **
3127 ** <li>
3128 ** ^If the specific value bound to [parameter | host parameter] in the 
3129 ** WHERE clause might influence the choice of query plan for a statement,
3130 ** then the statement will be automatically recompiled, as if there had been 
3131 ** a schema change, on the first  [sqlite3_step()] call following any change
3132 ** to the [sqlite3_bind_text | bindings] of that [parameter]. 
3133 ** ^The specific value of WHERE-clause [parameter] might influence the 
3134 ** choice of query plan if the parameter is the left-hand side of a [LIKE]
3135 ** or [GLOB] operator or if the parameter is compared to an indexed column
3136 ** and the [SQLITE_ENABLE_STAT2] compile-time option is enabled.
3137 ** the 
3138 ** </li>
3139 ** </ol>
3140 */
3141 SQLITE_API int sqlite3_prepare(
3142   sqlite3 *db,            /* Database handle */
3143   const char *zSql,       /* SQL statement, UTF-8 encoded */
3144   int nByte,              /* Maximum length of zSql in bytes. */
3145   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3146   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3147 );
3148 SQLITE_API int sqlite3_prepare_v2(
3149   sqlite3 *db,            /* Database handle */
3150   const char *zSql,       /* SQL statement, UTF-8 encoded */
3151   int nByte,              /* Maximum length of zSql in bytes. */
3152   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3153   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3154 );
3155 SQLITE_API int sqlite3_prepare16(
3156   sqlite3 *db,            /* Database handle */
3157   const void *zSql,       /* SQL statement, UTF-16 encoded */
3158   int nByte,              /* Maximum length of zSql in bytes. */
3159   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3160   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3161 );
3162 SQLITE_API int sqlite3_prepare16_v2(
3163   sqlite3 *db,            /* Database handle */
3164   const void *zSql,       /* SQL statement, UTF-16 encoded */
3165   int nByte,              /* Maximum length of zSql in bytes. */
3166   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3167   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3168 );
3169
3170 /*
3171 ** CAPI3REF: Retrieving Statement SQL
3172 **
3173 ** ^This interface can be used to retrieve a saved copy of the original
3174 ** SQL text used to create a [prepared statement] if that statement was
3175 ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
3176 */
3177 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
3178
3179 /*
3180 ** CAPI3REF: Dynamically Typed Value Object
3181 ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
3182 **
3183 ** SQLite uses the sqlite3_value object to represent all values
3184 ** that can be stored in a database table. SQLite uses dynamic typing
3185 ** for the values it stores.  ^Values stored in sqlite3_value objects
3186 ** can be integers, floating point values, strings, BLOBs, or NULL.
3187 **
3188 ** An sqlite3_value object may be either "protected" or "unprotected".
3189 ** Some interfaces require a protected sqlite3_value.  Other interfaces
3190 ** will accept either a protected or an unprotected sqlite3_value.
3191 ** Every interface that accepts sqlite3_value arguments specifies
3192 ** whether or not it requires a protected sqlite3_value.
3193 **
3194 ** The terms "protected" and "unprotected" refer to whether or not
3195 ** a mutex is held.  A internal mutex is held for a protected
3196 ** sqlite3_value object but no mutex is held for an unprotected
3197 ** sqlite3_value object.  If SQLite is compiled to be single-threaded
3198 ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
3199 ** or if SQLite is run in one of reduced mutex modes 
3200 ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
3201 ** then there is no distinction between protected and unprotected
3202 ** sqlite3_value objects and they can be used interchangeably.  However,
3203 ** for maximum code portability it is recommended that applications
3204 ** still make the distinction between protected and unprotected
3205 ** sqlite3_value objects even when not strictly required.
3206 **
3207 ** ^The sqlite3_value objects that are passed as parameters into the
3208 ** implementation of [application-defined SQL functions] are protected.
3209 ** ^The sqlite3_value object returned by
3210 ** [sqlite3_column_value()] is unprotected.
3211 ** Unprotected sqlite3_value objects may only be used with
3212 ** [sqlite3_result_value()] and [sqlite3_bind_value()].
3213 ** The [sqlite3_value_blob | sqlite3_value_type()] family of
3214 ** interfaces require protected sqlite3_value objects.
3215 */
3216 typedef struct Mem sqlite3_value;
3217
3218 /*
3219 ** CAPI3REF: SQL Function Context Object
3220 **
3221 ** The context in which an SQL function executes is stored in an
3222 ** sqlite3_context object.  ^A pointer to an sqlite3_context object
3223 ** is always first parameter to [application-defined SQL functions].
3224 ** The application-defined SQL function implementation will pass this
3225 ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
3226 ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
3227 ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
3228 ** and/or [sqlite3_set_auxdata()].
3229 */
3230 typedef struct sqlite3_context sqlite3_context;
3231
3232 /*
3233 ** CAPI3REF: Binding Values To Prepared Statements
3234 ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
3235 ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
3236 **
3237 ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
3238 ** literals may be replaced by a [parameter] that matches one of following
3239 ** templates:
3240 **
3241 ** <ul>
3242 ** <li>  ?
3243 ** <li>  ?NNN
3244 ** <li>  :VVV
3245 ** <li>  @VVV
3246 ** <li>  $VVV
3247 ** </ul>
3248 **
3249 ** In the templates above, NNN represents an integer literal,
3250 ** and VVV represents an alphanumeric identifier.)^  ^The values of these
3251 ** parameters (also called "host parameter names" or "SQL parameters")
3252 ** can be set using the sqlite3_bind_*() routines defined here.
3253 **
3254 ** ^The first argument to the sqlite3_bind_*() routines is always
3255 ** a pointer to the [sqlite3_stmt] object returned from
3256 ** [sqlite3_prepare_v2()] or its variants.
3257 **
3258 ** ^The second argument is the index of the SQL parameter to be set.
3259 ** ^The leftmost SQL parameter has an index of 1.  ^When the same named
3260 ** SQL parameter is used more than once, second and subsequent
3261 ** occurrences have the same index as the first occurrence.
3262 ** ^The index for named parameters can be looked up using the
3263 ** [sqlite3_bind_parameter_index()] API if desired.  ^The index
3264 ** for "?NNN" parameters is the value of NNN.
3265 ** ^The NNN value must be between 1 and the [sqlite3_limit()]
3266 ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
3267 **
3268 ** ^The third argument is the value to bind to the parameter.
3269 **
3270 ** ^(In those routines that have a fourth argument, its value is the
3271 ** number of bytes in the parameter.  To be clear: the value is the
3272 ** number of <u>bytes</u> in the value, not the number of characters.)^
3273 ** ^If the fourth parameter is negative, the length of the string is
3274 ** the number of bytes up to the first zero terminator.
3275 **
3276 ** ^The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
3277 ** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
3278 ** string after SQLite has finished with it. ^If the fifth argument is
3279 ** the special value [SQLITE_STATIC], then SQLite assumes that the
3280 ** information is in static, unmanaged space and does not need to be freed.
3281 ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
3282 ** SQLite makes its own private copy of the data immediately, before
3283 ** the sqlite3_bind_*() routine returns.
3284 **
3285 ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
3286 ** is filled with zeroes.  ^A zeroblob uses a fixed amount of memory
3287 ** (just an integer to hold its size) while it is being processed.
3288 ** Zeroblobs are intended to serve as placeholders for BLOBs whose
3289 ** content is later written using
3290 ** [sqlite3_blob_open | incremental BLOB I/O] routines.
3291 ** ^A negative value for the zeroblob results in a zero-length BLOB.
3292 **
3293 ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
3294 ** for the [prepared statement] or with a prepared statement for which
3295 ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
3296 ** then the call will return [SQLITE_MISUSE].  If any sqlite3_bind_()
3297 ** routine is passed a [prepared statement] that has been finalized, the
3298 ** result is undefined and probably harmful.
3299 **
3300 ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
3301 ** ^Unbound parameters are interpreted as NULL.
3302 **
3303 ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
3304 ** [error code] if anything goes wrong.
3305 ** ^[SQLITE_RANGE] is returned if the parameter
3306 ** index is out of range.  ^[SQLITE_NOMEM] is returned if malloc() fails.
3307 **
3308 ** See also: [sqlite3_bind_parameter_count()],
3309 ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
3310 */
3311 SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
3312 SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
3313 SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
3314 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
3315 SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
3316 SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
3317 SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
3318 SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
3319 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
3320
3321 /*
3322 ** CAPI3REF: Number Of SQL Parameters
3323 **
3324 ** ^This routine can be used to find the number of [SQL parameters]
3325 ** in a [prepared statement].  SQL parameters are tokens of the
3326 ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
3327 ** placeholders for values that are [sqlite3_bind_blob | bound]
3328 ** to the parameters at a later time.
3329 **
3330 ** ^(This routine actually returns the index of the largest (rightmost)
3331 ** parameter. For all forms except ?NNN, this will correspond to the
3332 ** number of unique parameters.  If parameters of the ?NNN form are used,
3333 ** there may be gaps in the list.)^
3334 **
3335 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3336 ** [sqlite3_bind_parameter_name()], and
3337 ** [sqlite3_bind_parameter_index()].
3338 */
3339 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
3340
3341 /*
3342 ** CAPI3REF: Name Of A Host Parameter
3343 **
3344 ** ^The sqlite3_bind_parameter_name(P,N) interface returns
3345 ** the name of the N-th [SQL parameter] in the [prepared statement] P.
3346 ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
3347 ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
3348 ** respectively.
3349 ** In other words, the initial ":" or "$" or "@" or "?"
3350 ** is included as part of the name.)^
3351 ** ^Parameters of the form "?" without a following integer have no name
3352 ** and are referred to as "nameless" or "anonymous parameters".
3353 **
3354 ** ^The first host parameter has an index of 1, not 0.
3355 **
3356 ** ^If the value N is out of range or if the N-th parameter is
3357 ** nameless, then NULL is returned.  ^The returned string is
3358 ** always in UTF-8 encoding even if the named parameter was
3359 ** originally specified as UTF-16 in [sqlite3_prepare16()] or
3360 ** [sqlite3_prepare16_v2()].
3361 **
3362 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3363 ** [sqlite3_bind_parameter_count()], and
3364 ** [sqlite3_bind_parameter_index()].
3365 */
3366 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
3367
3368 /*
3369 ** CAPI3REF: Index Of A Parameter With A Given Name
3370 **
3371 ** ^Return the index of an SQL parameter given its name.  ^The
3372 ** index value returned is suitable for use as the second
3373 ** parameter to [sqlite3_bind_blob|sqlite3_bind()].  ^A zero
3374 ** is returned if no matching parameter is found.  ^The parameter
3375 ** name must be given in UTF-8 even if the original statement
3376 ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
3377 **
3378 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3379 ** [sqlite3_bind_parameter_count()], and
3380 ** [sqlite3_bind_parameter_index()].
3381 */
3382 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
3383
3384 /*
3385 ** CAPI3REF: Reset All Bindings On A Prepared Statement
3386 **
3387 ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
3388 ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
3389 ** ^Use this routine to reset all host parameters to NULL.
3390 */
3391 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
3392
3393 /*
3394 ** CAPI3REF: Number Of Columns In A Result Set
3395 **
3396 ** ^Return the number of columns in the result set returned by the
3397 ** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
3398 ** statement that does not return data (for example an [UPDATE]).
3399 **
3400 ** See also: [sqlite3_data_count()]
3401 */
3402 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
3403
3404 /*
3405 ** CAPI3REF: Column Names In A Result Set
3406 **
3407 ** ^These routines return the name assigned to a particular column
3408 ** in the result set of a [SELECT] statement.  ^The sqlite3_column_name()
3409 ** interface returns a pointer to a zero-terminated UTF-8 string
3410 ** and sqlite3_column_name16() returns a pointer to a zero-terminated
3411 ** UTF-16 string.  ^The first parameter is the [prepared statement]
3412 ** that implements the [SELECT] statement. ^The second parameter is the
3413 ** column number.  ^The leftmost column is number 0.
3414 **
3415 ** ^The returned string pointer is valid until either the [prepared statement]
3416 ** is destroyed by [sqlite3_finalize()] or until the next call to
3417 ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
3418 **
3419 ** ^If sqlite3_malloc() fails during the processing of either routine
3420 ** (for example during a conversion from UTF-8 to UTF-16) then a
3421 ** NULL pointer is returned.
3422 **
3423 ** ^The name of a result column is the value of the "AS" clause for
3424 ** that column, if there is an AS clause.  If there is no AS clause
3425 ** then the name of the column is unspecified and may change from
3426 ** one release of SQLite to the next.
3427 */
3428 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
3429 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
3430
3431 /*
3432 ** CAPI3REF: Source Of Data In A Query Result
3433 **
3434 ** ^These routines provide a means to determine the database, table, and
3435 ** table column that is the origin of a particular result column in
3436 ** [SELECT] statement.
3437 ** ^The name of the database or table or column can be returned as
3438 ** either a UTF-8 or UTF-16 string.  ^The _database_ routines return
3439 ** the database name, the _table_ routines return the table name, and
3440 ** the origin_ routines return the column name.
3441 ** ^The returned string is valid until the [prepared statement] is destroyed
3442 ** using [sqlite3_finalize()] or until the same information is requested
3443 ** again in a different encoding.
3444 **
3445 ** ^The names returned are the original un-aliased names of the
3446 ** database, table, and column.
3447 **
3448 ** ^The first argument to these interfaces is a [prepared statement].
3449 ** ^These functions return information about the Nth result column returned by
3450 ** the statement, where N is the second function argument.
3451 ** ^The left-most column is column 0 for these routines.
3452 **
3453 ** ^If the Nth column returned by the statement is an expression or
3454 ** subquery and is not a column value, then all of these functions return
3455 ** NULL.  ^These routine might also return NULL if a memory allocation error
3456 ** occurs.  ^Otherwise, they return the name of the attached database, table,
3457 ** or column that query result column was extracted from.
3458 **
3459 ** ^As with all other SQLite APIs, those whose names end with "16" return
3460 ** UTF-16 encoded strings and the other functions return UTF-8.
3461 **
3462 ** ^These APIs are only available if the library was compiled with the
3463 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
3464 **
3465 ** If two or more threads call one or more of these routines against the same
3466 ** prepared statement and column at the same time then the results are
3467 ** undefined.
3468 **
3469 ** If two or more threads call one or more
3470 ** [sqlite3_column_database_name | column metadata interfaces]
3471 ** for the same [prepared statement] and result column
3472 ** at the same time then the results are undefined.
3473 */
3474 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
3475 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
3476 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
3477 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
3478 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
3479 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
3480
3481 /*
3482 ** CAPI3REF: Declared Datatype Of A Query Result
3483 **
3484 ** ^(The first parameter is a [prepared statement].
3485 ** If this statement is a [SELECT] statement and the Nth column of the
3486 ** returned result set of that [SELECT] is a table column (not an
3487 ** expression or subquery) then the declared type of the table
3488 ** column is returned.)^  ^If the Nth column of the result set is an
3489 ** expression or subquery, then a NULL pointer is returned.
3490 ** ^The returned string is always UTF-8 encoded.
3491 **
3492 ** ^(For example, given the database schema:
3493 **
3494 ** CREATE TABLE t1(c1 VARIANT);
3495 **
3496 ** and the following statement to be compiled:
3497 **
3498 ** SELECT c1 + 1, c1 FROM t1;
3499 **
3500 ** this routine would return the string "VARIANT" for the second result
3501 ** column (i==1), and a NULL pointer for the first result column (i==0).)^
3502 **
3503 ** ^SQLite uses dynamic run-time typing.  ^So just because a column
3504 ** is declared to contain a particular type does not mean that the
3505 ** data stored in that column is of the declared type.  SQLite is
3506 ** strongly typed, but the typing is dynamic not static.  ^Type
3507 ** is associated with individual values, not with the containers
3508 ** used to hold those values.
3509 */
3510 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
3511 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
3512
3513 /*
3514 ** CAPI3REF: Evaluate An SQL Statement
3515 **
3516 ** After a [prepared statement] has been prepared using either
3517 ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
3518 ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
3519 ** must be called one or more times to evaluate the statement.
3520 **
3521 ** The details of the behavior of the sqlite3_step() interface depend
3522 ** on whether the statement was prepared using the newer "v2" interface
3523 ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
3524 ** interface [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the
3525 ** new "v2" interface is recommended for new applications but the legacy
3526 ** interface will continue to be supported.
3527 **
3528 ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
3529 ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
3530 ** ^With the "v2" interface, any of the other [result codes] or
3531 ** [extended result codes] might be returned as well.
3532 **
3533 ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
3534 ** database locks it needs to do its job.  ^If the statement is a [COMMIT]
3535 ** or occurs outside of an explicit transaction, then you can retry the
3536 ** statement.  If the statement is not a [COMMIT] and occurs within a
3537 ** explicit transaction then you should rollback the transaction before
3538 ** continuing.
3539 **
3540 ** ^[SQLITE_DONE] means that the statement has finished executing
3541 ** successfully.  sqlite3_step() should not be called again on this virtual
3542 ** machine without first calling [sqlite3_reset()] to reset the virtual
3543 ** machine back to its initial state.
3544 **
3545 ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
3546 ** is returned each time a new row of data is ready for processing by the
3547 ** caller. The values may be accessed using the [column access functions].
3548 ** sqlite3_step() is called again to retrieve the next row of data.
3549 **
3550 ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
3551 ** violation) has occurred.  sqlite3_step() should not be called again on
3552 ** the VM. More information may be found by calling [sqlite3_errmsg()].
3553 ** ^With the legacy interface, a more specific error code (for example,
3554 ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
3555 ** can be obtained by calling [sqlite3_reset()] on the
3556 ** [prepared statement].  ^In the "v2" interface,
3557 ** the more specific error code is returned directly by sqlite3_step().
3558 **
3559 ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
3560 ** Perhaps it was called on a [prepared statement] that has
3561 ** already been [sqlite3_finalize | finalized] or on one that had
3562 ** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could
3563 ** be the case that the same database connection is being used by two or
3564 ** more threads at the same moment in time.
3565 **
3566 ** For all versions of SQLite up to and including 3.6.23.1, it was required
3567 ** after sqlite3_step() returned anything other than [SQLITE_ROW] that
3568 ** [sqlite3_reset()] be called before any subsequent invocation of
3569 ** sqlite3_step().  Failure to invoke [sqlite3_reset()] in this way would
3570 ** result in an [SQLITE_MISUSE] return from sqlite3_step().  But after
3571 ** version 3.6.23.1, sqlite3_step() began calling [sqlite3_reset()] 
3572 ** automatically in this circumstance rather than returning [SQLITE_MISUSE].  
3573 **
3574 ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
3575 ** API always returns a generic error code, [SQLITE_ERROR], following any
3576 ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE].  You must call
3577 ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
3578 ** specific [error codes] that better describes the error.
3579 ** We admit that this is a goofy design.  The problem has been fixed
3580 ** with the "v2" interface.  If you prepare all of your SQL statements
3581 ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
3582 ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
3583 ** then the more specific [error codes] are returned directly
3584 ** by sqlite3_step().  The use of the "v2" interface is recommended.
3585 */
3586 SQLITE_API int sqlite3_step(sqlite3_stmt*);
3587
3588 /*
3589 ** CAPI3REF: Number of columns in a result set
3590 **
3591 ** ^The sqlite3_data_count(P) interface returns the number of columns in the
3592 ** current row of the result set of [prepared statement] P.
3593 ** ^If prepared statement P does not have results ready to return
3594 ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
3595 ** interfaces) then sqlite3_data_count(P) returns 0.
3596 ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
3597 **
3598 ** See also: [sqlite3_column_count()]
3599 */
3600 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
3601
3602 /*
3603 ** CAPI3REF: Fundamental Datatypes
3604 ** KEYWORDS: SQLITE_TEXT
3605 **
3606 ** ^(Every value in SQLite has one of five fundamental datatypes:
3607 **
3608 ** <ul>
3609 ** <li> 64-bit signed integer
3610 ** <li> 64-bit IEEE floating point number
3611 ** <li> string
3612 ** <li> BLOB
3613 ** <li> NULL
3614 ** </ul>)^
3615 **
3616 ** These constants are codes for each of those types.
3617 **
3618 ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
3619 ** for a completely different meaning.  Software that links against both
3620 ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
3621 ** SQLITE_TEXT.
3622 */
3623 #define SQLITE_INTEGER  1
3624 #define SQLITE_FLOAT    2
3625 #define SQLITE_BLOB     4
3626 #define SQLITE_NULL     5
3627 #ifdef SQLITE_TEXT
3628 # undef SQLITE_TEXT
3629 #else
3630 # define SQLITE_TEXT     3
3631 #endif
3632 #define SQLITE3_TEXT     3
3633
3634 /*
3635 ** CAPI3REF: Result Values From A Query
3636 ** KEYWORDS: {column access functions}
3637 **
3638 ** These routines form the "result set" interface.
3639 **
3640 ** ^These routines return information about a single column of the current
3641 ** result row of a query.  ^In every case the first argument is a pointer
3642 ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
3643 ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
3644 ** and the second argument is the index of the column for which information
3645 ** should be returned. ^The leftmost column of the result set has the index 0.
3646 ** ^The number of columns in the result can be determined using
3647 ** [sqlite3_column_count()].
3648 **
3649 ** If the SQL statement does not currently point to a valid row, or if the
3650 ** column index is out of range, the result is undefined.
3651 ** These routines may only be called when the most recent call to
3652 ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
3653 ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
3654 ** If any of these routines are called after [sqlite3_reset()] or
3655 ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
3656 ** something other than [SQLITE_ROW], the results are undefined.
3657 ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
3658 ** are called from a different thread while any of these routines
3659 ** are pending, then the results are undefined.
3660 **
3661 ** ^The sqlite3_column_type() routine returns the
3662 ** [SQLITE_INTEGER | datatype code] for the initial data type
3663 ** of the result column.  ^The returned value is one of [SQLITE_INTEGER],
3664 ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].  The value
3665 ** returned by sqlite3_column_type() is only meaningful if no type
3666 ** conversions have occurred as described below.  After a type conversion,
3667 ** the value returned by sqlite3_column_type() is undefined.  Future
3668 ** versions of SQLite may change the behavior of sqlite3_column_type()
3669 ** following a type conversion.
3670 **
3671 ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
3672 ** routine returns the number of bytes in that BLOB or string.
3673 ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
3674 ** the string to UTF-8 and then returns the number of bytes.
3675 ** ^If the result is a numeric value then sqlite3_column_bytes() uses
3676 ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
3677 ** the number of bytes in that string.
3678 ** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
3679 **
3680 ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
3681 ** routine returns the number of bytes in that BLOB or string.
3682 ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
3683 ** the string to UTF-16 and then returns the number of bytes.
3684 ** ^If the result is a numeric value then sqlite3_column_bytes16() uses
3685 ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
3686 ** the number of bytes in that string.
3687 ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
3688 **
3689 ** ^The values returned by [sqlite3_column_bytes()] and 
3690 ** [sqlite3_column_bytes16()] do not include the zero terminators at the end
3691 ** of the string.  ^For clarity: the values returned by
3692 ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
3693 ** bytes in the string, not the number of characters.
3694 **
3695 ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
3696 ** even empty strings, are always zero terminated.  ^The return
3697 ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
3698 **
3699 ** ^The object returned by [sqlite3_column_value()] is an
3700 ** [unprotected sqlite3_value] object.  An unprotected sqlite3_value object
3701 ** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
3702 ** If the [unprotected sqlite3_value] object returned by
3703 ** [sqlite3_column_value()] is used in any other way, including calls
3704 ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
3705 ** or [sqlite3_value_bytes()], then the behavior is undefined.
3706 **
3707 ** These routines attempt to convert the value where appropriate.  ^For
3708 ** example, if the internal representation is FLOAT and a text result
3709 ** is requested, [sqlite3_snprintf()] is used internally to perform the
3710 ** conversion automatically.  ^(The following table details the conversions
3711 ** that are applied:
3712 **
3713 ** <blockquote>
3714 ** <table border="1">
3715 ** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
3716 **
3717 ** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
3718 ** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
3719 ** <tr><td>  NULL    <td>   TEXT    <td> Result is NULL pointer
3720 ** <tr><td>  NULL    <td>   BLOB    <td> Result is NULL pointer
3721 ** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
3722 ** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
3723 ** <tr><td> INTEGER  <td>   BLOB    <td> Same as INTEGER->TEXT
3724 ** <tr><td>  FLOAT   <td> INTEGER   <td> Convert from float to integer
3725 ** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
3726 ** <tr><td>  FLOAT   <td>   BLOB    <td> Same as FLOAT->TEXT
3727 ** <tr><td>  TEXT    <td> INTEGER   <td> Use atoi()
3728 ** <tr><td>  TEXT    <td>  FLOAT    <td> Use atof()
3729 ** <tr><td>  TEXT    <td>   BLOB    <td> No change
3730 ** <tr><td>  BLOB    <td> INTEGER   <td> Convert to TEXT then use atoi()
3731 ** <tr><td>  BLOB    <td>  FLOAT    <td> Convert to TEXT then use atof()
3732 ** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
3733 ** </table>
3734 ** </blockquote>)^
3735 **
3736 ** The table above makes reference to standard C library functions atoi()
3737 ** and atof().  SQLite does not really use these functions.  It has its
3738 ** own equivalent internal routines.  The atoi() and atof() names are
3739 ** used in the table for brevity and because they are familiar to most
3740 ** C programmers.
3741 **
3742 ** Note that when type conversions occur, pointers returned by prior
3743 ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
3744 ** sqlite3_column_text16() may be invalidated.
3745 ** Type conversions and pointer invalidations might occur
3746 ** in the following cases:
3747 **
3748 ** <ul>
3749 ** <li> The initial content is a BLOB and sqlite3_column_text() or
3750 **      sqlite3_column_text16() is called.  A zero-terminator might
3751 **      need to be added to the string.</li>
3752 ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
3753 **      sqlite3_column_text16() is called.  The content must be converted
3754 **      to UTF-16.</li>
3755 ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
3756 **      sqlite3_column_text() is called.  The content must be converted
3757 **      to UTF-8.</li>
3758 ** </ul>
3759 **
3760 ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
3761 ** not invalidate a prior pointer, though of course the content of the buffer
3762 ** that the prior pointer references will have been modified.  Other kinds
3763 ** of conversion are done in place when it is possible, but sometimes they
3764 ** are not possible and in those cases prior pointers are invalidated.
3765 **
3766 ** The safest and easiest to remember policy is to invoke these routines
3767 ** in one of the following ways:
3768 **
3769 ** <ul>
3770 **  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
3771 **  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
3772 **  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
3773 ** </ul>
3774 **
3775 ** In other words, you should call sqlite3_column_text(),
3776 ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
3777 ** into the desired format, then invoke sqlite3_column_bytes() or
3778 ** sqlite3_column_bytes16() to find the size of the result.  Do not mix calls
3779 ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
3780 ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
3781 ** with calls to sqlite3_column_bytes().
3782 **
3783 ** ^The pointers returned are valid until a type conversion occurs as
3784 ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
3785 ** [sqlite3_finalize()] is called.  ^The memory space used to hold strings
3786 ** and BLOBs is freed automatically.  Do <b>not</b> pass the pointers returned
3787 ** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
3788 ** [sqlite3_free()].
3789 **
3790 ** ^(If a memory allocation error occurs during the evaluation of any
3791 ** of these routines, a default value is returned.  The default value
3792 ** is either the integer 0, the floating point number 0.0, or a NULL
3793 ** pointer.  Subsequent calls to [sqlite3_errcode()] will return
3794 ** [SQLITE_NOMEM].)^
3795 */
3796 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
3797 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
3798 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
3799 SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
3800 SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
3801 SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
3802 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
3803 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
3804 SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
3805 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
3806
3807 /*
3808 ** CAPI3REF: Destroy A Prepared Statement Object
3809 **
3810 ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
3811 ** ^If the most recent evaluation of the statement encountered no errors or
3812 ** or if the statement is never been evaluated, then sqlite3_finalize() returns
3813 ** SQLITE_OK.  ^If the most recent evaluation of statement S failed, then
3814 ** sqlite3_finalize(S) returns the appropriate [error code] or
3815 ** [extended error code].
3816 **
3817 ** ^The sqlite3_finalize(S) routine can be called at any point during
3818 ** the life cycle of [prepared statement] S:
3819 ** before statement S is ever evaluated, after
3820 ** one or more calls to [sqlite3_reset()], or after any call
3821 ** to [sqlite3_step()] regardless of whether or not the statement has
3822 ** completed execution.
3823 **
3824 ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
3825 **
3826 ** The application must finalize every [prepared statement] in order to avoid
3827 ** resource leaks.  It is a grievous error for the application to try to use
3828 ** a prepared statement after it has been finalized.  Any use of a prepared
3829 ** statement after it has been finalized can result in undefined and
3830 ** undesirable behavior such as segfaults and heap corruption.
3831 */
3832 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
3833
3834 /*
3835 ** CAPI3REF: Reset A Prepared Statement Object
3836 **
3837 ** The sqlite3_reset() function is called to reset a [prepared statement]
3838 ** object back to its initial state, ready to be re-executed.
3839 ** ^Any SQL statement variables that had values bound to them using
3840 ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
3841 ** Use [sqlite3_clear_bindings()] to reset the bindings.
3842 **
3843 ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
3844 ** back to the beginning of its program.
3845 **
3846 ** ^If the most recent call to [sqlite3_step(S)] for the
3847 ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
3848 ** or if [sqlite3_step(S)] has never before been called on S,
3849 ** then [sqlite3_reset(S)] returns [SQLITE_OK].
3850 **
3851 ** ^If the most recent call to [sqlite3_step(S)] for the
3852 ** [prepared statement] S indicated an error, then
3853 ** [sqlite3_reset(S)] returns an appropriate [error code].
3854 **
3855 ** ^The [sqlite3_reset(S)] interface does not change the values
3856 ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
3857 */
3858 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
3859
3860 /*
3861 ** CAPI3REF: Create Or Redefine SQL Functions
3862 ** KEYWORDS: {function creation routines}
3863 ** KEYWORDS: {application-defined SQL function}
3864 ** KEYWORDS: {application-defined SQL functions}
3865 **
3866 ** ^These functions (collectively known as "function creation routines")
3867 ** are used to add SQL functions or aggregates or to redefine the behavior
3868 ** of existing SQL functions or aggregates.  The only differences between
3869 ** these routines are the text encoding expected for
3870 ** the the second parameter (the name of the function being created)
3871 ** and the presence or absence of a destructor callback for
3872 ** the application data pointer.
3873 **
3874 ** ^The first parameter is the [database connection] to which the SQL
3875 ** function is to be added.  ^If an application uses more than one database
3876 ** connection then application-defined SQL functions must be added
3877 ** to each database connection separately.
3878 **
3879 ** ^The second parameter is the name of the SQL function to be created or
3880 ** redefined.  ^The length of the name is limited to 255 bytes in a UTF-8
3881 ** representation, exclusive of the zero-terminator.  ^Note that the name
3882 ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.  
3883 ** ^Any attempt to create a function with a longer name
3884 ** will result in [SQLITE_MISUSE] being returned.
3885 **
3886 ** ^The third parameter (nArg)
3887 ** is the number of arguments that the SQL function or
3888 ** aggregate takes. ^If this parameter is -1, then the SQL function or
3889 ** aggregate may take any number of arguments between 0 and the limit
3890 ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]).  If the third
3891 ** parameter is less than -1 or greater than 127 then the behavior is
3892 ** undefined.
3893 **
3894 ** ^The fourth parameter, eTextRep, specifies what
3895 ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
3896 ** its parameters.  Every SQL function implementation must be able to work
3897 ** with UTF-8, UTF-16le, or UTF-16be.  But some implementations may be
3898 ** more efficient with one encoding than another.  ^An application may
3899 ** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
3900 ** times with the same function but with different values of eTextRep.
3901 ** ^When multiple implementations of the same function are available, SQLite
3902 ** will pick the one that involves the least amount of data conversion.
3903 ** If there is only a single implementation which does not care what text
3904 ** encoding is used, then the fourth argument should be [SQLITE_ANY].
3905 **
3906 ** ^(The fifth parameter is an arbitrary pointer.  The implementation of the
3907 ** function can gain access to this pointer using [sqlite3_user_data()].)^
3908 **
3909 ** ^The seventh, eighth and ninth parameters, xFunc, xStep and xFinal, are
3910 ** pointers to C-language functions that implement the SQL function or
3911 ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
3912 ** callback only; NULL pointers must be passed as the xStep and xFinal
3913 ** parameters. ^An aggregate SQL function requires an implementation of xStep
3914 ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
3915 ** SQL function or aggregate, pass NULL poiners for all three function
3916 ** callbacks.
3917 **
3918 ** ^If the tenth parameter to sqlite3_create_function_v2() is not NULL,
3919 ** then it is invoked when the function is deleted, either by being
3920 ** overloaded or when the database connection closes.
3921 ** ^When the destructure callback of the tenth parameter is invoked, it
3922 ** is passed a single argument which is a copy of the pointer which was
3923 ** the fifth parameter to sqlite3_create_function_v2().
3924 **
3925 ** ^It is permitted to register multiple implementations of the same
3926 ** functions with the same name but with either differing numbers of
3927 ** arguments or differing preferred text encodings.  ^SQLite will use
3928 ** the implementation that most closely matches the way in which the
3929 ** SQL function is used.  ^A function implementation with a non-negative
3930 ** nArg parameter is a better match than a function implementation with
3931 ** a negative nArg.  ^A function where the preferred text encoding
3932 ** matches the database encoding is a better
3933 ** match than a function where the encoding is different.  
3934 ** ^A function where the encoding difference is between UTF16le and UTF16be
3935 ** is a closer match than a function where the encoding difference is
3936 ** between UTF8 and UTF16.
3937 **
3938 ** ^Built-in functions may be overloaded by new application-defined functions.
3939 **
3940 ** ^An application-defined function is permitted to call other
3941 ** SQLite interfaces.  However, such calls must not
3942 ** close the database connection nor finalize or reset the prepared
3943 ** statement in which the function is running.
3944 */
3945 SQLITE_API int sqlite3_create_function(
3946   sqlite3 *db,
3947   const char *zFunctionName,
3948   int nArg,
3949   int eTextRep,
3950   void *pApp,
3951   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
3952   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
3953   void (*xFinal)(sqlite3_context*)
3954 );
3955 SQLITE_API int sqlite3_create_function16(
3956   sqlite3 *db,
3957   const void *zFunctionName,
3958   int nArg,
3959   int eTextRep,
3960   void *pApp,
3961   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
3962   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
3963   void (*xFinal)(sqlite3_context*)
3964 );
3965 SQLITE_API int sqlite3_create_function_v2(
3966   sqlite3 *db,
3967   const char *zFunctionName,
3968   int nArg,
3969   int eTextRep,
3970   void *pApp,
3971   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
3972   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
3973   void (*xFinal)(sqlite3_context*),
3974   void(*xDestroy)(void*)
3975 );
3976
3977 /*
3978 ** CAPI3REF: Text Encodings
3979 **
3980 ** These constant define integer codes that represent the various
3981 ** text encodings supported by SQLite.
3982 */
3983 #define SQLITE_UTF8           1
3984 #define SQLITE_UTF16LE        2
3985 #define SQLITE_UTF16BE        3
3986 #define SQLITE_UTF16          4    /* Use native byte order */
3987 #define SQLITE_ANY            5    /* sqlite3_create_function only */
3988 #define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */
3989
3990 /*
3991 ** CAPI3REF: Deprecated Functions
3992 ** DEPRECATED
3993 **
3994 ** These functions are [deprecated].  In order to maintain
3995 ** backwards compatibility with older code, these functions continue 
3996 ** to be supported.  However, new applications should avoid
3997 ** the use of these functions.  To help encourage people to avoid
3998 ** using these functions, we are not going to tell you what they do.
3999 */
4000 #ifndef SQLITE_OMIT_DEPRECATED
4001 SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
4002 SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
4003 SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
4004 SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
4005 SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
4006 SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64);
4007 #endif
4008
4009 /*
4010 ** CAPI3REF: Obtaining SQL Function Parameter Values
4011 **
4012 ** The C-language implementation of SQL functions and aggregates uses
4013 ** this set of interface routines to access the parameter values on
4014 ** the function or aggregate.
4015 **
4016 ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
4017 ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
4018 ** define callbacks that implement the SQL functions and aggregates.
4019 ** The 4th parameter to these callbacks is an array of pointers to
4020 ** [protected sqlite3_value] objects.  There is one [sqlite3_value] object for
4021 ** each parameter to the SQL function.  These routines are used to
4022 ** extract values from the [sqlite3_value] objects.
4023 **
4024 ** These routines work only with [protected sqlite3_value] objects.
4025 ** Any attempt to use these routines on an [unprotected sqlite3_value]
4026 ** object results in undefined behavior.
4027 **
4028 ** ^These routines work just like the corresponding [column access functions]
4029 ** except that  these routines take a single [protected sqlite3_value] object
4030 ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
4031 **
4032 ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
4033 ** in the native byte-order of the host machine.  ^The
4034 ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
4035 ** extract UTF-16 strings as big-endian and little-endian respectively.
4036 **
4037 ** ^(The sqlite3_value_numeric_type() interface attempts to apply
4038 ** numeric affinity to the value.  This means that an attempt is
4039 ** made to convert the value to an integer or floating point.  If
4040 ** such a conversion is possible without loss of information (in other
4041 ** words, if the value is a string that looks like a number)
4042 ** then the conversion is performed.  Otherwise no conversion occurs.
4043 ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
4044 **
4045 ** Please pay particular attention to the fact that the pointer returned
4046 ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
4047 ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
4048 ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
4049 ** or [sqlite3_value_text16()].
4050 **
4051 ** These routines must be called from the same thread as
4052 ** the SQL function that supplied the [sqlite3_value*] parameters.
4053 */
4054 SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
4055 SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
4056 SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
4057 SQLITE_API double sqlite3_value_double(sqlite3_value*);
4058 SQLITE_API int sqlite3_value_int(sqlite3_value*);
4059 SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
4060 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
4061 SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
4062 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
4063 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
4064 SQLITE_API int sqlite3_value_type(sqlite3_value*);
4065 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
4066
4067 /*
4068 ** CAPI3REF: Obtain Aggregate Function Context
4069 **
4070 ** Implementations of aggregate SQL functions use this
4071 ** routine to allocate memory for storing their state.
4072 **
4073 ** ^The first time the sqlite3_aggregate_context(C,N) routine is called 
4074 ** for a particular aggregate function, SQLite
4075 ** allocates N of memory, zeroes out that memory, and returns a pointer
4076 ** to the new memory. ^On second and subsequent calls to
4077 ** sqlite3_aggregate_context() for the same aggregate function instance,
4078 ** the same buffer is returned.  Sqlite3_aggregate_context() is normally
4079 ** called once for each invocation of the xStep callback and then one
4080 ** last time when the xFinal callback is invoked.  ^(When no rows match
4081 ** an aggregate query, the xStep() callback of the aggregate function
4082 ** implementation is never called and xFinal() is called exactly once.
4083 ** In those cases, sqlite3_aggregate_context() might be called for the
4084 ** first time from within xFinal().)^
4085 **
4086 ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer if N is
4087 ** less than or equal to zero or if a memory allocate error occurs.
4088 **
4089 ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
4090 ** determined by the N parameter on first successful call.  Changing the
4091 ** value of N in subsequent call to sqlite3_aggregate_context() within
4092 ** the same aggregate function instance will not resize the memory
4093 ** allocation.)^
4094 **
4095 ** ^SQLite automatically frees the memory allocated by 
4096 ** sqlite3_aggregate_context() when the aggregate query concludes.
4097 **
4098 ** The first parameter must be a copy of the
4099 ** [sqlite3_context | SQL function context] that is the first parameter
4100 ** to the xStep or xFinal callback routine that implements the aggregate
4101 ** function.
4102 **
4103 ** This routine must be called from the same thread in which
4104 ** the aggregate SQL function is running.
4105 */
4106 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
4107
4108 /*
4109 ** CAPI3REF: User Data For Functions
4110 **
4111 ** ^The sqlite3_user_data() interface returns a copy of
4112 ** the pointer that was the pUserData parameter (the 5th parameter)
4113 ** of the [sqlite3_create_function()]
4114 ** and [sqlite3_create_function16()] routines that originally
4115 ** registered the application defined function.
4116 **
4117 ** This routine must be called from the same thread in which
4118 ** the application-defined function is running.
4119 */
4120 SQLITE_API void *sqlite3_user_data(sqlite3_context*);
4121
4122 /*
4123 ** CAPI3REF: Database Connection For Functions
4124 **
4125 ** ^The sqlite3_context_db_handle() interface returns a copy of
4126 ** the pointer to the [database connection] (the 1st parameter)
4127 ** of the [sqlite3_create_function()]
4128 ** and [sqlite3_create_function16()] routines that originally
4129 ** registered the application defined function.
4130 */
4131 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
4132
4133 /*
4134 ** CAPI3REF: Function Auxiliary Data
4135 **
4136 ** The following two functions may be used by scalar SQL functions to
4137 ** associate metadata with argument values. If the same value is passed to
4138 ** multiple invocations of the same SQL function during query execution, under
4139 ** some circumstances the associated metadata may be preserved. This may
4140 ** be used, for example, to add a regular-expression matching scalar
4141 ** function. The compiled version of the regular expression is stored as
4142 ** metadata associated with the SQL value passed as the regular expression
4143 ** pattern.  The compiled regular expression can be reused on multiple
4144 ** invocations of the same function so that the original pattern string
4145 ** does not need to be recompiled on each invocation.
4146 **
4147 ** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
4148 ** associated by the sqlite3_set_auxdata() function with the Nth argument
4149 ** value to the application-defined function. ^If no metadata has been ever
4150 ** been set for the Nth argument of the function, or if the corresponding
4151 ** function parameter has changed since the meta-data was set,
4152 ** then sqlite3_get_auxdata() returns a NULL pointer.
4153 **
4154 ** ^The sqlite3_set_auxdata() interface saves the metadata
4155 ** pointed to by its 3rd parameter as the metadata for the N-th
4156 ** argument of the application-defined function.  Subsequent
4157 ** calls to sqlite3_get_auxdata() might return this data, if it has
4158 ** not been destroyed.
4159 ** ^If it is not NULL, SQLite will invoke the destructor
4160 ** function given by the 4th parameter to sqlite3_set_auxdata() on
4161 ** the metadata when the corresponding function parameter changes
4162 ** or when the SQL statement completes, whichever comes first.
4163 **
4164 ** SQLite is free to call the destructor and drop metadata on any
4165 ** parameter of any function at any time.  ^The only guarantee is that
4166 ** the destructor will be called before the metadata is dropped.
4167 **
4168 ** ^(In practice, metadata is preserved between function calls for
4169 ** expressions that are constant at compile time. This includes literal
4170 ** values and [parameters].)^
4171 **
4172 ** These routines must be called from the same thread in which
4173 ** the SQL function is running.
4174 */
4175 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
4176 SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
4177
4178
4179 /*
4180 ** CAPI3REF: Constants Defining Special Destructor Behavior
4181 **
4182 ** These are special values for the destructor that is passed in as the
4183 ** final argument to routines like [sqlite3_result_blob()].  ^If the destructor
4184 ** argument is SQLITE_STATIC, it means that the content pointer is constant
4185 ** and will never change.  It does not need to be destroyed.  ^The
4186 ** SQLITE_TRANSIENT value means that the content will likely change in
4187 ** the near future and that SQLite should make its own private copy of
4188 ** the content before returning.
4189 **
4190 ** The typedef is necessary to work around problems in certain
4191 ** C++ compilers.  See ticket #2191.
4192 */
4193 typedef void (*sqlite3_destructor_type)(void*);
4194 #define SQLITE_STATIC      ((sqlite3_destructor_type)0)
4195 #define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)
4196
4197 /*
4198 ** CAPI3REF: Setting The Result Of An SQL Function
4199 **
4200 ** These routines are used by the xFunc or xFinal callbacks that
4201 ** implement SQL functions and aggregates.  See
4202 ** [sqlite3_create_function()] and [sqlite3_create_function16()]
4203 ** for additional information.
4204 **
4205 ** These functions work very much like the [parameter binding] family of
4206 ** functions used to bind values to host parameters in prepared statements.
4207 ** Refer to the [SQL parameter] documentation for additional information.
4208 **
4209 ** ^The sqlite3_result_blob() interface sets the result from
4210 ** an application-defined function to be the BLOB whose content is pointed
4211 ** to by the second parameter and which is N bytes long where N is the
4212 ** third parameter.
4213 **
4214 ** ^The sqlite3_result_zeroblob() interfaces set the result of
4215 ** the application-defined function to be a BLOB containing all zero
4216 ** bytes and N bytes in size, where N is the value of the 2nd parameter.
4217 **
4218 ** ^The sqlite3_result_double() interface sets the result from
4219 ** an application-defined function to be a floating point value specified
4220 ** by its 2nd argument.
4221 **
4222 ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
4223 ** cause the implemented SQL function to throw an exception.
4224 ** ^SQLite uses the string pointed to by the
4225 ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
4226 ** as the text of an error message.  ^SQLite interprets the error
4227 ** message string from sqlite3_result_error() as UTF-8. ^SQLite
4228 ** interprets the string from sqlite3_result_error16() as UTF-16 in native
4229 ** byte order.  ^If the third parameter to sqlite3_result_error()
4230 ** or sqlite3_result_error16() is negative then SQLite takes as the error
4231 ** message all text up through the first zero character.
4232 ** ^If the third parameter to sqlite3_result_error() or
4233 ** sqlite3_result_error16() is non-negative then SQLite takes that many
4234 ** bytes (not characters) from the 2nd parameter as the error message.
4235 ** ^The sqlite3_result_error() and sqlite3_result_error16()
4236 ** routines make a private copy of the error message text before
4237 ** they return.  Hence, the calling function can deallocate or
4238 ** modify the text after they return without harm.
4239 ** ^The sqlite3_result_error_code() function changes the error code
4240 ** returned by SQLite as a result of an error in a function.  ^By default,
4241 ** the error code is SQLITE_ERROR.  ^A subsequent call to sqlite3_result_error()
4242 ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
4243 **
4244 ** ^The sqlite3_result_toobig() interface causes SQLite to throw an error
4245 ** indicating that a string or BLOB is too long to represent.
4246 **
4247 ** ^The sqlite3_result_nomem() interface causes SQLite to throw an error
4248 ** indicating that a memory allocation failed.
4249 **
4250 ** ^The sqlite3_result_int() interface sets the return value
4251 ** of the application-defined function to be the 32-bit signed integer
4252 ** value given in the 2nd argument.
4253 ** ^The sqlite3_result_int64() interface sets the return value
4254 ** of the application-defined function to be the 64-bit signed integer
4255 ** value given in the 2nd argument.
4256 **
4257 ** ^The sqlite3_result_null() interface sets the return value
4258 ** of the application-defined function to be NULL.
4259 **
4260 ** ^The sqlite3_result_text(), sqlite3_result_text16(),
4261 ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
4262 ** set the return value of the application-defined function to be
4263 ** a text string which is represented as UTF-8, UTF-16 native byte order,
4264 ** UTF-16 little endian, or UTF-16 big endian, respectively.
4265 ** ^SQLite takes the text result from the application from
4266 ** the 2nd parameter of the sqlite3_result_text* interfaces.
4267 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4268 ** is negative, then SQLite takes result text from the 2nd parameter
4269 ** through the first zero character.
4270 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4271 ** is non-negative, then as many bytes (not characters) of the text
4272 ** pointed to by the 2nd parameter are taken as the application-defined
4273 ** function result.
4274 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
4275 ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
4276 ** function as the destructor on the text or BLOB result when it has
4277 ** finished using that result.
4278 ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
4279 ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
4280 ** assumes that the text or BLOB result is in constant space and does not
4281 ** copy the content of the parameter nor call a destructor on the content
4282 ** when it has finished using that result.
4283 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
4284 ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
4285 ** then SQLite makes a copy of the result into space obtained from
4286 ** from [sqlite3_malloc()] before it returns.
4287 **
4288 ** ^The sqlite3_result_value() interface sets the result of
4289 ** the application-defined function to be a copy the
4290 ** [unprotected sqlite3_value] object specified by the 2nd parameter.  ^The
4291 ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
4292 ** so that the [sqlite3_value] specified in the parameter may change or
4293 ** be deallocated after sqlite3_result_value() returns without harm.
4294 ** ^A [protected sqlite3_value] object may always be used where an
4295 ** [unprotected sqlite3_value] object is required, so either
4296 ** kind of [sqlite3_value] object can be used with this interface.
4297 **
4298 ** If these routines are called from within the different thread
4299 ** than the one containing the application-defined function that received
4300 ** the [sqlite3_context] pointer, the results are undefined.
4301 */
4302 SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
4303 SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
4304 SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
4305 SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
4306 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
4307 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
4308 SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
4309 SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
4310 SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
4311 SQLITE_API void sqlite3_result_null(sqlite3_context*);
4312 SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
4313 SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
4314 SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
4315 SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
4316 SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
4317 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
4318
4319 /*
4320 ** CAPI3REF: Define New Collating Sequences
4321 **
4322 ** ^These functions add, remove, or modify a [collation] associated
4323 ** with the [database connection] specified as the first argument.
4324 **
4325 ** ^The name of the collation is a UTF-8 string
4326 ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
4327 ** and a UTF-16 string in native byte order for sqlite3_create_collation16().
4328 ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
4329 ** considered to be the same name.
4330 **
4331 ** ^(The third argument (eTextRep) must be one of the constants:
4332 ** <ul>
4333 ** <li> [SQLITE_UTF8],
4334 ** <li> [SQLITE_UTF16LE],
4335 ** <li> [SQLITE_UTF16BE],
4336 ** <li> [SQLITE_UTF16], or
4337 ** <li> [SQLITE_UTF16_ALIGNED].
4338 ** </ul>)^
4339 ** ^The eTextRep argument determines the encoding of strings passed
4340 ** to the collating function callback, xCallback.
4341 ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
4342 ** force strings to be UTF16 with native byte order.
4343 ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
4344 ** on an even byte address.
4345 **
4346 ** ^The fourth argument, pArg, is a application data pointer that is passed
4347 ** through as the first argument to the collating function callback.
4348 **
4349 ** ^The fifth argument, xCallback, is a pointer to the collating function.
4350 ** ^Multiple collating functions can be registered using the same name but
4351 ** with different eTextRep parameters and SQLite will use whichever
4352 ** function requires the least amount of data transformation.
4353 ** ^If the xCallback argument is NULL then the collating function is
4354 ** deleted.  ^When all collating functions having the same name are deleted,
4355 ** that collation is no longer usable.
4356 **
4357 ** ^The collating function callback is invoked with a copy of the pArg 
4358 ** application data pointer and with two strings in the encoding specified
4359 ** by the eTextRep argument.  The collating function must return an
4360 ** integer that is negative, zero, or positive
4361 ** if the first string is less than, equal to, or greater than the second,
4362 ** respectively.  A collating function must alway return the same answer
4363 ** given the same inputs.  If two or more collating functions are registered
4364 ** to the same collation name (using different eTextRep values) then all
4365 ** must give an equivalent answer when invoked with equivalent strings.
4366 ** The collating function must obey the following properties for all
4367 ** strings A, B, and C:
4368 **
4369 ** <ol>
4370 ** <li> If A==B then B==A.
4371 ** <li> If A==B and B==C then A==C.
4372 ** <li> If A&lt;B THEN B&gt;A.
4373 ** <li> If A&lt;B and B&lt;C then A&lt;C.
4374 ** </ol>
4375 **
4376 ** If a collating function fails any of the above constraints and that
4377 ** collating function is  registered and used, then the behavior of SQLite
4378 ** is undefined.
4379 **
4380 ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
4381 ** with the addition that the xDestroy callback is invoked on pArg when
4382 ** the collating function is deleted.
4383 ** ^Collating functions are deleted when they are overridden by later
4384 ** calls to the collation creation functions or when the
4385 ** [database connection] is closed using [sqlite3_close()].
4386 **
4387 ** See also:  [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
4388 */
4389 SQLITE_API int sqlite3_create_collation(
4390   sqlite3*, 
4391   const char *zName, 
4392   int eTextRep, 
4393   void *pArg,
4394   int(*xCompare)(void*,int,const void*,int,const void*)
4395 );
4396 SQLITE_API int sqlite3_create_collation_v2(
4397   sqlite3*, 
4398   const char *zName, 
4399   int eTextRep, 
4400   void *pArg,
4401   int(*xCompare)(void*,int,const void*,int,const void*),
4402   void(*xDestroy)(void*)
4403 );
4404 SQLITE_API int sqlite3_create_collation16(
4405   sqlite3*, 
4406   const void *zName,
4407   int eTextRep, 
4408   void *pArg,
4409   int(*xCompare)(void*,int,const void*,int,const void*)
4410 );
4411
4412 /*
4413 ** CAPI3REF: Collation Needed Callbacks
4414 **
4415 ** ^To avoid having to register all collation sequences before a database
4416 ** can be used, a single callback function may be registered with the
4417 ** [database connection] to be invoked whenever an undefined collation
4418 ** sequence is required.
4419 **
4420 ** ^If the function is registered using the sqlite3_collation_needed() API,
4421 ** then it is passed the names of undefined collation sequences as strings
4422 ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
4423 ** the names are passed as UTF-16 in machine native byte order.
4424 ** ^A call to either function replaces the existing collation-needed callback.
4425 **
4426 ** ^(When the callback is invoked, the first argument passed is a copy
4427 ** of the second argument to sqlite3_collation_needed() or
4428 ** sqlite3_collation_needed16().  The second argument is the database
4429 ** connection.  The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
4430 ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
4431 ** sequence function required.  The fourth parameter is the name of the
4432 ** required collation sequence.)^
4433 **
4434 ** The callback function should register the desired collation using
4435 ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
4436 ** [sqlite3_create_collation_v2()].
4437 */
4438 SQLITE_API int sqlite3_collation_needed(
4439   sqlite3*, 
4440   void*, 
4441   void(*)(void*,sqlite3*,int eTextRep,const char*)
4442 );
4443 SQLITE_API int sqlite3_collation_needed16(
4444   sqlite3*, 
4445   void*,
4446   void(*)(void*,sqlite3*,int eTextRep,const void*)
4447 );
4448
4449 #ifdef SQLITE_HAS_CODEC
4450 /*
4451 ** Specify the key for an encrypted database.  This routine should be
4452 ** called right after sqlite3_open().
4453 **
4454 ** The code to implement this API is not available in the public release
4455 ** of SQLite.
4456 */
4457 SQLITE_API int sqlite3_key(
4458   sqlite3 *db,                   /* Database to be rekeyed */
4459   const void *pKey, int nKey     /* The key */
4460 );
4461
4462 /*
4463 ** Change the key on an open database.  If the current database is not
4464 ** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
4465 ** database is decrypted.
4466 **
4467 ** The code to implement this API is not available in the public release
4468 ** of SQLite.
4469 */
4470 SQLITE_API int sqlite3_rekey(
4471   sqlite3 *db,                   /* Database to be rekeyed */
4472   const void *pKey, int nKey     /* The new key */
4473 );
4474
4475 /*
4476 ** Specify the activation key for a SEE database.  Unless 
4477 ** activated, none of the SEE routines will work.
4478 */
4479 SQLITE_API void sqlite3_activate_see(
4480   const char *zPassPhrase        /* Activation phrase */
4481 );
4482 #endif
4483
4484 #ifdef SQLITE_ENABLE_CEROD
4485 /*
4486 ** Specify the activation key for a CEROD database.  Unless 
4487 ** activated, none of the CEROD routines will work.
4488 */
4489 SQLITE_API void sqlite3_activate_cerod(
4490   const char *zPassPhrase        /* Activation phrase */
4491 );
4492 #endif
4493
4494 /*
4495 ** CAPI3REF: Suspend Execution For A Short Time
4496 **
4497 ** The sqlite3_sleep() function causes the current thread to suspend execution
4498 ** for at least a number of milliseconds specified in its parameter.
4499 **
4500 ** If the operating system does not support sleep requests with
4501 ** millisecond time resolution, then the time will be rounded up to
4502 ** the nearest second. The number of milliseconds of sleep actually
4503 ** requested from the operating system is returned.
4504 **
4505 ** ^SQLite implements this interface by calling the xSleep()
4506 ** method of the default [sqlite3_vfs] object.  If the xSleep() method
4507 ** of the default VFS is not implemented correctly, or not implemented at
4508 ** all, then the behavior of sqlite3_sleep() may deviate from the description
4509 ** in the previous paragraphs.
4510 */
4511 SQLITE_API int sqlite3_sleep(int);
4512
4513 /*
4514 ** CAPI3REF: Name Of The Folder Holding Temporary Files
4515 **
4516 ** ^(If this global variable is made to point to a string which is
4517 ** the name of a folder (a.k.a. directory), then all temporary files
4518 ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
4519 ** will be placed in that directory.)^  ^If this variable
4520 ** is a NULL pointer, then SQLite performs a search for an appropriate
4521 ** temporary file directory.
4522 **
4523 ** It is not safe to read or modify this variable in more than one
4524 ** thread at a time.  It is not safe to read or modify this variable
4525 ** if a [database connection] is being used at the same time in a separate
4526 ** thread.
4527 ** It is intended that this variable be set once
4528 ** as part of process initialization and before any SQLite interface
4529 ** routines have been called and that this variable remain unchanged
4530 ** thereafter.
4531 **
4532 ** ^The [temp_store_directory pragma] may modify this variable and cause
4533 ** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
4534 ** the [temp_store_directory pragma] always assumes that any string
4535 ** that this variable points to is held in memory obtained from 
4536 ** [sqlite3_malloc] and the pragma may attempt to free that memory
4537 ** using [sqlite3_free].
4538 ** Hence, if this variable is modified directly, either it should be
4539 ** made NULL or made to point to memory obtained from [sqlite3_malloc]
4540 ** or else the use of the [temp_store_directory pragma] should be avoided.
4541 */
4542 SQLITE_API char *sqlite3_temp_directory;
4543
4544 /*
4545 ** CAPI3REF: Test For Auto-Commit Mode
4546 ** KEYWORDS: {autocommit mode}
4547 **
4548 ** ^The sqlite3_get_autocommit() interface returns non-zero or
4549 ** zero if the given database connection is or is not in autocommit mode,
4550 ** respectively.  ^Autocommit mode is on by default.
4551 ** ^Autocommit mode is disabled by a [BEGIN] statement.
4552 ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
4553 **
4554 ** If certain kinds of errors occur on a statement within a multi-statement
4555 ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
4556 ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
4557 ** transaction might be rolled back automatically.  The only way to
4558 ** find out whether SQLite automatically rolled back the transaction after
4559 ** an error is to use this function.
4560 **
4561 ** If another thread changes the autocommit status of the database
4562 ** connection while this routine is running, then the return value
4563 ** is undefined.
4564 */
4565 SQLITE_API int sqlite3_get_autocommit(sqlite3*);
4566
4567 /*
4568 ** CAPI3REF: Find The Database Handle Of A Prepared Statement
4569 **
4570 ** ^The sqlite3_db_handle interface returns the [database connection] handle
4571 ** to which a [prepared statement] belongs.  ^The [database connection]
4572 ** returned by sqlite3_db_handle is the same [database connection]
4573 ** that was the first argument
4574 ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
4575 ** create the statement in the first place.
4576 */
4577 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
4578
4579 /*
4580 ** CAPI3REF: Find the next prepared statement
4581 **
4582 ** ^This interface returns a pointer to the next [prepared statement] after
4583 ** pStmt associated with the [database connection] pDb.  ^If pStmt is NULL
4584 ** then this interface returns a pointer to the first prepared statement
4585 ** associated with the database connection pDb.  ^If no prepared statement
4586 ** satisfies the conditions of this routine, it returns NULL.
4587 **
4588 ** The [database connection] pointer D in a call to
4589 ** [sqlite3_next_stmt(D,S)] must refer to an open database
4590 ** connection and in particular must not be a NULL pointer.
4591 */
4592 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
4593
4594 /*
4595 ** CAPI3REF: Commit And Rollback Notification Callbacks
4596 **
4597 ** ^The sqlite3_commit_hook() interface registers a callback
4598 ** function to be invoked whenever a transaction is [COMMIT | committed].
4599 ** ^Any callback set by a previous call to sqlite3_commit_hook()
4600 ** for the same database connection is overridden.
4601 ** ^The sqlite3_rollback_hook() interface registers a callback
4602 ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
4603 ** ^Any callback set by a previous call to sqlite3_rollback_hook()
4604 ** for the same database connection is overridden.
4605 ** ^The pArg argument is passed through to the callback.
4606 ** ^If the callback on a commit hook function returns non-zero,
4607 ** then the commit is converted into a rollback.
4608 **
4609 ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
4610 ** return the P argument from the previous call of the same function
4611 ** on the same [database connection] D, or NULL for
4612 ** the first call for each function on D.
4613 **
4614 ** The callback implementation must not do anything that will modify
4615 ** the database connection that invoked the callback.  Any actions
4616 ** to modify the database connection must be deferred until after the
4617 ** completion of the [sqlite3_step()] call that triggered the commit
4618 ** or rollback hook in the first place.
4619 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
4620 ** database connections for the meaning of "modify" in this paragraph.
4621 **
4622 ** ^Registering a NULL function disables the callback.
4623 **
4624 ** ^When the commit hook callback routine returns zero, the [COMMIT]
4625 ** operation is allowed to continue normally.  ^If the commit hook
4626 ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
4627 ** ^The rollback hook is invoked on a rollback that results from a commit
4628 ** hook returning non-zero, just as it would be with any other rollback.
4629 **
4630 ** ^For the purposes of this API, a transaction is said to have been
4631 ** rolled back if an explicit "ROLLBACK" statement is executed, or
4632 ** an error or constraint causes an implicit rollback to occur.
4633 ** ^The rollback callback is not invoked if a transaction is
4634 ** automatically rolled back because the database connection is closed.
4635 **
4636 ** See also the [sqlite3_update_hook()] interface.
4637 */
4638 SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
4639 SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
4640
4641 /*
4642 ** CAPI3REF: Data Change Notification Callbacks
4643 **
4644 ** ^The sqlite3_update_hook() interface registers a callback function
4645 ** with the [database connection] identified by the first argument
4646 ** to be invoked whenever a row is updated, inserted or deleted.
4647 ** ^Any callback set by a previous call to this function
4648 ** for the same database connection is overridden.
4649 **
4650 ** ^The second argument is a pointer to the function to invoke when a
4651 ** row is updated, inserted or deleted.
4652 ** ^The first argument to the callback is a copy of the third argument
4653 ** to sqlite3_update_hook().
4654 ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
4655 ** or [SQLITE_UPDATE], depending on the operation that caused the callback
4656 ** to be invoked.
4657 ** ^The third and fourth arguments to the callback contain pointers to the
4658 ** database and table name containing the affected row.
4659 ** ^The final callback parameter is the [rowid] of the row.
4660 ** ^In the case of an update, this is the [rowid] after the update takes place.
4661 **
4662 ** ^(The update hook is not invoked when internal system tables are
4663 ** modified (i.e. sqlite_master and sqlite_sequence).)^
4664 **
4665 ** ^In the current implementation, the update hook
4666 ** is not invoked when duplication rows are deleted because of an
4667 ** [ON CONFLICT | ON CONFLICT REPLACE] clause.  ^Nor is the update hook
4668 ** invoked when rows are deleted using the [truncate optimization].
4669 ** The exceptions defined in this paragraph might change in a future
4670 ** release of SQLite.
4671 **
4672 ** The update hook implementation must not do anything that will modify
4673 ** the database connection that invoked the update hook.  Any actions
4674 ** to modify the database connection must be deferred until after the
4675 ** completion of the [sqlite3_step()] call that triggered the update hook.
4676 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
4677 ** database connections for the meaning of "modify" in this paragraph.
4678 **
4679 ** ^The sqlite3_update_hook(D,C,P) function
4680 ** returns the P argument from the previous call
4681 ** on the same [database connection] D, or NULL for
4682 ** the first call on D.
4683 **
4684 ** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
4685 ** interfaces.
4686 */
4687 SQLITE_API void *sqlite3_update_hook(
4688   sqlite3*, 
4689   void(*)(void *,int ,char const *,char const *,sqlite3_int64),
4690   void*
4691 );
4692
4693 /*
4694 ** CAPI3REF: Enable Or Disable Shared Pager Cache
4695 ** KEYWORDS: {shared cache}
4696 **
4697 ** ^(This routine enables or disables the sharing of the database cache
4698 ** and schema data structures between [database connection | connections]
4699 ** to the same database. Sharing is enabled if the argument is true
4700 ** and disabled if the argument is false.)^
4701 **
4702 ** ^Cache sharing is enabled and disabled for an entire process.
4703 ** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
4704 ** sharing was enabled or disabled for each thread separately.
4705 **
4706 ** ^(The cache sharing mode set by this interface effects all subsequent
4707 ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
4708 ** Existing database connections continue use the sharing mode
4709 ** that was in effect at the time they were opened.)^
4710 **
4711 ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
4712 ** successfully.  An [error code] is returned otherwise.)^
4713 **
4714 ** ^Shared cache is disabled by default. But this might change in
4715 ** future releases of SQLite.  Applications that care about shared
4716 ** cache setting should set it explicitly.
4717 **
4718 ** See Also:  [SQLite Shared-Cache Mode]
4719 */
4720 SQLITE_API int sqlite3_enable_shared_cache(int);
4721
4722 /*
4723 ** CAPI3REF: Attempt To Free Heap Memory
4724 **
4725 ** ^The sqlite3_release_memory() interface attempts to free N bytes
4726 ** of heap memory by deallocating non-essential memory allocations
4727 ** held by the database library.   Memory used to cache database
4728 ** pages to improve performance is an example of non-essential memory.
4729 ** ^sqlite3_release_memory() returns the number of bytes actually freed,
4730 ** which might be more or less than the amount requested.
4731 ** ^The sqlite3_release_memory() routine is a no-op returning zero
4732 ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
4733 */
4734 SQLITE_API int sqlite3_release_memory(int);
4735
4736 /*
4737 ** CAPI3REF: Impose A Limit On Heap Size
4738 **
4739 ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
4740 ** soft limit on the amount of heap memory that may be allocated by SQLite.
4741 ** ^SQLite strives to keep heap memory utilization below the soft heap
4742 ** limit by reducing the number of pages held in the page cache
4743 ** as heap memory usages approaches the limit.
4744 ** ^The soft heap limit is "soft" because even though SQLite strives to stay
4745 ** below the limit, it will exceed the limit rather than generate
4746 ** an [SQLITE_NOMEM] error.  In other words, the soft heap limit 
4747 ** is advisory only.
4748 **
4749 ** ^The return value from sqlite3_soft_heap_limit64() is the size of
4750 ** the soft heap limit prior to the call.  ^If the argument N is negative
4751 ** then no change is made to the soft heap limit.  Hence, the current
4752 ** size of the soft heap limit can be determined by invoking
4753 ** sqlite3_soft_heap_limit64() with a negative argument.
4754 **
4755 ** ^If the argument N is zero then the soft heap limit is disabled.
4756 **
4757 ** ^(The soft heap limit is not enforced in the current implementation
4758 ** if one or more of following conditions are true:
4759 **
4760 ** <ul>
4761 ** <li> The soft heap limit is set to zero.
4762 ** <li> Memory accounting is disabled using a combination of the
4763 **      [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
4764 **      the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
4765 ** <li> An alternative page cache implementation is specifed using
4766 **      [sqlite3_config]([SQLITE_CONFIG_PCACHE],...).
4767 ** <li> The page cache allocates from its own memory pool supplied
4768 **      by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
4769 **      from the heap.
4770 ** </ul>)^
4771 **
4772 ** Beginning with SQLite version 3.7.3, the soft heap limit is enforced
4773 ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
4774 ** compile-time option is invoked.  With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
4775 ** the soft heap limit is enforced on every memory allocation.  Without
4776 ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
4777 ** when memory is allocated by the page cache.  Testing suggests that because
4778 ** the page cache is the predominate memory user in SQLite, most
4779 ** applications will achieve adequate soft heap limit enforcement without
4780 ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
4781 **
4782 ** The circumstances under which SQLite will enforce the soft heap limit may
4783 ** changes in future releases of SQLite.
4784 */
4785 SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
4786
4787 /*
4788 ** CAPI3REF: Deprecated Soft Heap Limit Interface
4789 ** DEPRECATED
4790 **
4791 ** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
4792 ** interface.  This routine is provided for historical compatibility
4793 ** only.  All new applications should use the
4794 ** [sqlite3_soft_heap_limit64()] interface rather than this one.
4795 */
4796 SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
4797
4798
4799 /*
4800 ** CAPI3REF: Extract Metadata About A Column Of A Table
4801 **
4802 ** ^This routine returns metadata about a specific column of a specific
4803 ** database table accessible using the [database connection] handle
4804 ** passed as the first function argument.
4805 **
4806 ** ^The column is identified by the second, third and fourth parameters to
4807 ** this function. ^The second parameter is either the name of the database
4808 ** (i.e. "main", "temp", or an attached database) containing the specified
4809 ** table or NULL. ^If it is NULL, then all attached databases are searched
4810 ** for the table using the same algorithm used by the database engine to
4811 ** resolve unqualified table references.
4812 **
4813 ** ^The third and fourth parameters to this function are the table and column
4814 ** name of the desired column, respectively. Neither of these parameters
4815 ** may be NULL.
4816 **
4817 ** ^Metadata is returned by writing to the memory locations passed as the 5th
4818 ** and subsequent parameters to this function. ^Any of these arguments may be
4819 ** NULL, in which case the corresponding element of metadata is omitted.
4820 **
4821 ** ^(<blockquote>
4822 ** <table border="1">
4823 ** <tr><th> Parameter <th> Output<br>Type <th>  Description
4824 **
4825 ** <tr><td> 5th <td> const char* <td> Data type
4826 ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
4827 ** <tr><td> 7th <td> int         <td> True if column has a NOT NULL constraint
4828 ** <tr><td> 8th <td> int         <td> True if column is part of the PRIMARY KEY
4829 ** <tr><td> 9th <td> int         <td> True if column is [AUTOINCREMENT]
4830 ** </table>
4831 ** </blockquote>)^
4832 **
4833 ** ^The memory pointed to by the character pointers returned for the
4834 ** declaration type and collation sequence is valid only until the next
4835 ** call to any SQLite API function.
4836 **
4837 ** ^If the specified table is actually a view, an [error code] is returned.
4838 **
4839 ** ^If the specified column is "rowid", "oid" or "_rowid_" and an
4840 ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
4841 ** parameters are set for the explicitly declared column. ^(If there is no
4842 ** explicitly declared [INTEGER PRIMARY KEY] column, then the output
4843 ** parameters are set as follows:
4844 **
4845 ** <pre>
4846 **     data type: "INTEGER"
4847 **     collation sequence: "BINARY"
4848 **     not null: 0
4849 **     primary key: 1
4850 **     auto increment: 0
4851 ** </pre>)^
4852 **
4853 ** ^(This function may load one or more schemas from database files. If an
4854 ** error occurs during this process, or if the requested table or column
4855 ** cannot be found, an [error code] is returned and an error message left
4856 ** in the [database connection] (to be retrieved using sqlite3_errmsg()).)^
4857 **
4858 ** ^This API is only available if the library was compiled with the
4859 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
4860 */
4861 SQLITE_API int sqlite3_table_column_metadata(
4862   sqlite3 *db,                /* Connection handle */
4863   const char *zDbName,        /* Database name or NULL */
4864   const char *zTableName,     /* Table name */
4865   const char *zColumnName,    /* Column name */
4866   char const **pzDataType,    /* OUTPUT: Declared data type */
4867   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
4868   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
4869   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
4870   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
4871 );
4872
4873 /*
4874 ** CAPI3REF: Load An Extension
4875 **
4876 ** ^This interface loads an SQLite extension library from the named file.
4877 **
4878 ** ^The sqlite3_load_extension() interface attempts to load an
4879 ** SQLite extension library contained in the file zFile.
4880 **
4881 ** ^The entry point is zProc.
4882 ** ^zProc may be 0, in which case the name of the entry point
4883 ** defaults to "sqlite3_extension_init".
4884 ** ^The sqlite3_load_extension() interface returns
4885 ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
4886 ** ^If an error occurs and pzErrMsg is not 0, then the
4887 ** [sqlite3_load_extension()] interface shall attempt to
4888 ** fill *pzErrMsg with error message text stored in memory
4889 ** obtained from [sqlite3_malloc()]. The calling function
4890 ** should free this memory by calling [sqlite3_free()].
4891 **
4892 ** ^Extension loading must be enabled using
4893 ** [sqlite3_enable_load_extension()] prior to calling this API,
4894 ** otherwise an error will be returned.
4895 **
4896 ** See also the [load_extension() SQL function].
4897 */
4898 SQLITE_API int sqlite3_load_extension(
4899   sqlite3 *db,          /* Load the extension into this database connection */
4900   const char *zFile,    /* Name of the shared library containing extension */
4901   const char *zProc,    /* Entry point.  Derived from zFile if 0 */
4902   char **pzErrMsg       /* Put error message here if not 0 */
4903 );
4904
4905 /*
4906 ** CAPI3REF: Enable Or Disable Extension Loading
4907 **
4908 ** ^So as not to open security holes in older applications that are
4909 ** unprepared to deal with extension loading, and as a means of disabling
4910 ** extension loading while evaluating user-entered SQL, the following API
4911 ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
4912 **
4913 ** ^Extension loading is off by default. See ticket #1863.
4914 ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
4915 ** to turn extension loading on and call it with onoff==0 to turn
4916 ** it back off again.
4917 */
4918 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
4919
4920 /*
4921 ** CAPI3REF: Automatically Load Statically Linked Extensions
4922 **
4923 ** ^This interface causes the xEntryPoint() function to be invoked for
4924 ** each new [database connection] that is created.  The idea here is that
4925 ** xEntryPoint() is the entry point for a statically linked SQLite extension
4926 ** that is to be automatically loaded into all new database connections.
4927 **
4928 ** ^(Even though the function prototype shows that xEntryPoint() takes
4929 ** no arguments and returns void, SQLite invokes xEntryPoint() with three
4930 ** arguments and expects and integer result as if the signature of the
4931 ** entry point where as follows:
4932 **
4933 ** <blockquote><pre>
4934 ** &nbsp;  int xEntryPoint(
4935 ** &nbsp;    sqlite3 *db,
4936 ** &nbsp;    const char **pzErrMsg,
4937 ** &nbsp;    const struct sqlite3_api_routines *pThunk
4938 ** &nbsp;  );
4939 ** </pre></blockquote>)^
4940 **
4941 ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
4942 ** point to an appropriate error message (obtained from [sqlite3_mprintf()])
4943 ** and return an appropriate [error code].  ^SQLite ensures that *pzErrMsg
4944 ** is NULL before calling the xEntryPoint().  ^SQLite will invoke
4945 ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns.  ^If any
4946 ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
4947 ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
4948 **
4949 ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
4950 ** on the list of automatic extensions is a harmless no-op. ^No entry point
4951 ** will be called more than once for each database connection that is opened.
4952 **
4953 ** See also: [sqlite3_reset_auto_extension()].
4954 */
4955 SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void));
4956
4957 /*
4958 ** CAPI3REF: Reset Automatic Extension Loading
4959 **
4960 ** ^This interface disables all automatic extensions previously
4961 ** registered using [sqlite3_auto_extension()].
4962 */
4963 SQLITE_API void sqlite3_reset_auto_extension(void);
4964
4965 /*
4966 ** The interface to the virtual-table mechanism is currently considered
4967 ** to be experimental.  The interface might change in incompatible ways.
4968 ** If this is a problem for you, do not use the interface at this time.
4969 **
4970 ** When the virtual-table mechanism stabilizes, we will declare the
4971 ** interface fixed, support it indefinitely, and remove this comment.
4972 */
4973
4974 /*
4975 ** Structures used by the virtual table interface
4976 */
4977 typedef struct sqlite3_vtab sqlite3_vtab;
4978 typedef struct sqlite3_index_info sqlite3_index_info;
4979 typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
4980 typedef struct sqlite3_module sqlite3_module;
4981
4982 /*
4983 ** CAPI3REF: Virtual Table Object
4984 ** KEYWORDS: sqlite3_module {virtual table module}
4985 **
4986 ** This structure, sometimes called a a "virtual table module", 
4987 ** defines the implementation of a [virtual tables].  
4988 ** This structure consists mostly of methods for the module.
4989 **
4990 ** ^A virtual table module is created by filling in a persistent
4991 ** instance of this structure and passing a pointer to that instance
4992 ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
4993 ** ^The registration remains valid until it is replaced by a different
4994 ** module or until the [database connection] closes.  The content
4995 ** of this structure must not change while it is registered with
4996 ** any database connection.
4997 */
4998 struct sqlite3_module {
4999   int iVersion;
5000   int (*xCreate)(sqlite3*, void *pAux,
5001                int argc, const char *const*argv,
5002                sqlite3_vtab **ppVTab, char**);
5003   int (*xConnect)(sqlite3*, void *pAux,
5004                int argc, const char *const*argv,
5005                sqlite3_vtab **ppVTab, char**);
5006   int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
5007   int (*xDisconnect)(sqlite3_vtab *pVTab);
5008   int (*xDestroy)(sqlite3_vtab *pVTab);
5009   int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
5010   int (*xClose)(sqlite3_vtab_cursor*);
5011   int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
5012                 int argc, sqlite3_value **argv);
5013   int (*xNext)(sqlite3_vtab_cursor*);
5014   int (*xEof)(sqlite3_vtab_cursor*);
5015   int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
5016   int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
5017   int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
5018   int (*xBegin)(sqlite3_vtab *pVTab);
5019   int (*xSync)(sqlite3_vtab *pVTab);
5020   int (*xCommit)(sqlite3_vtab *pVTab);
5021   int (*xRollback)(sqlite3_vtab *pVTab);
5022   int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
5023                        void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
5024                        void **ppArg);
5025   int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
5026 };
5027
5028 /*
5029 ** CAPI3REF: Virtual Table Indexing Information
5030 ** KEYWORDS: sqlite3_index_info
5031 **
5032 ** The sqlite3_index_info structure and its substructures is used as part
5033 ** of the [virtual table] interface to
5034 ** pass information into and receive the reply from the [xBestIndex]
5035 ** method of a [virtual table module].  The fields under **Inputs** are the
5036 ** inputs to xBestIndex and are read-only.  xBestIndex inserts its
5037 ** results into the **Outputs** fields.
5038 **
5039 ** ^(The aConstraint[] array records WHERE clause constraints of the form:
5040 **
5041 ** <blockquote>column OP expr</blockquote>
5042 **
5043 ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^  ^(The particular operator is
5044 ** stored in aConstraint[].op using one of the
5045 ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
5046 ** ^(The index of the column is stored in
5047 ** aConstraint[].iColumn.)^  ^(aConstraint[].usable is TRUE if the
5048 ** expr on the right-hand side can be evaluated (and thus the constraint
5049 ** is usable) and false if it cannot.)^
5050 **
5051 ** ^The optimizer automatically inverts terms of the form "expr OP column"
5052 ** and makes other simplifications to the WHERE clause in an attempt to
5053 ** get as many WHERE clause terms into the form shown above as possible.
5054 ** ^The aConstraint[] array only reports WHERE clause terms that are
5055 ** relevant to the particular virtual table being queried.
5056 **
5057 ** ^Information about the ORDER BY clause is stored in aOrderBy[].
5058 ** ^Each term of aOrderBy records a column of the ORDER BY clause.
5059 **
5060 ** The [xBestIndex] method must fill aConstraintUsage[] with information
5061 ** about what parameters to pass to xFilter.  ^If argvIndex>0 then
5062 ** the right-hand side of the corresponding aConstraint[] is evaluated
5063 ** and becomes the argvIndex-th entry in argv.  ^(If aConstraintUsage[].omit
5064 ** is true, then the constraint is assumed to be fully handled by the
5065 ** virtual table and is not checked again by SQLite.)^
5066 **
5067 ** ^The idxNum and idxPtr values are recorded and passed into the
5068 ** [xFilter] method.
5069 ** ^[sqlite3_free()] is used to free idxPtr if and only if
5070 ** needToFreeIdxPtr is true.
5071 **
5072 ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
5073 ** the correct order to satisfy the ORDER BY clause so that no separate
5074 ** sorting step is required.
5075 **
5076 ** ^The estimatedCost value is an estimate of the cost of doing the
5077 ** particular lookup.  A full scan of a table with N entries should have
5078 ** a cost of N.  A binary search of a table of N entries should have a
5079 ** cost of approximately log(N).
5080 */
5081 struct sqlite3_index_info {
5082   /* Inputs */
5083   int nConstraint;           /* Number of entries in aConstraint */
5084   struct sqlite3_index_constraint {
5085      int iColumn;              /* Column on left-hand side of constraint */
5086      unsigned char op;         /* Constraint operator */
5087      unsigned char usable;     /* True if this constraint is usable */
5088      int iTermOffset;          /* Used internally - xBestIndex should ignore */
5089   } *aConstraint;            /* Table of WHERE clause constraints */
5090   int nOrderBy;              /* Number of terms in the ORDER BY clause */
5091   struct sqlite3_index_orderby {
5092      int iColumn;              /* Column number */
5093      unsigned char desc;       /* True for DESC.  False for ASC. */
5094   } *aOrderBy;               /* The ORDER BY clause */
5095   /* Outputs */
5096   struct sqlite3_index_constraint_usage {
5097     int argvIndex;           /* if >0, constraint is part of argv to xFilter */
5098     unsigned char omit;      /* Do not code a test for this constraint */
5099   } *aConstraintUsage;
5100   int idxNum;                /* Number used to identify the index */
5101   char *idxStr;              /* String, possibly obtained from sqlite3_malloc */
5102   int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */
5103   int orderByConsumed;       /* True if output is already ordered */
5104   double estimatedCost;      /* Estimated cost of using this index */
5105 };
5106
5107 /*
5108 ** CAPI3REF: Virtual Table Constraint Operator Codes
5109 **
5110 ** These macros defined the allowed values for the
5111 ** [sqlite3_index_info].aConstraint[].op field.  Each value represents
5112 ** an operator that is part of a constraint term in the wHERE clause of
5113 ** a query that uses a [virtual table].
5114 */
5115 #define SQLITE_INDEX_CONSTRAINT_EQ    2
5116 #define SQLITE_INDEX_CONSTRAINT_GT    4
5117 #define SQLITE_INDEX_CONSTRAINT_LE    8
5118 #define SQLITE_INDEX_CONSTRAINT_LT    16
5119 #define SQLITE_INDEX_CONSTRAINT_GE    32
5120 #define SQLITE_INDEX_CONSTRAINT_MATCH 64
5121
5122 /*
5123 ** CAPI3REF: Register A Virtual Table Implementation
5124 **
5125 ** ^These routines are used to register a new [virtual table module] name.
5126 ** ^Module names must be registered before
5127 ** creating a new [virtual table] using the module and before using a
5128 ** preexisting [virtual table] for the module.
5129 **
5130 ** ^The module name is registered on the [database connection] specified
5131 ** by the first parameter.  ^The name of the module is given by the 
5132 ** second parameter.  ^The third parameter is a pointer to
5133 ** the implementation of the [virtual table module].   ^The fourth
5134 ** parameter is an arbitrary client data pointer that is passed through
5135 ** into the [xCreate] and [xConnect] methods of the virtual table module
5136 ** when a new virtual table is be being created or reinitialized.
5137 **
5138 ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
5139 ** is a pointer to a destructor for the pClientData.  ^SQLite will
5140 ** invoke the destructor function (if it is not NULL) when SQLite
5141 ** no longer needs the pClientData pointer.  ^The sqlite3_create_module()
5142 ** interface is equivalent to sqlite3_create_module_v2() with a NULL
5143 ** destructor.
5144 */
5145 SQLITE_API int sqlite3_create_module(
5146   sqlite3 *db,               /* SQLite connection to register module with */
5147   const char *zName,         /* Name of the module */
5148   const sqlite3_module *p,   /* Methods for the module */
5149   void *pClientData          /* Client data for xCreate/xConnect */
5150 );
5151 SQLITE_API int sqlite3_create_module_v2(
5152   sqlite3 *db,               /* SQLite connection to register module with */
5153   const char *zName,         /* Name of the module */
5154   const sqlite3_module *p,   /* Methods for the module */
5155   void *pClientData,         /* Client data for xCreate/xConnect */
5156   void(*xDestroy)(void*)     /* Module destructor function */
5157 );
5158
5159 /*
5160 ** CAPI3REF: Virtual Table Instance Object
5161 ** KEYWORDS: sqlite3_vtab
5162 **
5163 ** Every [virtual table module] implementation uses a subclass
5164 ** of this object to describe a particular instance
5165 ** of the [virtual table].  Each subclass will
5166 ** be tailored to the specific needs of the module implementation.
5167 ** The purpose of this superclass is to define certain fields that are
5168 ** common to all module implementations.
5169 **
5170 ** ^Virtual tables methods can set an error message by assigning a
5171 ** string obtained from [sqlite3_mprintf()] to zErrMsg.  The method should
5172 ** take care that any prior string is freed by a call to [sqlite3_free()]
5173 ** prior to assigning a new string to zErrMsg.  ^After the error message
5174 ** is delivered up to the client application, the string will be automatically
5175 ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
5176 */
5177 struct sqlite3_vtab {
5178   const sqlite3_module *pModule;  /* The module for this virtual table */
5179   int nRef;                       /* NO LONGER USED */
5180   char *zErrMsg;                  /* Error message from sqlite3_mprintf() */
5181   /* Virtual table implementations will typically add additional fields */
5182 };
5183
5184 /*
5185 ** CAPI3REF: Virtual Table Cursor Object
5186 ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
5187 **
5188 ** Every [virtual table module] implementation uses a subclass of the
5189 ** following structure to describe cursors that point into the
5190 ** [virtual table] and are used
5191 ** to loop through the virtual table.  Cursors are created using the
5192 ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
5193 ** by the [sqlite3_module.xClose | xClose] method.  Cursors are used
5194 ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
5195 ** of the module.  Each module implementation will define
5196 ** the content of a cursor structure to suit its own needs.
5197 **
5198 ** This superclass exists in order to define fields of the cursor that
5199 ** are common to all implementations.
5200 */
5201 struct sqlite3_vtab_cursor {
5202   sqlite3_vtab *pVtab;      /* Virtual table of this cursor */
5203   /* Virtual table implementations will typically add additional fields */
5204 };
5205
5206 /*
5207 ** CAPI3REF: Declare The Schema Of A Virtual Table
5208 **
5209 ** ^The [xCreate] and [xConnect] methods of a
5210 ** [virtual table module] call this interface
5211 ** to declare the format (the names and datatypes of the columns) of
5212 ** the virtual tables they implement.
5213 */
5214 SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
5215
5216 /*
5217 ** CAPI3REF: Overload A Function For A Virtual Table
5218 **
5219 ** ^(Virtual tables can provide alternative implementations of functions
5220 ** using the [xFindFunction] method of the [virtual table module].  
5221 ** But global versions of those functions
5222 ** must exist in order to be overloaded.)^
5223 **
5224 ** ^(This API makes sure a global version of a function with a particular
5225 ** name and number of parameters exists.  If no such function exists
5226 ** before this API is called, a new function is created.)^  ^The implementation
5227 ** of the new function always causes an exception to be thrown.  So
5228 ** the new function is not good for anything by itself.  Its only
5229 ** purpose is to be a placeholder function that can be overloaded
5230 ** by a [virtual table].
5231 */
5232 SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
5233
5234 /*
5235 ** The interface to the virtual-table mechanism defined above (back up
5236 ** to a comment remarkably similar to this one) is currently considered
5237 ** to be experimental.  The interface might change in incompatible ways.
5238 ** If this is a problem for you, do not use the interface at this time.
5239 **
5240 ** When the virtual-table mechanism stabilizes, we will declare the
5241 ** interface fixed, support it indefinitely, and remove this comment.
5242 */
5243
5244 /*
5245 ** CAPI3REF: A Handle To An Open BLOB
5246 ** KEYWORDS: {BLOB handle} {BLOB handles}
5247 **
5248 ** An instance of this object represents an open BLOB on which
5249 ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
5250 ** ^Objects of this type are created by [sqlite3_blob_open()]
5251 ** and destroyed by [sqlite3_blob_close()].
5252 ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
5253 ** can be used to read or write small subsections of the BLOB.
5254 ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
5255 */
5256 typedef struct sqlite3_blob sqlite3_blob;
5257
5258 /*
5259 ** CAPI3REF: Open A BLOB For Incremental I/O
5260 **
5261 ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
5262 ** in row iRow, column zColumn, table zTable in database zDb;
5263 ** in other words, the same BLOB that would be selected by:
5264 **
5265 ** <pre>
5266 **     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
5267 ** </pre>)^
5268 **
5269 ** ^If the flags parameter is non-zero, then the BLOB is opened for read
5270 ** and write access. ^If it is zero, the BLOB is opened for read access.
5271 ** ^It is not possible to open a column that is part of an index or primary 
5272 ** key for writing. ^If [foreign key constraints] are enabled, it is 
5273 ** not possible to open a column that is part of a [child key] for writing.
5274 **
5275 ** ^Note that the database name is not the filename that contains
5276 ** the database but rather the symbolic name of the database that
5277 ** appears after the AS keyword when the database is connected using [ATTACH].
5278 ** ^For the main database file, the database name is "main".
5279 ** ^For TEMP tables, the database name is "temp".
5280 **
5281 ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is written
5282 ** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set
5283 ** to be a null pointer.)^
5284 ** ^This function sets the [database connection] error code and message
5285 ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related
5286 ** functions. ^Note that the *ppBlob variable is always initialized in a
5287 ** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob
5288 ** regardless of the success or failure of this routine.
5289 **
5290 ** ^(If the row that a BLOB handle points to is modified by an
5291 ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
5292 ** then the BLOB handle is marked as "expired".
5293 ** This is true if any column of the row is changed, even a column
5294 ** other than the one the BLOB handle is open on.)^
5295 ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
5296 ** a expired BLOB handle fail with an return code of [SQLITE_ABORT].
5297 ** ^(Changes written into a BLOB prior to the BLOB expiring are not
5298 ** rolled back by the expiration of the BLOB.  Such changes will eventually
5299 ** commit if the transaction continues to completion.)^
5300 **
5301 ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
5302 ** the opened blob.  ^The size of a blob may not be changed by this
5303 ** interface.  Use the [UPDATE] SQL command to change the size of a
5304 ** blob.
5305 **
5306 ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
5307 ** and the built-in [zeroblob] SQL function can be used, if desired,
5308 ** to create an empty, zero-filled blob in which to read or write using
5309 ** this interface.
5310 **
5311 ** To avoid a resource leak, every open [BLOB handle] should eventually
5312 ** be released by a call to [sqlite3_blob_close()].
5313 */
5314 SQLITE_API int sqlite3_blob_open(
5315   sqlite3*,
5316   const char *zDb,
5317   const char *zTable,
5318   const char *zColumn,
5319   sqlite3_int64 iRow,
5320   int flags,
5321   sqlite3_blob **ppBlob
5322 );
5323
5324 /*
5325 ** CAPI3REF: Close A BLOB Handle
5326 **
5327 ** ^Closes an open [BLOB handle].
5328 **
5329 ** ^Closing a BLOB shall cause the current transaction to commit
5330 ** if there are no other BLOBs, no pending prepared statements, and the
5331 ** database connection is in [autocommit mode].
5332 ** ^If any writes were made to the BLOB, they might be held in cache
5333 ** until the close operation if they will fit.
5334 **
5335 ** ^(Closing the BLOB often forces the changes
5336 ** out to disk and so if any I/O errors occur, they will likely occur
5337 ** at the time when the BLOB is closed.  Any errors that occur during
5338 ** closing are reported as a non-zero return value.)^
5339 **
5340 ** ^(The BLOB is closed unconditionally.  Even if this routine returns
5341 ** an error code, the BLOB is still closed.)^
5342 **
5343 ** ^Calling this routine with a null pointer (such as would be returned
5344 ** by a failed call to [sqlite3_blob_open()]) is a harmless no-op.
5345 */
5346 SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
5347
5348 /*
5349 ** CAPI3REF: Return The Size Of An Open BLOB
5350 **
5351 ** ^Returns the size in bytes of the BLOB accessible via the 
5352 ** successfully opened [BLOB handle] in its only argument.  ^The
5353 ** incremental blob I/O routines can only read or overwriting existing
5354 ** blob content; they cannot change the size of a blob.
5355 **
5356 ** This routine only works on a [BLOB handle] which has been created
5357 ** by a prior successful call to [sqlite3_blob_open()] and which has not
5358 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5359 ** to this routine results in undefined and probably undesirable behavior.
5360 */
5361 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
5362
5363 /*
5364 ** CAPI3REF: Read Data From A BLOB Incrementally
5365 **
5366 ** ^(This function is used to read data from an open [BLOB handle] into a
5367 ** caller-supplied buffer. N bytes of data are copied into buffer Z
5368 ** from the open BLOB, starting at offset iOffset.)^
5369 **
5370 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
5371 ** [SQLITE_ERROR] is returned and no data is read.  ^If N or iOffset is
5372 ** less than zero, [SQLITE_ERROR] is returned and no data is read.
5373 ** ^The size of the blob (and hence the maximum value of N+iOffset)
5374 ** can be determined using the [sqlite3_blob_bytes()] interface.
5375 **
5376 ** ^An attempt to read from an expired [BLOB handle] fails with an
5377 ** error code of [SQLITE_ABORT].
5378 **
5379 ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
5380 ** Otherwise, an [error code] or an [extended error code] is returned.)^
5381 **
5382 ** This routine only works on a [BLOB handle] which has been created
5383 ** by a prior successful call to [sqlite3_blob_open()] and which has not
5384 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5385 ** to this routine results in undefined and probably undesirable behavior.
5386 **
5387 ** See also: [sqlite3_blob_write()].
5388 */
5389 SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
5390
5391 /*
5392 ** CAPI3REF: Write Data Into A BLOB Incrementally
5393 **
5394 ** ^This function is used to write data into an open [BLOB handle] from a
5395 ** caller-supplied buffer. ^N bytes of data are copied from the buffer Z
5396 ** into the open BLOB, starting at offset iOffset.
5397 **
5398 ** ^If the [BLOB handle] passed as the first argument was not opened for
5399 ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
5400 ** this function returns [SQLITE_READONLY].
5401 **
5402 ** ^This function may only modify the contents of the BLOB; it is
5403 ** not possible to increase the size of a BLOB using this API.
5404 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
5405 ** [SQLITE_ERROR] is returned and no data is written.  ^If N is
5406 ** less than zero [SQLITE_ERROR] is returned and no data is written.
5407 ** The size of the BLOB (and hence the maximum value of N+iOffset)
5408 ** can be determined using the [sqlite3_blob_bytes()] interface.
5409 **
5410 ** ^An attempt to write to an expired [BLOB handle] fails with an
5411 ** error code of [SQLITE_ABORT].  ^Writes to the BLOB that occurred
5412 ** before the [BLOB handle] expired are not rolled back by the
5413 ** expiration of the handle, though of course those changes might
5414 ** have been overwritten by the statement that expired the BLOB handle
5415 ** or by other independent statements.
5416 **
5417 ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
5418 ** Otherwise, an  [error code] or an [extended error code] is returned.)^
5419 **
5420 ** This routine only works on a [BLOB handle] which has been created
5421 ** by a prior successful call to [sqlite3_blob_open()] and which has not
5422 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5423 ** to this routine results in undefined and probably undesirable behavior.
5424 **
5425 ** See also: [sqlite3_blob_read()].
5426 */
5427 SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
5428
5429 /*
5430 ** CAPI3REF: Virtual File System Objects
5431 **
5432 ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
5433 ** that SQLite uses to interact
5434 ** with the underlying operating system.  Most SQLite builds come with a
5435 ** single default VFS that is appropriate for the host computer.
5436 ** New VFSes can be registered and existing VFSes can be unregistered.
5437 ** The following interfaces are provided.
5438 **
5439 ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
5440 ** ^Names are case sensitive.
5441 ** ^Names are zero-terminated UTF-8 strings.
5442 ** ^If there is no match, a NULL pointer is returned.
5443 ** ^If zVfsName is NULL then the default VFS is returned.
5444 **
5445 ** ^New VFSes are registered with sqlite3_vfs_register().
5446 ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
5447 ** ^The same VFS can be registered multiple times without injury.
5448 ** ^To make an existing VFS into the default VFS, register it again
5449 ** with the makeDflt flag set.  If two different VFSes with the
5450 ** same name are registered, the behavior is undefined.  If a
5451 ** VFS is registered with a name that is NULL or an empty string,
5452 ** then the behavior is undefined.
5453 **
5454 ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
5455 ** ^(If the default VFS is unregistered, another VFS is chosen as
5456 ** the default.  The choice for the new VFS is arbitrary.)^
5457 */
5458 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
5459 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
5460 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
5461
5462 /*
5463 ** CAPI3REF: Mutexes
5464 **
5465 ** The SQLite core uses these routines for thread
5466 ** synchronization. Though they are intended for internal
5467 ** use by SQLite, code that links against SQLite is
5468 ** permitted to use any of these routines.
5469 **
5470 ** The SQLite source code contains multiple implementations
5471 ** of these mutex routines.  An appropriate implementation
5472 ** is selected automatically at compile-time.  ^(The following
5473 ** implementations are available in the SQLite core:
5474 **
5475 ** <ul>
5476 ** <li>   SQLITE_MUTEX_OS2
5477 ** <li>   SQLITE_MUTEX_PTHREAD
5478 ** <li>   SQLITE_MUTEX_W32
5479 ** <li>   SQLITE_MUTEX_NOOP
5480 ** </ul>)^
5481 **
5482 ** ^The SQLITE_MUTEX_NOOP implementation is a set of routines
5483 ** that does no real locking and is appropriate for use in
5484 ** a single-threaded application.  ^The SQLITE_MUTEX_OS2,
5485 ** SQLITE_MUTEX_PTHREAD, and SQLITE_MUTEX_W32 implementations
5486 ** are appropriate for use on OS/2, Unix, and Windows.
5487 **
5488 ** ^(If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
5489 ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
5490 ** implementation is included with the library. In this case the
5491 ** application must supply a custom mutex implementation using the
5492 ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
5493 ** before calling sqlite3_initialize() or any other public sqlite3_
5494 ** function that calls sqlite3_initialize().)^
5495 **
5496 ** ^The sqlite3_mutex_alloc() routine allocates a new
5497 ** mutex and returns a pointer to it. ^If it returns NULL
5498 ** that means that a mutex could not be allocated.  ^SQLite
5499 ** will unwind its stack and return an error.  ^(The argument
5500 ** to sqlite3_mutex_alloc() is one of these integer constants:
5501 **
5502 ** <ul>
5503 ** <li>  SQLITE_MUTEX_FAST
5504 ** <li>  SQLITE_MUTEX_RECURSIVE
5505 ** <li>  SQLITE_MUTEX_STATIC_MASTER
5506 ** <li>  SQLITE_MUTEX_STATIC_MEM
5507 ** <li>  SQLITE_MUTEX_STATIC_MEM2
5508 ** <li>  SQLITE_MUTEX_STATIC_PRNG
5509 ** <li>  SQLITE_MUTEX_STATIC_LRU
5510 ** <li>  SQLITE_MUTEX_STATIC_LRU2
5511 ** </ul>)^
5512 **
5513 ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
5514 ** cause sqlite3_mutex_alloc() to create
5515 ** a new mutex.  ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
5516 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
5517 ** The mutex implementation does not need to make a distinction
5518 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
5519 ** not want to.  ^SQLite will only request a recursive mutex in
5520 ** cases where it really needs one.  ^If a faster non-recursive mutex
5521 ** implementation is available on the host platform, the mutex subsystem
5522 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
5523 **
5524 ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
5525 ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
5526 ** a pointer to a static preexisting mutex.  ^Six static mutexes are
5527 ** used by the current version of SQLite.  Future versions of SQLite
5528 ** may add additional static mutexes.  Static mutexes are for internal
5529 ** use by SQLite only.  Applications that use SQLite mutexes should
5530 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
5531 ** SQLITE_MUTEX_RECURSIVE.
5532 **
5533 ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
5534 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
5535 ** returns a different mutex on every call.  ^But for the static
5536 ** mutex types, the same mutex is returned on every call that has
5537 ** the same type number.
5538 **
5539 ** ^The sqlite3_mutex_free() routine deallocates a previously
5540 ** allocated dynamic mutex.  ^SQLite is careful to deallocate every
5541 ** dynamic mutex that it allocates.  The dynamic mutexes must not be in
5542 ** use when they are deallocated.  Attempting to deallocate a static
5543 ** mutex results in undefined behavior.  ^SQLite never deallocates
5544 ** a static mutex.
5545 **
5546 ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
5547 ** to enter a mutex.  ^If another thread is already within the mutex,
5548 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
5549 ** SQLITE_BUSY.  ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
5550 ** upon successful entry.  ^(Mutexes created using
5551 ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
5552 ** In such cases the,
5553 ** mutex must be exited an equal number of times before another thread
5554 ** can enter.)^  ^(If the same thread tries to enter any other
5555 ** kind of mutex more than once, the behavior is undefined.
5556 ** SQLite will never exhibit
5557 ** such behavior in its own use of mutexes.)^
5558 **
5559 ** ^(Some systems (for example, Windows 95) do not support the operation
5560 ** implemented by sqlite3_mutex_try().  On those systems, sqlite3_mutex_try()
5561 ** will always return SQLITE_BUSY.  The SQLite core only ever uses
5562 ** sqlite3_mutex_try() as an optimization so this is acceptable behavior.)^
5563 **
5564 ** ^The sqlite3_mutex_leave() routine exits a mutex that was
5565 ** previously entered by the same thread.   ^(The behavior
5566 ** is undefined if the mutex is not currently entered by the
5567 ** calling thread or is not currently allocated.  SQLite will
5568 ** never do either.)^
5569 **
5570 ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
5571 ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
5572 ** behave as no-ops.
5573 **
5574 ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
5575 */
5576 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
5577 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
5578 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
5579 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
5580 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
5581
5582 /*
5583 ** CAPI3REF: Mutex Methods Object
5584 **
5585 ** An instance of this structure defines the low-level routines
5586 ** used to allocate and use mutexes.
5587 **
5588 ** Usually, the default mutex implementations provided by SQLite are
5589 ** sufficient, however the user has the option of substituting a custom
5590 ** implementation for specialized deployments or systems for which SQLite
5591 ** does not provide a suitable implementation. In this case, the user
5592 ** creates and populates an instance of this structure to pass
5593 ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
5594 ** Additionally, an instance of this structure can be used as an
5595 ** output variable when querying the system for the current mutex
5596 ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
5597 **
5598 ** ^The xMutexInit method defined by this structure is invoked as
5599 ** part of system initialization by the sqlite3_initialize() function.
5600 ** ^The xMutexInit routine is called by SQLite exactly once for each
5601 ** effective call to [sqlite3_initialize()].
5602 **
5603 ** ^The xMutexEnd method defined by this structure is invoked as
5604 ** part of system shutdown by the sqlite3_shutdown() function. The
5605 ** implementation of this method is expected to release all outstanding
5606 ** resources obtained by the mutex methods implementation, especially
5607 ** those obtained by the xMutexInit method.  ^The xMutexEnd()
5608 ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
5609 **
5610 ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
5611 ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
5612 ** xMutexNotheld) implement the following interfaces (respectively):
5613 **
5614 ** <ul>
5615 **   <li>  [sqlite3_mutex_alloc()] </li>
5616 **   <li>  [sqlite3_mutex_free()] </li>
5617 **   <li>  [sqlite3_mutex_enter()] </li>
5618 **   <li>  [sqlite3_mutex_try()] </li>
5619 **   <li>  [sqlite3_mutex_leave()] </li>
5620 **   <li>  [sqlite3_mutex_held()] </li>
5621 **   <li>  [sqlite3_mutex_notheld()] </li>
5622 ** </ul>)^
5623 **
5624 ** The only difference is that the public sqlite3_XXX functions enumerated
5625 ** above silently ignore any invocations that pass a NULL pointer instead
5626 ** of a valid mutex handle. The implementations of the methods defined
5627 ** by this structure are not required to handle this case, the results
5628 ** of passing a NULL pointer instead of a valid mutex handle are undefined
5629 ** (i.e. it is acceptable to provide an implementation that segfaults if
5630 ** it is passed a NULL pointer).
5631 **
5632 ** The xMutexInit() method must be threadsafe.  ^It must be harmless to
5633 ** invoke xMutexInit() multiple times within the same process and without
5634 ** intervening calls to xMutexEnd().  Second and subsequent calls to
5635 ** xMutexInit() must be no-ops.
5636 **
5637 ** ^xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
5638 ** and its associates).  ^Similarly, xMutexAlloc() must not use SQLite memory
5639 ** allocation for a static mutex.  ^However xMutexAlloc() may use SQLite
5640 ** memory allocation for a fast or recursive mutex.
5641 **
5642 ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
5643 ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
5644 ** If xMutexInit fails in any way, it is expected to clean up after itself
5645 ** prior to returning.
5646 */
5647 typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
5648 struct sqlite3_mutex_methods {
5649   int (*xMutexInit)(void);
5650   int (*xMutexEnd)(void);
5651   sqlite3_mutex *(*xMutexAlloc)(int);
5652   void (*xMutexFree)(sqlite3_mutex *);
5653   void (*xMutexEnter)(sqlite3_mutex *);
5654   int (*xMutexTry)(sqlite3_mutex *);
5655   void (*xMutexLeave)(sqlite3_mutex *);
5656   int (*xMutexHeld)(sqlite3_mutex *);
5657   int (*xMutexNotheld)(sqlite3_mutex *);
5658 };
5659
5660 /*
5661 ** CAPI3REF: Mutex Verification Routines
5662 **
5663 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
5664 ** are intended for use inside assert() statements.  ^The SQLite core
5665 ** never uses these routines except inside an assert() and applications
5666 ** are advised to follow the lead of the core.  ^The SQLite core only
5667 ** provides implementations for these routines when it is compiled
5668 ** with the SQLITE_DEBUG flag.  ^External mutex implementations
5669 ** are only required to provide these routines if SQLITE_DEBUG is
5670 ** defined and if NDEBUG is not defined.
5671 **
5672 ** ^These routines should return true if the mutex in their argument
5673 ** is held or not held, respectively, by the calling thread.
5674 **
5675 ** ^The implementation is not required to provided versions of these
5676 ** routines that actually work. If the implementation does not provide working
5677 ** versions of these routines, it should at least provide stubs that always
5678 ** return true so that one does not get spurious assertion failures.
5679 **
5680 ** ^If the argument to sqlite3_mutex_held() is a NULL pointer then
5681 ** the routine should return 1.   This seems counter-intuitive since
5682 ** clearly the mutex cannot be held if it does not exist.  But the
5683 ** the reason the mutex does not exist is because the build is not
5684 ** using mutexes.  And we do not want the assert() containing the
5685 ** call to sqlite3_mutex_held() to fail, so a non-zero return is
5686 ** the appropriate thing to do.  ^The sqlite3_mutex_notheld()
5687 ** interface should also return 1 when given a NULL pointer.
5688 */
5689 #ifndef NDEBUG
5690 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
5691 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
5692 #endif
5693
5694 /*
5695 ** CAPI3REF: Mutex Types
5696 **
5697 ** The [sqlite3_mutex_alloc()] interface takes a single argument
5698 ** which is one of these integer constants.
5699 **
5700 ** The set of static mutexes may change from one SQLite release to the
5701 ** next.  Applications that override the built-in mutex logic must be
5702 ** prepared to accommodate additional static mutexes.
5703 */
5704 #define SQLITE_MUTEX_FAST             0
5705 #define SQLITE_MUTEX_RECURSIVE        1
5706 #define SQLITE_MUTEX_STATIC_MASTER    2
5707 #define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
5708 #define SQLITE_MUTEX_STATIC_MEM2      4  /* NOT USED */
5709 #define SQLITE_MUTEX_STATIC_OPEN      4  /* sqlite3BtreeOpen() */
5710 #define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_random() */
5711 #define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */
5712 #define SQLITE_MUTEX_STATIC_LRU2      7  /* lru page list */
5713
5714 /*
5715 ** CAPI3REF: Retrieve the mutex for a database connection
5716 **
5717 ** ^This interface returns a pointer the [sqlite3_mutex] object that 
5718 ** serializes access to the [database connection] given in the argument
5719 ** when the [threading mode] is Serialized.
5720 ** ^If the [threading mode] is Single-thread or Multi-thread then this
5721 ** routine returns a NULL pointer.
5722 */
5723 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
5724
5725 /*
5726 ** CAPI3REF: Low-Level Control Of Database Files
5727 **
5728 ** ^The [sqlite3_file_control()] interface makes a direct call to the
5729 ** xFileControl method for the [sqlite3_io_methods] object associated
5730 ** with a particular database identified by the second argument. ^The
5731 ** name of the database "main" for the main database or "temp" for the
5732 ** TEMP database, or the name that appears after the AS keyword for
5733 ** databases that are added using the [ATTACH] SQL command.
5734 ** ^A NULL pointer can be used in place of "main" to refer to the
5735 ** main database file.
5736 ** ^The third and fourth parameters to this routine
5737 ** are passed directly through to the second and third parameters of
5738 ** the xFileControl method.  ^The return value of the xFileControl
5739 ** method becomes the return value of this routine.
5740 **
5741 ** ^If the second parameter (zDbName) does not match the name of any
5742 ** open database file, then SQLITE_ERROR is returned.  ^This error
5743 ** code is not remembered and will not be recalled by [sqlite3_errcode()]
5744 ** or [sqlite3_errmsg()].  The underlying xFileControl method might
5745 ** also return SQLITE_ERROR.  There is no way to distinguish between
5746 ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
5747 ** xFileControl method.
5748 **
5749 ** See also: [SQLITE_FCNTL_LOCKSTATE]
5750 */
5751 SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
5752
5753 /*
5754 ** CAPI3REF: Testing Interface
5755 **
5756 ** ^The sqlite3_test_control() interface is used to read out internal
5757 ** state of SQLite and to inject faults into SQLite for testing
5758 ** purposes.  ^The first parameter is an operation code that determines
5759 ** the number, meaning, and operation of all subsequent parameters.
5760 **
5761 ** This interface is not for use by applications.  It exists solely
5762 ** for verifying the correct operation of the SQLite library.  Depending
5763 ** on how the SQLite library is compiled, this interface might not exist.
5764 **
5765 ** The details of the operation codes, their meanings, the parameters
5766 ** they take, and what they do are all subject to change without notice.
5767 ** Unlike most of the SQLite API, this function is not guaranteed to
5768 ** operate consistently from one release to the next.
5769 */
5770 SQLITE_API int sqlite3_test_control(int op, ...);
5771
5772 /*
5773 ** CAPI3REF: Testing Interface Operation Codes
5774 **
5775 ** These constants are the valid operation code parameters used
5776 ** as the first argument to [sqlite3_test_control()].
5777 **
5778 ** These parameters and their meanings are subject to change
5779 ** without notice.  These values are for testing purposes only.
5780 ** Applications should not use any of these parameters or the
5781 ** [sqlite3_test_control()] interface.
5782 */
5783 #define SQLITE_TESTCTRL_FIRST                    5
5784 #define SQLITE_TESTCTRL_PRNG_SAVE                5
5785 #define SQLITE_TESTCTRL_PRNG_RESTORE             6
5786 #define SQLITE_TESTCTRL_PRNG_RESET               7
5787 #define SQLITE_TESTCTRL_BITVEC_TEST              8
5788 #define SQLITE_TESTCTRL_FAULT_INSTALL            9
5789 #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS     10
5790 #define SQLITE_TESTCTRL_PENDING_BYTE            11
5791 #define SQLITE_TESTCTRL_ASSERT                  12
5792 #define SQLITE_TESTCTRL_ALWAYS                  13
5793 #define SQLITE_TESTCTRL_RESERVE                 14
5794 #define SQLITE_TESTCTRL_OPTIMIZATIONS           15
5795 #define SQLITE_TESTCTRL_ISKEYWORD               16
5796 #define SQLITE_TESTCTRL_PGHDRSZ                 17
5797 #define SQLITE_TESTCTRL_SCRATCHMALLOC           18
5798 #define SQLITE_TESTCTRL_LAST                    18
5799
5800 /*
5801 ** CAPI3REF: SQLite Runtime Status
5802 **
5803 ** ^This interface is used to retrieve runtime status information
5804 ** about the performance of SQLite, and optionally to reset various
5805 ** highwater marks.  ^The first argument is an integer code for
5806 ** the specific parameter to measure.  ^(Recognized integer codes
5807 ** are of the form [SQLITE_STATUS_MEMORY_USED | SQLITE_STATUS_...].)^
5808 ** ^The current value of the parameter is returned into *pCurrent.
5809 ** ^The highest recorded value is returned in *pHighwater.  ^If the
5810 ** resetFlag is true, then the highest record value is reset after
5811 ** *pHighwater is written.  ^(Some parameters do not record the highest
5812 ** value.  For those parameters
5813 ** nothing is written into *pHighwater and the resetFlag is ignored.)^
5814 ** ^(Other parameters record only the highwater mark and not the current
5815 ** value.  For these latter parameters nothing is written into *pCurrent.)^
5816 **
5817 ** ^The sqlite3_status() routine returns SQLITE_OK on success and a
5818 ** non-zero [error code] on failure.
5819 **
5820 ** This routine is threadsafe but is not atomic.  This routine can be
5821 ** called while other threads are running the same or different SQLite
5822 ** interfaces.  However the values returned in *pCurrent and
5823 ** *pHighwater reflect the status of SQLite at different points in time
5824 ** and it is possible that another thread might change the parameter
5825 ** in between the times when *pCurrent and *pHighwater are written.
5826 **
5827 ** See also: [sqlite3_db_status()]
5828 */
5829 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
5830
5831
5832 /*
5833 ** CAPI3REF: Status Parameters
5834 **
5835 ** These integer constants designate various run-time status parameters
5836 ** that can be returned by [sqlite3_status()].
5837 **
5838 ** <dl>
5839 ** ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
5840 ** <dd>This parameter is the current amount of memory checked out
5841 ** using [sqlite3_malloc()], either directly or indirectly.  The
5842 ** figure includes calls made to [sqlite3_malloc()] by the application
5843 ** and internal memory usage by the SQLite library.  Scratch memory
5844 ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
5845 ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
5846 ** this parameter.  The amount returned is the sum of the allocation
5847 ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
5848 **
5849 ** ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
5850 ** <dd>This parameter records the largest memory allocation request
5851 ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
5852 ** internal equivalents).  Only the value returned in the
5853 ** *pHighwater parameter to [sqlite3_status()] is of interest.  
5854 ** The value written into the *pCurrent parameter is undefined.</dd>)^
5855 **
5856 ** ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
5857 ** <dd>This parameter records the number of separate memory allocations.</dd>)^
5858 **
5859 ** ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
5860 ** <dd>This parameter returns the number of pages used out of the
5861 ** [pagecache memory allocator] that was configured using 
5862 ** [SQLITE_CONFIG_PAGECACHE].  The
5863 ** value returned is in pages, not in bytes.</dd>)^
5864 **
5865 ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
5866 ** <dd>This parameter returns the number of bytes of page cache
5867 ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
5868 ** buffer and where forced to overflow to [sqlite3_malloc()].  The
5869 ** returned value includes allocations that overflowed because they
5870 ** where too large (they were larger than the "sz" parameter to
5871 ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
5872 ** no space was left in the page cache.</dd>)^
5873 **
5874 ** ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
5875 ** <dd>This parameter records the largest memory allocation request
5876 ** handed to [pagecache memory allocator].  Only the value returned in the
5877 ** *pHighwater parameter to [sqlite3_status()] is of interest.  
5878 ** The value written into the *pCurrent parameter is undefined.</dd>)^
5879 **
5880 ** ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
5881 ** <dd>This parameter returns the number of allocations used out of the
5882 ** [scratch memory allocator] configured using
5883 ** [SQLITE_CONFIG_SCRATCH].  The value returned is in allocations, not
5884 ** in bytes.  Since a single thread may only have one scratch allocation
5885 ** outstanding at time, this parameter also reports the number of threads
5886 ** using scratch memory at the same time.</dd>)^
5887 **
5888 ** ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
5889 ** <dd>This parameter returns the number of bytes of scratch memory
5890 ** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]
5891 ** buffer and where forced to overflow to [sqlite3_malloc()].  The values
5892 ** returned include overflows because the requested allocation was too
5893 ** larger (that is, because the requested allocation was larger than the
5894 ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
5895 ** slots were available.
5896 ** </dd>)^
5897 **
5898 ** ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
5899 ** <dd>This parameter records the largest memory allocation request
5900 ** handed to [scratch memory allocator].  Only the value returned in the
5901 ** *pHighwater parameter to [sqlite3_status()] is of interest.  
5902 ** The value written into the *pCurrent parameter is undefined.</dd>)^
5903 **
5904 ** ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
5905 ** <dd>This parameter records the deepest parser stack.  It is only
5906 ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
5907 ** </dl>
5908 **
5909 ** New status parameters may be added from time to time.
5910 */
5911 #define SQLITE_STATUS_MEMORY_USED          0
5912 #define SQLITE_STATUS_PAGECACHE_USED       1
5913 #define SQLITE_STATUS_PAGECACHE_OVERFLOW   2
5914 #define SQLITE_STATUS_SCRATCH_USED         3
5915 #define SQLITE_STATUS_SCRATCH_OVERFLOW     4
5916 #define SQLITE_STATUS_MALLOC_SIZE          5
5917 #define SQLITE_STATUS_PARSER_STACK         6
5918 #define SQLITE_STATUS_PAGECACHE_SIZE       7
5919 #define SQLITE_STATUS_SCRATCH_SIZE         8
5920 #define SQLITE_STATUS_MALLOC_COUNT         9
5921
5922 /*
5923 ** CAPI3REF: Database Connection Status
5924 **
5925 ** ^This interface is used to retrieve runtime status information 
5926 ** about a single [database connection].  ^The first argument is the
5927 ** database connection object to be interrogated.  ^The second argument
5928 ** is an integer constant, taken from the set of
5929 ** [SQLITE_DBSTATUS_LOOKASIDE_USED | SQLITE_DBSTATUS_*] macros, that
5930 ** determines the parameter to interrogate.  The set of 
5931 ** [SQLITE_DBSTATUS_LOOKASIDE_USED | SQLITE_DBSTATUS_*] macros is likely
5932 ** to grow in future releases of SQLite.
5933 **
5934 ** ^The current value of the requested parameter is written into *pCur
5935 ** and the highest instantaneous value is written into *pHiwtr.  ^If
5936 ** the resetFlg is true, then the highest instantaneous value is
5937 ** reset back down to the current value.
5938 **
5939 ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
5940 ** non-zero [error code] on failure.
5941 **
5942 ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
5943 */
5944 SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
5945
5946 /*
5947 ** CAPI3REF: Status Parameters for database connections
5948 **
5949 ** These constants are the available integer "verbs" that can be passed as
5950 ** the second argument to the [sqlite3_db_status()] interface.
5951 **
5952 ** New verbs may be added in future releases of SQLite. Existing verbs
5953 ** might be discontinued. Applications should check the return code from
5954 ** [sqlite3_db_status()] to make sure that the call worked.
5955 ** The [sqlite3_db_status()] interface will return a non-zero error code
5956 ** if a discontinued or unsupported verb is invoked.
5957 **
5958 ** <dl>
5959 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
5960 ** <dd>This parameter returns the number of lookaside memory slots currently
5961 ** checked out.</dd>)^
5962 **
5963 ** ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
5964 ** <dd>This parameter returns the approximate number of of bytes of heap
5965 ** memory used by all pager caches associated with the database connection.)^
5966 ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
5967 **
5968 ** ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
5969 ** <dd>This parameter returns the approximate number of of bytes of heap
5970 ** memory used to store the schema for all databases associated
5971 ** with the connection - main, temp, and any [ATTACH]-ed databases.)^ 
5972 ** ^The full amount of memory used by the schemas is reported, even if the
5973 ** schema memory is shared with other database connections due to
5974 ** [shared cache mode] being enabled.
5975 ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
5976 **
5977 ** ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
5978 ** <dd>This parameter returns the approximate number of of bytes of heap
5979 ** and lookaside memory used by all prepared statements associated with
5980 ** the database connection.)^
5981 ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
5982 ** </dd>
5983 ** </dl>
5984 */
5985 #define SQLITE_DBSTATUS_LOOKASIDE_USED     0
5986 #define SQLITE_DBSTATUS_CACHE_USED         1
5987 #define SQLITE_DBSTATUS_SCHEMA_USED        2
5988 #define SQLITE_DBSTATUS_STMT_USED          3
5989 #define SQLITE_DBSTATUS_MAX                3   /* Largest defined DBSTATUS */
5990
5991
5992 /*
5993 ** CAPI3REF: Prepared Statement Status
5994 **
5995 ** ^(Each prepared statement maintains various
5996 ** [SQLITE_STMTSTATUS_SORT | counters] that measure the number
5997 ** of times it has performed specific operations.)^  These counters can
5998 ** be used to monitor the performance characteristics of the prepared
5999 ** statements.  For example, if the number of table steps greatly exceeds
6000 ** the number of table searches or result rows, that would tend to indicate
6001 ** that the prepared statement is using a full table scan rather than
6002 ** an index.  
6003 **
6004 ** ^(This interface is used to retrieve and reset counter values from
6005 ** a [prepared statement].  The first argument is the prepared statement
6006 ** object to be interrogated.  The second argument
6007 ** is an integer code for a specific [SQLITE_STMTSTATUS_SORT | counter]
6008 ** to be interrogated.)^
6009 ** ^The current value of the requested counter is returned.
6010 ** ^If the resetFlg is true, then the counter is reset to zero after this
6011 ** interface call returns.
6012 **
6013 ** See also: [sqlite3_status()] and [sqlite3_db_status()].
6014 */
6015 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
6016
6017 /*
6018 ** CAPI3REF: Status Parameters for prepared statements
6019 **
6020 ** These preprocessor macros define integer codes that name counter
6021 ** values associated with the [sqlite3_stmt_status()] interface.
6022 ** The meanings of the various counters are as follows:
6023 **
6024 ** <dl>
6025 ** <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
6026 ** <dd>^This is the number of times that SQLite has stepped forward in
6027 ** a table as part of a full table scan.  Large numbers for this counter
6028 ** may indicate opportunities for performance improvement through 
6029 ** careful use of indices.</dd>
6030 **
6031 ** <dt>SQLITE_STMTSTATUS_SORT</dt>
6032 ** <dd>^This is the number of sort operations that have occurred.
6033 ** A non-zero value in this counter may indicate an opportunity to
6034 ** improvement performance through careful use of indices.</dd>
6035 **
6036 ** <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
6037 ** <dd>^This is the number of rows inserted into transient indices that
6038 ** were created automatically in order to help joins run faster.
6039 ** A non-zero value in this counter may indicate an opportunity to
6040 ** improvement performance by adding permanent indices that do not
6041 ** need to be reinitialized each time the statement is run.</dd>
6042 **
6043 ** </dl>
6044 */
6045 #define SQLITE_STMTSTATUS_FULLSCAN_STEP     1
6046 #define SQLITE_STMTSTATUS_SORT              2
6047 #define SQLITE_STMTSTATUS_AUTOINDEX         3
6048
6049 /*
6050 ** CAPI3REF: Custom Page Cache Object
6051 **
6052 ** The sqlite3_pcache type is opaque.  It is implemented by
6053 ** the pluggable module.  The SQLite core has no knowledge of
6054 ** its size or internal structure and never deals with the
6055 ** sqlite3_pcache object except by holding and passing pointers
6056 ** to the object.
6057 **
6058 ** See [sqlite3_pcache_methods] for additional information.
6059 */
6060 typedef struct sqlite3_pcache sqlite3_pcache;
6061
6062 /*
6063 ** CAPI3REF: Application Defined Page Cache.
6064 ** KEYWORDS: {page cache}
6065 **
6066 ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE], ...) interface can
6067 ** register an alternative page cache implementation by passing in an 
6068 ** instance of the sqlite3_pcache_methods structure.)^
6069 ** In many applications, most of the heap memory allocated by 
6070 ** SQLite is used for the page cache.
6071 ** By implementing a 
6072 ** custom page cache using this API, an application can better control
6073 ** the amount of memory consumed by SQLite, the way in which 
6074 ** that memory is allocated and released, and the policies used to 
6075 ** determine exactly which parts of a database file are cached and for 
6076 ** how long.
6077 **
6078 ** The alternative page cache mechanism is an
6079 ** extreme measure that is only needed by the most demanding applications.
6080 ** The built-in page cache is recommended for most uses.
6081 **
6082 ** ^(The contents of the sqlite3_pcache_methods structure are copied to an
6083 ** internal buffer by SQLite within the call to [sqlite3_config].  Hence
6084 ** the application may discard the parameter after the call to
6085 ** [sqlite3_config()] returns.)^
6086 **
6087 ** ^(The xInit() method is called once for each effective 
6088 ** call to [sqlite3_initialize()])^
6089 ** (usually only once during the lifetime of the process). ^(The xInit()
6090 ** method is passed a copy of the sqlite3_pcache_methods.pArg value.)^
6091 ** The intent of the xInit() method is to set up global data structures 
6092 ** required by the custom page cache implementation. 
6093 ** ^(If the xInit() method is NULL, then the 
6094 ** built-in default page cache is used instead of the application defined
6095 ** page cache.)^
6096 **
6097 ** ^The xShutdown() method is called by [sqlite3_shutdown()].
6098 ** It can be used to clean up 
6099 ** any outstanding resources before process shutdown, if required.
6100 ** ^The xShutdown() method may be NULL.
6101 **
6102 ** ^SQLite automatically serializes calls to the xInit method,
6103 ** so the xInit method need not be threadsafe.  ^The
6104 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
6105 ** not need to be threadsafe either.  All other methods must be threadsafe
6106 ** in multithreaded applications.
6107 **
6108 ** ^SQLite will never invoke xInit() more than once without an intervening
6109 ** call to xShutdown().
6110 **
6111 ** ^SQLite invokes the xCreate() method to construct a new cache instance.
6112 ** SQLite will typically create one cache instance for each open database file,
6113 ** though this is not guaranteed. ^The
6114 ** first parameter, szPage, is the size in bytes of the pages that must
6115 ** be allocated by the cache.  ^szPage will not be a power of two.  ^szPage
6116 ** will the page size of the database file that is to be cached plus an
6117 ** increment (here called "R") of about 100 or 200.  SQLite will use the
6118 ** extra R bytes on each page to store metadata about the underlying
6119 ** database page on disk.  The value of R depends
6120 ** on the SQLite version, the target platform, and how SQLite was compiled.
6121 ** ^R is constant for a particular build of SQLite.  ^The second argument to
6122 ** xCreate(), bPurgeable, is true if the cache being created will
6123 ** be used to cache database pages of a file stored on disk, or
6124 ** false if it is used for an in-memory database. The cache implementation
6125 ** does not have to do anything special based with the value of bPurgeable;
6126 ** it is purely advisory.  ^On a cache where bPurgeable is false, SQLite will
6127 ** never invoke xUnpin() except to deliberately delete a page.
6128 ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
6129 ** false will always have the "discard" flag set to true.  
6130 ** ^Hence, a cache created with bPurgeable false will
6131 ** never contain any unpinned pages.
6132 **
6133 ** ^(The xCachesize() method may be called at any time by SQLite to set the
6134 ** suggested maximum cache-size (number of pages stored by) the cache
6135 ** instance passed as the first argument. This is the value configured using
6136 ** the SQLite "[PRAGMA cache_size]" command.)^  As with the bPurgeable
6137 ** parameter, the implementation is not required to do anything with this
6138 ** value; it is advisory only.
6139 **
6140 ** The xPagecount() method must return the number of pages currently
6141 ** stored in the cache, both pinned and unpinned.
6142 ** 
6143 ** The xFetch() method locates a page in the cache and returns a pointer to 
6144 ** the page, or a NULL pointer.
6145 ** A "page", in this context, means a buffer of szPage bytes aligned at an
6146 ** 8-byte boundary. The page to be fetched is determined by the key. ^The
6147 ** mimimum key value is 1.  After it has been retrieved using xFetch, the page 
6148 ** is considered to be "pinned".
6149 **
6150 ** If the requested page is already in the page cache, then the page cache
6151 ** implementation must return a pointer to the page buffer with its content
6152 ** intact.  If the requested page is not already in the cache, then the
6153 ** behavior of the cache implementation should use the value of the createFlag
6154 ** parameter to help it determined what action to take:
6155 **
6156 ** <table border=1 width=85% align=center>
6157 ** <tr><th> createFlag <th> Behaviour when page is not already in cache
6158 ** <tr><td> 0 <td> Do not allocate a new page.  Return NULL.
6159 ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
6160 **                 Otherwise return NULL.
6161 ** <tr><td> 2 <td> Make every effort to allocate a new page.  Only return
6162 **                 NULL if allocating a new page is effectively impossible.
6163 ** </table>
6164 **
6165 ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1.  SQLite
6166 ** will only use a createFlag of 2 after a prior call with a createFlag of 1
6167 ** failed.)^  In between the to xFetch() calls, SQLite may
6168 ** attempt to unpin one or more cache pages by spilling the content of
6169 ** pinned pages to disk and synching the operating system disk cache.
6170 **
6171 ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
6172 ** as its second argument.  If the third parameter, discard, is non-zero,
6173 ** then the page must be evicted from the cache.
6174 ** ^If the discard parameter is
6175 ** zero, then the page may be discarded or retained at the discretion of
6176 ** page cache implementation. ^The page cache implementation
6177 ** may choose to evict unpinned pages at any time.
6178 **
6179 ** The cache must not perform any reference counting. A single 
6180 ** call to xUnpin() unpins the page regardless of the number of prior calls 
6181 ** to xFetch().
6182 **
6183 ** The xRekey() method is used to change the key value associated with the
6184 ** page passed as the second argument. If the cache
6185 ** previously contains an entry associated with newKey, it must be
6186 ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
6187 ** to be pinned.
6188 **
6189 ** When SQLite calls the xTruncate() method, the cache must discard all
6190 ** existing cache entries with page numbers (keys) greater than or equal
6191 ** to the value of the iLimit parameter passed to xTruncate(). If any
6192 ** of these pages are pinned, they are implicitly unpinned, meaning that
6193 ** they can be safely discarded.
6194 **
6195 ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
6196 ** All resources associated with the specified cache should be freed. ^After
6197 ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
6198 ** handle invalid, and will not use it with any other sqlite3_pcache_methods
6199 ** functions.
6200 */
6201 typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
6202 struct sqlite3_pcache_methods {
6203   void *pArg;
6204   int (*xInit)(void*);
6205   void (*xShutdown)(void*);
6206   sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
6207   void (*xCachesize)(sqlite3_pcache*, int nCachesize);
6208   int (*xPagecount)(sqlite3_pcache*);
6209   void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
6210   void (*xUnpin)(sqlite3_pcache*, void*, int discard);
6211   void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
6212   void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
6213   void (*xDestroy)(sqlite3_pcache*);
6214 };
6215
6216 /*
6217 ** CAPI3REF: Online Backup Object
6218 **
6219 ** The sqlite3_backup object records state information about an ongoing
6220 ** online backup operation.  ^The sqlite3_backup object is created by
6221 ** a call to [sqlite3_backup_init()] and is destroyed by a call to
6222 ** [sqlite3_backup_finish()].
6223 **
6224 ** See Also: [Using the SQLite Online Backup API]
6225 */
6226 typedef struct sqlite3_backup sqlite3_backup;
6227
6228 /*
6229 ** CAPI3REF: Online Backup API.
6230 **
6231 ** The backup API copies the content of one database into another.
6232 ** It is useful either for creating backups of databases or
6233 ** for copying in-memory databases to or from persistent files. 
6234 **
6235 ** See Also: [Using the SQLite Online Backup API]
6236 **
6237 ** ^Exclusive access is required to the destination database for the 
6238 ** duration of the operation. ^However the source database is only
6239 ** read-locked while it is actually being read; it is not locked
6240 ** continuously for the entire backup operation. ^Thus, the backup may be
6241 ** performed on a live source database without preventing other users from
6242 ** reading or writing to the source database while the backup is underway.
6243 ** 
6244 ** ^(To perform a backup operation: 
6245 **   <ol>
6246 **     <li><b>sqlite3_backup_init()</b> is called once to initialize the
6247 **         backup, 
6248 **     <li><b>sqlite3_backup_step()</b> is called one or more times to transfer 
6249 **         the data between the two databases, and finally
6250 **     <li><b>sqlite3_backup_finish()</b> is called to release all resources 
6251 **         associated with the backup operation. 
6252 **   </ol>)^
6253 ** There should be exactly one call to sqlite3_backup_finish() for each
6254 ** successful call to sqlite3_backup_init().
6255 **
6256 ** <b>sqlite3_backup_init()</b>
6257 **
6258 ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the 
6259 ** [database connection] associated with the destination database 
6260 ** and the database name, respectively.
6261 ** ^The database name is "main" for the main database, "temp" for the
6262 ** temporary database, or the name specified after the AS keyword in
6263 ** an [ATTACH] statement for an attached database.
6264 ** ^The S and M arguments passed to 
6265 ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
6266 ** and database name of the source database, respectively.
6267 ** ^The source and destination [database connections] (parameters S and D)
6268 ** must be different or else sqlite3_backup_init(D,N,S,M) will file with
6269 ** an error.
6270 **
6271 ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
6272 ** returned and an error code and error message are store3d in the
6273 ** destination [database connection] D.
6274 ** ^The error code and message for the failed call to sqlite3_backup_init()
6275 ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
6276 ** [sqlite3_errmsg16()] functions.
6277 ** ^A successful call to sqlite3_backup_init() returns a pointer to an
6278 ** [sqlite3_backup] object.
6279 ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
6280 ** sqlite3_backup_finish() functions to perform the specified backup 
6281 ** operation.
6282 **
6283 ** <b>sqlite3_backup_step()</b>
6284 **
6285 ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between 
6286 ** the source and destination databases specified by [sqlite3_backup] object B.
6287 ** ^If N is negative, all remaining source pages are copied. 
6288 ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
6289 ** are still more pages to be copied, then the function resturns [SQLITE_OK].
6290 ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
6291 ** from source to destination, then it returns [SQLITE_DONE].
6292 ** ^If an error occurs while running sqlite3_backup_step(B,N),
6293 ** then an [error code] is returned. ^As well as [SQLITE_OK] and
6294 ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
6295 ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
6296 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
6297 **
6298 ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
6299 ** <ol>
6300 ** <li> the destination database was opened read-only, or
6301 ** <li> the destination database is using write-ahead-log journaling
6302 ** and the destination and source page sizes differ, or
6303 ** <li> The destination database is an in-memory database and the
6304 ** destination and source page sizes differ.
6305 ** </ol>)^
6306 **
6307 ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
6308 ** the [sqlite3_busy_handler | busy-handler function]
6309 ** is invoked (if one is specified). ^If the 
6310 ** busy-handler returns non-zero before the lock is available, then 
6311 ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
6312 ** sqlite3_backup_step() can be retried later. ^If the source
6313 ** [database connection]
6314 ** is being used to write to the source database when sqlite3_backup_step()
6315 ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
6316 ** case the call to sqlite3_backup_step() can be retried later on. ^(If
6317 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
6318 ** [SQLITE_READONLY] is returned, then 
6319 ** there is no point in retrying the call to sqlite3_backup_step(). These 
6320 ** errors are considered fatal.)^  The application must accept 
6321 ** that the backup operation has failed and pass the backup operation handle 
6322 ** to the sqlite3_backup_finish() to release associated resources.
6323 **
6324 ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
6325 ** on the destination file. ^The exclusive lock is not released until either 
6326 ** sqlite3_backup_finish() is called or the backup operation is complete 
6327 ** and sqlite3_backup_step() returns [SQLITE_DONE].  ^Every call to
6328 ** sqlite3_backup_step() obtains a [shared lock] on the source database that
6329 ** lasts for the duration of the sqlite3_backup_step() call.
6330 ** ^Because the source database is not locked between calls to
6331 ** sqlite3_backup_step(), the source database may be modified mid-way
6332 ** through the backup process.  ^If the source database is modified by an
6333 ** external process or via a database connection other than the one being
6334 ** used by the backup operation, then the backup will be automatically
6335 ** restarted by the next call to sqlite3_backup_step(). ^If the source 
6336 ** database is modified by the using the same database connection as is used
6337 ** by the backup operation, then the backup database is automatically
6338 ** updated at the same time.
6339 **
6340 ** <b>sqlite3_backup_finish()</b>
6341 **
6342 ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the 
6343 ** application wishes to abandon the backup operation, the application
6344 ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
6345 ** ^The sqlite3_backup_finish() interfaces releases all
6346 ** resources associated with the [sqlite3_backup] object. 
6347 ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
6348 ** active write-transaction on the destination database is rolled back.
6349 ** The [sqlite3_backup] object is invalid
6350 ** and may not be used following a call to sqlite3_backup_finish().
6351 **
6352 ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
6353 ** sqlite3_backup_step() errors occurred, regardless or whether or not
6354 ** sqlite3_backup_step() completed.
6355 ** ^If an out-of-memory condition or IO error occurred during any prior
6356 ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
6357 ** sqlite3_backup_finish() returns the corresponding [error code].
6358 **
6359 ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
6360 ** is not a permanent error and does not affect the return value of
6361 ** sqlite3_backup_finish().
6362 **
6363 ** <b>sqlite3_backup_remaining(), sqlite3_backup_pagecount()</b>
6364 **
6365 ** ^Each call to sqlite3_backup_step() sets two values inside
6366 ** the [sqlite3_backup] object: the number of pages still to be backed
6367 ** up and the total number of pages in the source database file.
6368 ** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces
6369 ** retrieve these two values, respectively.
6370 **
6371 ** ^The values returned by these functions are only updated by
6372 ** sqlite3_backup_step(). ^If the source database is modified during a backup
6373 ** operation, then the values are not updated to account for any extra
6374 ** pages that need to be updated or the size of the source database file
6375 ** changing.
6376 **
6377 ** <b>Concurrent Usage of Database Handles</b>
6378 **
6379 ** ^The source [database connection] may be used by the application for other
6380 ** purposes while a backup operation is underway or being initialized.
6381 ** ^If SQLite is compiled and configured to support threadsafe database
6382 ** connections, then the source database connection may be used concurrently
6383 ** from within other threads.
6384 **
6385 ** However, the application must guarantee that the destination 
6386 ** [database connection] is not passed to any other API (by any thread) after 
6387 ** sqlite3_backup_init() is called and before the corresponding call to
6388 ** sqlite3_backup_finish().  SQLite does not currently check to see
6389 ** if the application incorrectly accesses the destination [database connection]
6390 ** and so no error code is reported, but the operations may malfunction
6391 ** nevertheless.  Use of the destination database connection while a
6392 ** backup is in progress might also also cause a mutex deadlock.
6393 **
6394 ** If running in [shared cache mode], the application must
6395 ** guarantee that the shared cache used by the destination database
6396 ** is not accessed while the backup is running. In practice this means
6397 ** that the application must guarantee that the disk file being 
6398 ** backed up to is not accessed by any connection within the process,
6399 ** not just the specific connection that was passed to sqlite3_backup_init().
6400 **
6401 ** The [sqlite3_backup] object itself is partially threadsafe. Multiple 
6402 ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
6403 ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
6404 ** APIs are not strictly speaking threadsafe. If they are invoked at the
6405 ** same time as another thread is invoking sqlite3_backup_step() it is
6406 ** possible that they return invalid values.
6407 */
6408 SQLITE_API sqlite3_backup *sqlite3_backup_init(
6409   sqlite3 *pDest,                        /* Destination database handle */
6410   const char *zDestName,                 /* Destination database name */
6411   sqlite3 *pSource,                      /* Source database handle */
6412   const char *zSourceName                /* Source database name */
6413 );
6414 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
6415 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
6416 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
6417 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
6418
6419 /*
6420 ** CAPI3REF: Unlock Notification
6421 **
6422 ** ^When running in shared-cache mode, a database operation may fail with
6423 ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
6424 ** individual tables within the shared-cache cannot be obtained. See
6425 ** [SQLite Shared-Cache Mode] for a description of shared-cache locking. 
6426 ** ^This API may be used to register a callback that SQLite will invoke 
6427 ** when the connection currently holding the required lock relinquishes it.
6428 ** ^This API is only available if the library was compiled with the
6429 ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
6430 **
6431 ** See Also: [Using the SQLite Unlock Notification Feature].
6432 **
6433 ** ^Shared-cache locks are released when a database connection concludes
6434 ** its current transaction, either by committing it or rolling it back. 
6435 **
6436 ** ^When a connection (known as the blocked connection) fails to obtain a
6437 ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
6438 ** identity of the database connection (the blocking connection) that
6439 ** has locked the required resource is stored internally. ^After an 
6440 ** application receives an SQLITE_LOCKED error, it may call the
6441 ** sqlite3_unlock_notify() method with the blocked connection handle as 
6442 ** the first argument to register for a callback that will be invoked
6443 ** when the blocking connections current transaction is concluded. ^The
6444 ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
6445 ** call that concludes the blocking connections transaction.
6446 **
6447 ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
6448 ** there is a chance that the blocking connection will have already
6449 ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
6450 ** If this happens, then the specified callback is invoked immediately,
6451 ** from within the call to sqlite3_unlock_notify().)^
6452 **
6453 ** ^If the blocked connection is attempting to obtain a write-lock on a
6454 ** shared-cache table, and more than one other connection currently holds
6455 ** a read-lock on the same table, then SQLite arbitrarily selects one of 
6456 ** the other connections to use as the blocking connection.
6457 **
6458 ** ^(There may be at most one unlock-notify callback registered by a 
6459 ** blocked connection. If sqlite3_unlock_notify() is called when the
6460 ** blocked connection already has a registered unlock-notify callback,
6461 ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
6462 ** called with a NULL pointer as its second argument, then any existing
6463 ** unlock-notify callback is canceled. ^The blocked connections 
6464 ** unlock-notify callback may also be canceled by closing the blocked
6465 ** connection using [sqlite3_close()].
6466 **
6467 ** The unlock-notify callback is not reentrant. If an application invokes
6468 ** any sqlite3_xxx API functions from within an unlock-notify callback, a
6469 ** crash or deadlock may be the result.
6470 **
6471 ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
6472 ** returns SQLITE_OK.
6473 **
6474 ** <b>Callback Invocation Details</b>
6475 **
6476 ** When an unlock-notify callback is registered, the application provides a 
6477 ** single void* pointer that is passed to the callback when it is invoked.
6478 ** However, the signature of the callback function allows SQLite to pass
6479 ** it an array of void* context pointers. The first argument passed to
6480 ** an unlock-notify callback is a pointer to an array of void* pointers,
6481 ** and the second is the number of entries in the array.
6482 **
6483 ** When a blocking connections transaction is concluded, there may be
6484 ** more than one blocked connection that has registered for an unlock-notify
6485 ** callback. ^If two or more such blocked connections have specified the
6486 ** same callback function, then instead of invoking the callback function
6487 ** multiple times, it is invoked once with the set of void* context pointers
6488 ** specified by the blocked connections bundled together into an array.
6489 ** This gives the application an opportunity to prioritize any actions 
6490 ** related to the set of unblocked database connections.
6491 **
6492 ** <b>Deadlock Detection</b>
6493 **
6494 ** Assuming that after registering for an unlock-notify callback a 
6495 ** database waits for the callback to be issued before taking any further
6496 ** action (a reasonable assumption), then using this API may cause the
6497 ** application to deadlock. For example, if connection X is waiting for
6498 ** connection Y's transaction to be concluded, and similarly connection
6499 ** Y is waiting on connection X's transaction, then neither connection
6500 ** will proceed and the system may remain deadlocked indefinitely.
6501 **
6502 ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
6503 ** detection. ^If a given call to sqlite3_unlock_notify() would put the
6504 ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
6505 ** unlock-notify callback is registered. The system is said to be in
6506 ** a deadlocked state if connection A has registered for an unlock-notify
6507 ** callback on the conclusion of connection B's transaction, and connection
6508 ** B has itself registered for an unlock-notify callback when connection
6509 ** A's transaction is concluded. ^Indirect deadlock is also detected, so
6510 ** the system is also considered to be deadlocked if connection B has
6511 ** registered for an unlock-notify callback on the conclusion of connection
6512 ** C's transaction, where connection C is waiting on connection A. ^Any
6513 ** number of levels of indirection are allowed.
6514 **
6515 ** <b>The "DROP TABLE" Exception</b>
6516 **
6517 ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost 
6518 ** always appropriate to call sqlite3_unlock_notify(). There is however,
6519 ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
6520 ** SQLite checks if there are any currently executing SELECT statements
6521 ** that belong to the same connection. If there are, SQLITE_LOCKED is
6522 ** returned. In this case there is no "blocking connection", so invoking
6523 ** sqlite3_unlock_notify() results in the unlock-notify callback being
6524 ** invoked immediately. If the application then re-attempts the "DROP TABLE"
6525 ** or "DROP INDEX" query, an infinite loop might be the result.
6526 **
6527 ** One way around this problem is to check the extended error code returned
6528 ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
6529 ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
6530 ** the special "DROP TABLE/INDEX" case, the extended error code is just 
6531 ** SQLITE_LOCKED.)^
6532 */
6533 SQLITE_API int sqlite3_unlock_notify(
6534   sqlite3 *pBlocked,                          /* Waiting connection */
6535   void (*xNotify)(void **apArg, int nArg),    /* Callback function to invoke */
6536   void *pNotifyArg                            /* Argument to pass to xNotify */
6537 );
6538
6539
6540 /*
6541 ** CAPI3REF: String Comparison
6542 **
6543 ** ^The [sqlite3_strnicmp()] API allows applications and extensions to
6544 ** compare the contents of two buffers containing UTF-8 strings in a
6545 ** case-independent fashion, using the same definition of case independence 
6546 ** that SQLite uses internally when comparing identifiers.
6547 */
6548 SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
6549
6550 /*
6551 ** CAPI3REF: Error Logging Interface
6552 **
6553 ** ^The [sqlite3_log()] interface writes a message into the error log
6554 ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
6555 ** ^If logging is enabled, the zFormat string and subsequent arguments are
6556 ** used with [sqlite3_snprintf()] to generate the final output string.
6557 **
6558 ** The sqlite3_log() interface is intended for use by extensions such as
6559 ** virtual tables, collating functions, and SQL functions.  While there is
6560 ** nothing to prevent an application from calling sqlite3_log(), doing so
6561 ** is considered bad form.
6562 **
6563 ** The zFormat string must not be NULL.
6564 **
6565 ** To avoid deadlocks and other threading problems, the sqlite3_log() routine
6566 ** will not use dynamically allocated memory.  The log message is stored in
6567 ** a fixed-length buffer on the stack.  If the log message is longer than
6568 ** a few hundred characters, it will be truncated to the length of the
6569 ** buffer.
6570 */
6571 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
6572
6573 /*
6574 ** CAPI3REF: Write-Ahead Log Commit Hook
6575 **
6576 ** ^The [sqlite3_wal_hook()] function is used to register a callback that
6577 ** will be invoked each time a database connection commits data to a
6578 ** [write-ahead log] (i.e. whenever a transaction is committed in
6579 ** [journal_mode | journal_mode=WAL mode]). 
6580 **
6581 ** ^The callback is invoked by SQLite after the commit has taken place and 
6582 ** the associated write-lock on the database released, so the implementation 
6583 ** may read, write or [checkpoint] the database as required.
6584 **
6585 ** ^The first parameter passed to the callback function when it is invoked
6586 ** is a copy of the third parameter passed to sqlite3_wal_hook() when
6587 ** registering the callback. ^The second is a copy of the database handle.
6588 ** ^The third parameter is the name of the database that was written to -
6589 ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
6590 ** is the number of pages currently in the write-ahead log file,
6591 ** including those that were just committed.
6592 **
6593 ** The callback function should normally return [SQLITE_OK].  ^If an error
6594 ** code is returned, that error will propagate back up through the
6595 ** SQLite code base to cause the statement that provoked the callback
6596 ** to report an error, though the commit will have still occurred. If the
6597 ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
6598 ** that does not correspond to any valid SQLite error code, the results
6599 ** are undefined.
6600 **
6601 ** A single database handle may have at most a single write-ahead log callback 
6602 ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
6603 ** previously registered write-ahead log callback. ^Note that the
6604 ** [sqlite3_wal_autocheckpoint()] interface and the
6605 ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
6606 ** those overwrite any prior [sqlite3_wal_hook()] settings.
6607 */
6608 SQLITE_API void *sqlite3_wal_hook(
6609   sqlite3*, 
6610   int(*)(void *,sqlite3*,const char*,int),
6611   void*
6612 );
6613
6614 /*
6615 ** CAPI3REF: Configure an auto-checkpoint
6616 **
6617 ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
6618 ** [sqlite3_wal_hook()] that causes any database on [database connection] D
6619 ** to automatically [checkpoint]
6620 ** after committing a transaction if there are N or
6621 ** more frames in the [write-ahead log] file.  ^Passing zero or 
6622 ** a negative value as the nFrame parameter disables automatic
6623 ** checkpoints entirely.
6624 **
6625 ** ^The callback registered by this function replaces any existing callback
6626 ** registered using [sqlite3_wal_hook()].  ^Likewise, registering a callback
6627 ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
6628 ** configured by this function.
6629 **
6630 ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
6631 ** from SQL.
6632 **
6633 ** ^Every new [database connection] defaults to having the auto-checkpoint
6634 ** enabled with a threshold of 1000 pages.  The use of this interface
6635 ** is only necessary if the default setting is found to be suboptimal
6636 ** for a particular application.
6637 */
6638 SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
6639
6640 /*
6641 ** CAPI3REF: Checkpoint a database
6642 **
6643 ** ^The [sqlite3_wal_checkpoint(D,X)] interface causes database named X
6644 ** on [database connection] D to be [checkpointed].  ^If X is NULL or an
6645 ** empty string, then a checkpoint is run on all databases of
6646 ** connection D.  ^If the database connection D is not in
6647 ** [WAL | write-ahead log mode] then this interface is a harmless no-op.
6648 **
6649 ** ^The [wal_checkpoint pragma] can be used to invoke this interface
6650 ** from SQL.  ^The [sqlite3_wal_autocheckpoint()] interface and the
6651 ** [wal_autocheckpoint pragma] can be used to cause this interface to be
6652 ** run whenever the WAL reaches a certain size threshold.
6653 */
6654 SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
6655
6656 /*
6657 ** Undo the hack that converts floating point types to integer for
6658 ** builds on processors without floating point support.
6659 */
6660 #ifdef SQLITE_OMIT_FLOATING_POINT
6661 # undef double
6662 #endif
6663
6664 #if 0
6665 }  /* End of the 'extern "C"' block */
6666 #endif
6667 #endif
6668
6669 /*
6670 ** 2010 August 30
6671 **
6672 ** The author disclaims copyright to this source code.  In place of
6673 ** a legal notice, here is a blessing:
6674 **
6675 **    May you do good and not evil.
6676 **    May you find forgiveness for yourself and forgive others.
6677 **    May you share freely, never taking more than you give.
6678 **
6679 *************************************************************************
6680 */
6681
6682 #ifndef _SQLITE3RTREE_H_
6683 #define _SQLITE3RTREE_H_
6684
6685
6686 #if 0
6687 extern "C" {
6688 #endif
6689
6690 typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
6691
6692 /*
6693 ** Register a geometry callback named zGeom that can be used as part of an
6694 ** R-Tree geometry query as follows:
6695 **
6696 **   SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
6697 */
6698 SQLITE_API int sqlite3_rtree_geometry_callback(
6699   sqlite3 *db,
6700   const char *zGeom,
6701   int (*xGeom)(sqlite3_rtree_geometry *, int nCoord, double *aCoord, int *pRes),
6702   void *pContext
6703 );
6704
6705
6706 /*
6707 ** A pointer to a structure of the following type is passed as the first
6708 ** argument to callbacks registered using rtree_geometry_callback().
6709 */
6710 struct sqlite3_rtree_geometry {
6711   void *pContext;                 /* Copy of pContext passed to s_r_g_c() */
6712   int nParam;                     /* Size of array aParam[] */
6713   double *aParam;                 /* Parameters passed to SQL geom function */
6714   void *pUser;                    /* Callback implementation user data */
6715   void (*xDelUser)(void *);       /* Called by SQLite to clean up pUser */
6716 };
6717
6718
6719 #if 0
6720 }  /* end of the 'extern "C"' block */
6721 #endif
6722
6723 #endif  /* ifndef _SQLITE3RTREE_H_ */
6724
6725
6726 /************** End of sqlite3.h *********************************************/
6727 /************** Continuing where we left off in sqliteInt.h ******************/
6728 /************** Include hash.h in the middle of sqliteInt.h ******************/
6729 /************** Begin file hash.h ********************************************/
6730 /*
6731 ** 2001 September 22
6732 **
6733 ** The author disclaims copyright to this source code.  In place of
6734 ** a legal notice, here is a blessing:
6735 **
6736 **    May you do good and not evil.
6737 **    May you find forgiveness for yourself and forgive others.
6738 **    May you share freely, never taking more than you give.
6739 **
6740 *************************************************************************
6741 ** This is the header file for the generic hash-table implemenation
6742 ** used in SQLite.
6743 */
6744 #ifndef _SQLITE_HASH_H_
6745 #define _SQLITE_HASH_H_
6746
6747 /* Forward declarations of structures. */
6748 typedef struct Hash Hash;
6749 typedef struct HashElem HashElem;
6750
6751 /* A complete hash table is an instance of the following structure.
6752 ** The internals of this structure are intended to be opaque -- client
6753 ** code should not attempt to access or modify the fields of this structure
6754 ** directly.  Change this structure only by using the routines below.
6755 ** However, some of the "procedures" and "functions" for modifying and
6756 ** accessing this structure are really macros, so we can't really make
6757 ** this structure opaque.
6758 **
6759 ** All elements of the hash table are on a single doubly-linked list.
6760 ** Hash.first points to the head of this list.
6761 **
6762 ** There are Hash.htsize buckets.  Each bucket points to a spot in
6763 ** the global doubly-linked list.  The contents of the bucket are the
6764 ** element pointed to plus the next _ht.count-1 elements in the list.
6765 **
6766 ** Hash.htsize and Hash.ht may be zero.  In that case lookup is done
6767 ** by a linear search of the global list.  For small tables, the 
6768 ** Hash.ht table is never allocated because if there are few elements
6769 ** in the table, it is faster to do a linear search than to manage
6770 ** the hash table.
6771 */
6772 struct Hash {
6773   unsigned int htsize;      /* Number of buckets in the hash table */
6774   unsigned int count;       /* Number of entries in this table */
6775   HashElem *first;          /* The first element of the array */
6776   struct _ht {              /* the hash table */
6777     int count;                 /* Number of entries with this hash */
6778     HashElem *chain;           /* Pointer to first entry with this hash */
6779   } *ht;
6780 };
6781
6782 /* Each element in the hash table is an instance of the following 
6783 ** structure.  All elements are stored on a single doubly-linked list.
6784 **
6785 ** Again, this structure is intended to be opaque, but it can't really
6786 ** be opaque because it is used by macros.
6787 */
6788 struct HashElem {
6789   HashElem *next, *prev;       /* Next and previous elements in the table */
6790   void *data;                  /* Data associated with this element */
6791   const char *pKey; int nKey;  /* Key associated with this element */
6792 };
6793
6794 /*
6795 ** Access routines.  To delete, insert a NULL pointer.
6796 */
6797 SQLITE_PRIVATE void sqlite3HashInit(Hash*);
6798 SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, int nKey, void *pData);
6799 SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey, int nKey);
6800 SQLITE_PRIVATE void sqlite3HashClear(Hash*);
6801
6802 /*
6803 ** Macros for looping over all elements of a hash table.  The idiom is
6804 ** like this:
6805 **
6806 **   Hash h;
6807 **   HashElem *p;
6808 **   ...
6809 **   for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
6810 **     SomeStructure *pData = sqliteHashData(p);
6811 **     // do something with pData
6812 **   }
6813 */
6814 #define sqliteHashFirst(H)  ((H)->first)
6815 #define sqliteHashNext(E)   ((E)->next)
6816 #define sqliteHashData(E)   ((E)->data)
6817 /* #define sqliteHashKey(E)    ((E)->pKey) // NOT USED */
6818 /* #define sqliteHashKeysize(E) ((E)->nKey)  // NOT USED */
6819
6820 /*
6821 ** Number of entries in a hash table
6822 */
6823 /* #define sqliteHashCount(H)  ((H)->count) // NOT USED */
6824
6825 #endif /* _SQLITE_HASH_H_ */
6826
6827 /************** End of hash.h ************************************************/
6828 /************** Continuing where we left off in sqliteInt.h ******************/
6829 /************** Include parse.h in the middle of sqliteInt.h *****************/
6830 /************** Begin file parse.h *******************************************/
6831 #define TK_SEMI                            1
6832 #define TK_EXPLAIN                         2
6833 #define TK_QUERY                           3
6834 #define TK_PLAN                            4
6835 #define TK_BEGIN                           5
6836 #define TK_TRANSACTION                     6
6837 #define TK_DEFERRED                        7
6838 #define TK_IMMEDIATE                       8
6839 #define TK_EXCLUSIVE                       9
6840 #define TK_COMMIT                         10
6841 #define TK_END                            11
6842 #define TK_ROLLBACK                       12
6843 #define TK_SAVEPOINT                      13
6844 #define TK_RELEASE                        14
6845 #define TK_TO                             15
6846 #define TK_TABLE                          16
6847 #define TK_CREATE                         17
6848 #define TK_IF                             18
6849 #define TK_NOT                            19
6850 #define TK_EXISTS                         20
6851 #define TK_TEMP                           21
6852 #define TK_LP                             22
6853 #define TK_RP                             23
6854 #define TK_AS                             24
6855 #define TK_COMMA                          25
6856 #define TK_ID                             26
6857 #define TK_INDEXED                        27
6858 #define TK_ABORT                          28
6859 #define TK_ACTION                         29
6860 #define TK_AFTER                          30
6861 #define TK_ANALYZE                        31
6862 #define TK_ASC                            32
6863 #define TK_ATTACH                         33
6864 #define TK_BEFORE                         34
6865 #define TK_BY                             35
6866 #define TK_CASCADE                        36
6867 #define TK_CAST                           37
6868 #define TK_COLUMNKW                       38
6869 #define TK_CONFLICT                       39
6870 #define TK_DATABASE                       40
6871 #define TK_DESC                           41
6872 #define TK_DETACH                         42
6873 #define TK_EACH                           43
6874 #define TK_FAIL                           44
6875 #define TK_FOR                            45
6876 #define TK_IGNORE                         46
6877 #define TK_INITIALLY                      47
6878 #define TK_INSTEAD                        48
6879 #define TK_LIKE_KW                        49
6880 #define TK_MATCH                          50
6881 #define TK_NO                             51
6882 #define TK_KEY                            52
6883 #define TK_OF                             53
6884 #define TK_OFFSET                         54
6885 #define TK_PRAGMA                         55
6886 #define TK_RAISE                          56
6887 #define TK_REPLACE                        57
6888 #define TK_RESTRICT                       58
6889 #define TK_ROW                            59
6890 #define TK_TRIGGER                        60
6891 #define TK_VACUUM                         61
6892 #define TK_VIEW                           62
6893 #define TK_VIRTUAL                        63
6894 #define TK_REINDEX                        64
6895 #define TK_RENAME                         65
6896 #define TK_CTIME_KW                       66
6897 #define TK_ANY                            67
6898 #define TK_OR                             68
6899 #define TK_AND                            69
6900 #define TK_IS                             70
6901 #define TK_BETWEEN                        71
6902 #define TK_IN                             72
6903 #define TK_ISNULL                         73
6904 #define TK_NOTNULL                        74
6905 #define TK_NE                             75
6906 #define TK_EQ                             76
6907 #define TK_GT                             77
6908 #define TK_LE                             78
6909 #define TK_LT                             79
6910 #define TK_GE                             80
6911 #define TK_ESCAPE                         81
6912 #define TK_BITAND                         82
6913 #define TK_BITOR                          83
6914 #define TK_LSHIFT                         84
6915 #define TK_RSHIFT                         85
6916 #define TK_PLUS                           86
6917 #define TK_MINUS                          87
6918 #define TK_STAR                           88
6919 #define TK_SLASH                          89
6920 #define TK_REM                            90
6921 #define TK_CONCAT                         91
6922 #define TK_COLLATE                        92
6923 #define TK_BITNOT                         93
6924 #define TK_STRING                         94
6925 #define TK_JOIN_KW                        95
6926 #define TK_CONSTRAINT                     96
6927 #define TK_DEFAULT                        97
6928 #define TK_NULL                           98
6929 #define TK_PRIMARY                        99
6930 #define TK_UNIQUE                         100
6931 #define TK_CHECK                          101
6932 #define TK_REFERENCES                     102
6933 #define TK_AUTOINCR                       103
6934 #define TK_ON                             104
6935 #define TK_INSERT                         105
6936 #define TK_DELETE                         106
6937 #define TK_UPDATE                         107
6938 #define TK_SET                            108
6939 #define TK_DEFERRABLE                     109
6940 #define TK_FOREIGN                        110
6941 #define TK_DROP                           111
6942 #define TK_UNION                          112
6943 #define TK_ALL                            113
6944 #define TK_EXCEPT                         114
6945 #define TK_INTERSECT                      115
6946 #define TK_SELECT                         116
6947 #define TK_DISTINCT                       117
6948 #define TK_DOT                            118
6949 #define TK_FROM                           119
6950 #define TK_JOIN                           120
6951 #define TK_USING                          121
6952 #define TK_ORDER                          122
6953 #define TK_GROUP                          123
6954 #define TK_HAVING                         124
6955 #define TK_LIMIT                          125
6956 #define TK_WHERE                          126
6957 #define TK_INTO                           127
6958 #define TK_VALUES                         128
6959 #define TK_INTEGER                        129
6960 #define TK_FLOAT                          130
6961 #define TK_BLOB                           131
6962 #define TK_REGISTER                       132
6963 #define TK_VARIABLE                       133
6964 #define TK_CASE                           134
6965 #define TK_WHEN                           135
6966 #define TK_THEN                           136
6967 #define TK_ELSE                           137
6968 #define TK_INDEX                          138
6969 #define TK_ALTER                          139
6970 #define TK_ADD                            140
6971 #define TK_TO_TEXT                        141
6972 #define TK_TO_BLOB                        142
6973 #define TK_TO_NUMERIC                     143
6974 #define TK_TO_INT                         144
6975 #define TK_TO_REAL                        145
6976 #define TK_ISNOT                          146
6977 #define TK_END_OF_FILE                    147
6978 #define TK_ILLEGAL                        148
6979 #define TK_SPACE                          149
6980 #define TK_UNCLOSED_STRING                150
6981 #define TK_FUNCTION                       151
6982 #define TK_COLUMN                         152
6983 #define TK_AGG_FUNCTION                   153
6984 #define TK_AGG_COLUMN                     154
6985 #define TK_CONST_FUNC                     155
6986 #define TK_UMINUS                         156
6987 #define TK_UPLUS                          157
6988
6989 /************** End of parse.h ***********************************************/
6990 /************** Continuing where we left off in sqliteInt.h ******************/
6991 #include <stdio.h>
6992 #include <stdlib.h>
6993 #include <string.h>
6994 #include <assert.h>
6995 #include <stddef.h>
6996
6997 /*
6998 ** If compiling for a processor that lacks floating point support,
6999 ** substitute integer for floating-point
7000 */
7001 #ifdef SQLITE_OMIT_FLOATING_POINT
7002 # define double sqlite_int64
7003 # define float sqlite_int64
7004 # define LONGDOUBLE_TYPE sqlite_int64
7005 # ifndef SQLITE_BIG_DBL
7006 #   define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
7007 # endif
7008 # define SQLITE_OMIT_DATETIME_FUNCS 1
7009 # define SQLITE_OMIT_TRACE 1
7010 # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
7011 # undef SQLITE_HAVE_ISNAN
7012 #endif
7013 #ifndef SQLITE_BIG_DBL
7014 # define SQLITE_BIG_DBL (1e99)
7015 #endif
7016
7017 /*
7018 ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
7019 ** afterward. Having this macro allows us to cause the C compiler 
7020 ** to omit code used by TEMP tables without messy #ifndef statements.
7021 */
7022 #ifdef SQLITE_OMIT_TEMPDB
7023 #define OMIT_TEMPDB 1
7024 #else
7025 #define OMIT_TEMPDB 0
7026 #endif
7027
7028 /*
7029 ** The "file format" number is an integer that is incremented whenever
7030 ** the VDBE-level file format changes.  The following macros define the
7031 ** the default file format for new databases and the maximum file format
7032 ** that the library can read.
7033 */
7034 #define SQLITE_MAX_FILE_FORMAT 4
7035 #ifndef SQLITE_DEFAULT_FILE_FORMAT
7036 # define SQLITE_DEFAULT_FILE_FORMAT 1
7037 #endif
7038
7039 /*
7040 ** Determine whether triggers are recursive by default.  This can be
7041 ** changed at run-time using a pragma.
7042 */
7043 #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
7044 # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
7045 #endif
7046
7047 /*
7048 ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
7049 ** on the command-line
7050 */
7051 #ifndef SQLITE_TEMP_STORE
7052 # define SQLITE_TEMP_STORE 1
7053 #endif
7054
7055 /*
7056 ** GCC does not define the offsetof() macro so we'll have to do it
7057 ** ourselves.
7058 */
7059 #ifndef offsetof
7060 #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
7061 #endif
7062
7063 /*
7064 ** Check to see if this machine uses EBCDIC.  (Yes, believe it or
7065 ** not, there are still machines out there that use EBCDIC.)
7066 */
7067 #if 'A' == '\301'
7068 # define SQLITE_EBCDIC 1
7069 #else
7070 # define SQLITE_ASCII 1
7071 #endif
7072
7073 /*
7074 ** Integers of known sizes.  These typedefs might change for architectures
7075 ** where the sizes very.  Preprocessor macros are available so that the
7076 ** types can be conveniently redefined at compile-type.  Like this:
7077 **
7078 **         cc '-DUINTPTR_TYPE=long long int' ...
7079 */
7080 #ifndef UINT32_TYPE
7081 # ifdef HAVE_UINT32_T
7082 #  define UINT32_TYPE uint32_t
7083 # else
7084 #  define UINT32_TYPE unsigned int
7085 # endif
7086 #endif
7087 #ifndef UINT16_TYPE
7088 # ifdef HAVE_UINT16_T
7089 #  define UINT16_TYPE uint16_t
7090 # else
7091 #  define UINT16_TYPE unsigned short int
7092 # endif
7093 #endif
7094 #ifndef INT16_TYPE
7095 # ifdef HAVE_INT16_T
7096 #  define INT16_TYPE int16_t
7097 # else
7098 #  define INT16_TYPE short int
7099 # endif
7100 #endif
7101 #ifndef UINT8_TYPE
7102 # ifdef HAVE_UINT8_T
7103 #  define UINT8_TYPE uint8_t
7104 # else
7105 #  define UINT8_TYPE unsigned char
7106 # endif
7107 #endif
7108 #ifndef INT8_TYPE
7109 # ifdef HAVE_INT8_T
7110 #  define INT8_TYPE int8_t
7111 # else
7112 #  define INT8_TYPE signed char
7113 # endif
7114 #endif
7115 #ifndef LONGDOUBLE_TYPE
7116 # define LONGDOUBLE_TYPE long double
7117 #endif
7118 typedef sqlite_int64 i64;          /* 8-byte signed integer */
7119 typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
7120 typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
7121 typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
7122 typedef INT16_TYPE i16;            /* 2-byte signed integer */
7123 typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
7124 typedef INT8_TYPE i8;              /* 1-byte signed integer */
7125
7126 /*
7127 ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
7128 ** that can be stored in a u32 without loss of data.  The value
7129 ** is 0x00000000ffffffff.  But because of quirks of some compilers, we
7130 ** have to specify the value in the less intuitive manner shown:
7131 */
7132 #define SQLITE_MAX_U32  ((((u64)1)<<32)-1)
7133
7134 /*
7135 ** Macros to determine whether the machine is big or little endian,
7136 ** evaluated at runtime.
7137 */
7138 #ifdef SQLITE_AMALGAMATION
7139 SQLITE_PRIVATE const int sqlite3one = 1;
7140 #else
7141 SQLITE_PRIVATE const int sqlite3one;
7142 #endif
7143 #if defined(i386) || defined(__i386__) || defined(_M_IX86)\
7144                              || defined(__x86_64) || defined(__x86_64__)
7145 # define SQLITE_BIGENDIAN    0
7146 # define SQLITE_LITTLEENDIAN 1
7147 # define SQLITE_UTF16NATIVE  SQLITE_UTF16LE
7148 #else
7149 # define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)
7150 # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
7151 # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
7152 #endif
7153
7154 /*
7155 ** Constants for the largest and smallest possible 64-bit signed integers.
7156 ** These macros are designed to work correctly on both 32-bit and 64-bit
7157 ** compilers.
7158 */
7159 #define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
7160 #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
7161
7162 /* 
7163 ** Round up a number to the next larger multiple of 8.  This is used
7164 ** to force 8-byte alignment on 64-bit architectures.
7165 */
7166 #define ROUND8(x)     (((x)+7)&~7)
7167
7168 /*
7169 ** Round down to the nearest multiple of 8
7170 */
7171 #define ROUNDDOWN8(x) ((x)&~7)
7172
7173 /*
7174 ** Assert that the pointer X is aligned to an 8-byte boundary.  This
7175 ** macro is used only within assert() to verify that the code gets
7176 ** all alignment restrictions correct.
7177 **
7178 ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
7179 ** underlying malloc() implemention might return us 4-byte aligned
7180 ** pointers.  In that case, only verify 4-byte alignment.
7181 */
7182 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
7183 # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&3)==0)
7184 #else
7185 # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&7)==0)
7186 #endif
7187
7188
7189 /*
7190 ** An instance of the following structure is used to store the busy-handler
7191 ** callback for a given sqlite handle. 
7192 **
7193 ** The sqlite.busyHandler member of the sqlite struct contains the busy
7194 ** callback for the database handle. Each pager opened via the sqlite
7195 ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
7196 ** callback is currently invoked only from within pager.c.
7197 */
7198 typedef struct BusyHandler BusyHandler;
7199 struct BusyHandler {
7200   int (*xFunc)(void *,int);  /* The busy callback */
7201   void *pArg;                /* First arg to busy callback */
7202   int nBusy;                 /* Incremented with each busy call */
7203 };
7204
7205 /*
7206 ** Name of the master database table.  The master database table
7207 ** is a special table that holds the names and attributes of all
7208 ** user tables and indices.
7209 */
7210 #define MASTER_NAME       "sqlite_master"
7211 #define TEMP_MASTER_NAME  "sqlite_temp_master"
7212
7213 /*
7214 ** The root-page of the master database table.
7215 */
7216 #define MASTER_ROOT       1
7217
7218 /*
7219 ** The name of the schema table.
7220 */
7221 #define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
7222
7223 /*
7224 ** A convenience macro that returns the number of elements in
7225 ** an array.
7226 */
7227 #define ArraySize(X)    ((int)(sizeof(X)/sizeof(X[0])))
7228
7229 /*
7230 ** The following value as a destructor means to use sqlite3DbFree().
7231 ** This is an internal extension to SQLITE_STATIC and SQLITE_TRANSIENT.
7232 */
7233 #define SQLITE_DYNAMIC   ((sqlite3_destructor_type)sqlite3DbFree)
7234
7235 /*
7236 ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
7237 ** not support Writable Static Data (WSD) such as global and static variables.
7238 ** All variables must either be on the stack or dynamically allocated from
7239 ** the heap.  When WSD is unsupported, the variable declarations scattered
7240 ** throughout the SQLite code must become constants instead.  The SQLITE_WSD
7241 ** macro is used for this purpose.  And instead of referencing the variable
7242 ** directly, we use its constant as a key to lookup the run-time allocated
7243 ** buffer that holds real variable.  The constant is also the initializer
7244 ** for the run-time allocated buffer.
7245 **
7246 ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
7247 ** macros become no-ops and have zero performance impact.
7248 */
7249 #ifdef SQLITE_OMIT_WSD
7250   #define SQLITE_WSD const
7251   #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
7252   #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
7253 SQLITE_API   int sqlite3_wsd_init(int N, int J);
7254 SQLITE_API   void *sqlite3_wsd_find(void *K, int L);
7255 #else
7256   #define SQLITE_WSD 
7257   #define GLOBAL(t,v) v
7258   #define sqlite3GlobalConfig sqlite3Config
7259 #endif
7260
7261 /*
7262 ** The following macros are used to suppress compiler warnings and to
7263 ** make it clear to human readers when a function parameter is deliberately 
7264 ** left unused within the body of a function. This usually happens when
7265 ** a function is called via a function pointer. For example the 
7266 ** implementation of an SQL aggregate step callback may not use the
7267 ** parameter indicating the number of arguments passed to the aggregate,
7268 ** if it knows that this is enforced elsewhere.
7269 **
7270 ** When a function parameter is not used at all within the body of a function,
7271 ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
7272 ** However, these macros may also be used to suppress warnings related to
7273 ** parameters that may or may not be used depending on compilation options.
7274 ** For example those parameters only used in assert() statements. In these
7275 ** cases the parameters are named as per the usual conventions.
7276 */
7277 #define UNUSED_PARAMETER(x) (void)(x)
7278 #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
7279
7280 /*
7281 ** Forward references to structures
7282 */
7283 typedef struct AggInfo AggInfo;
7284 typedef struct AuthContext AuthContext;
7285 typedef struct AutoincInfo AutoincInfo;
7286 typedef struct Bitvec Bitvec;
7287 typedef struct CollSeq CollSeq;
7288 typedef struct Column Column;
7289 typedef struct Db Db;
7290 typedef struct Schema Schema;
7291 typedef struct Expr Expr;
7292 typedef struct ExprList ExprList;
7293 typedef struct ExprSpan ExprSpan;
7294 typedef struct FKey FKey;
7295 typedef struct FuncDestructor FuncDestructor;
7296 typedef struct FuncDef FuncDef;
7297 typedef struct FuncDefHash FuncDefHash;
7298 typedef struct IdList IdList;
7299 typedef struct Index Index;
7300 typedef struct IndexSample IndexSample;
7301 typedef struct KeyClass KeyClass;
7302 typedef struct KeyInfo KeyInfo;
7303 typedef struct Lookaside Lookaside;
7304 typedef struct LookasideSlot LookasideSlot;
7305 typedef struct Module Module;
7306 typedef struct NameContext NameContext;
7307 typedef struct Parse Parse;
7308 typedef struct RowSet RowSet;
7309 typedef struct Savepoint Savepoint;
7310 typedef struct Select Select;
7311 typedef struct SrcList SrcList;
7312 typedef struct StrAccum StrAccum;
7313 typedef struct Table Table;
7314 typedef struct TableLock TableLock;
7315 typedef struct Token Token;
7316 typedef struct Trigger Trigger;
7317 typedef struct TriggerPrg TriggerPrg;
7318 typedef struct TriggerStep TriggerStep;
7319 typedef struct UnpackedRecord UnpackedRecord;
7320 typedef struct VTable VTable;
7321 typedef struct Walker Walker;
7322 typedef struct WherePlan WherePlan;
7323 typedef struct WhereInfo WhereInfo;
7324 typedef struct WhereLevel WhereLevel;
7325
7326 /*
7327 ** Defer sourcing vdbe.h and btree.h until after the "u8" and 
7328 ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
7329 ** pointer types (i.e. FuncDef) defined above.
7330 */
7331 /************** Include btree.h in the middle of sqliteInt.h *****************/
7332 /************** Begin file btree.h *******************************************/
7333 /*
7334 ** 2001 September 15
7335 **
7336 ** The author disclaims copyright to this source code.  In place of
7337 ** a legal notice, here is a blessing:
7338 **
7339 **    May you do good and not evil.
7340 **    May you find forgiveness for yourself and forgive others.
7341 **    May you share freely, never taking more than you give.
7342 **
7343 *************************************************************************
7344 ** This header file defines the interface that the sqlite B-Tree file
7345 ** subsystem.  See comments in the source code for a detailed description
7346 ** of what each interface routine does.
7347 */
7348 #ifndef _BTREE_H_
7349 #define _BTREE_H_
7350
7351 /* TODO: This definition is just included so other modules compile. It
7352 ** needs to be revisited.
7353 */
7354 #define SQLITE_N_BTREE_META 10
7355
7356 /*
7357 ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
7358 ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
7359 */
7360 #ifndef SQLITE_DEFAULT_AUTOVACUUM
7361   #define SQLITE_DEFAULT_AUTOVACUUM 0
7362 #endif
7363
7364 #define BTREE_AUTOVACUUM_NONE 0        /* Do not do auto-vacuum */
7365 #define BTREE_AUTOVACUUM_FULL 1        /* Do full auto-vacuum */
7366 #define BTREE_AUTOVACUUM_INCR 2        /* Incremental vacuum */
7367
7368 /*
7369 ** Forward declarations of structure
7370 */
7371 typedef struct Btree Btree;
7372 typedef struct BtCursor BtCursor;
7373 typedef struct BtShared BtShared;
7374 typedef struct BtreeMutexArray BtreeMutexArray;
7375
7376 /*
7377 ** This structure records all of the Btrees that need to hold
7378 ** a mutex before we enter sqlite3VdbeExec().  The Btrees are
7379 ** are placed in aBtree[] in order of aBtree[]->pBt.  That way,
7380 ** we can always lock and unlock them all quickly.
7381 */
7382 struct BtreeMutexArray {
7383   int nMutex;
7384   Btree *aBtree[SQLITE_MAX_ATTACHED+1];
7385 };
7386
7387
7388 SQLITE_PRIVATE int sqlite3BtreeOpen(
7389   const char *zFilename,   /* Name of database file to open */
7390   sqlite3 *db,             /* Associated database connection */
7391   Btree **ppBtree,         /* Return open Btree* here */
7392   int flags,               /* Flags */
7393   int vfsFlags             /* Flags passed through to VFS open */
7394 );
7395
7396 /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
7397 ** following values.
7398 **
7399 ** NOTE:  These values must match the corresponding PAGER_ values in
7400 ** pager.h.
7401 */
7402 #define BTREE_OMIT_JOURNAL  1  /* Do not create or use a rollback journal */
7403 #define BTREE_NO_READLOCK   2  /* Omit readlocks on readonly files */
7404 #define BTREE_MEMORY        4  /* This is an in-memory DB */
7405 #define BTREE_SINGLE        8  /* The file contains at most 1 b-tree */
7406 #define BTREE_UNORDERED    16  /* Use of a hash implementation is OK */
7407
7408 SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
7409 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
7410 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree*,int,int);
7411 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
7412 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
7413 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
7414 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
7415 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
7416 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
7417 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
7418 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
7419 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
7420 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
7421 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
7422 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*);
7423 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
7424 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*);
7425 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
7426 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
7427 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
7428 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
7429 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
7430 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
7431 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
7432 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
7433 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
7434
7435 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
7436 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
7437 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
7438
7439 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
7440
7441 /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
7442 ** of the flags shown below.
7443 **
7444 ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
7445 ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
7446 ** is stored in the leaves.  (BTREE_INTKEY is used for SQL tables.)  With
7447 ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
7448 ** anywhere - the key is the content.  (BTREE_BLOBKEY is used for SQL
7449 ** indices.)
7450 */
7451 #define BTREE_INTKEY     1    /* Table has only 64-bit signed integer keys */
7452 #define BTREE_BLOBKEY    2    /* Table has keys only - no data */
7453
7454 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
7455 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
7456 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int);
7457
7458 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
7459 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
7460
7461 /*
7462 ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
7463 ** should be one of the following values. The integer values are assigned 
7464 ** to constants so that the offset of the corresponding field in an
7465 ** SQLite database header may be found using the following formula:
7466 **
7467 **   offset = 36 + (idx * 4)
7468 **
7469 ** For example, the free-page-count field is located at byte offset 36 of
7470 ** the database file header. The incr-vacuum-flag field is located at
7471 ** byte offset 64 (== 36+4*7).
7472 */
7473 #define BTREE_FREE_PAGE_COUNT     0
7474 #define BTREE_SCHEMA_VERSION      1
7475 #define BTREE_FILE_FORMAT         2
7476 #define BTREE_DEFAULT_CACHE_SIZE  3
7477 #define BTREE_LARGEST_ROOT_PAGE   4
7478 #define BTREE_TEXT_ENCODING       5
7479 #define BTREE_USER_VERSION        6
7480 #define BTREE_INCR_VACUUM         7
7481
7482 SQLITE_PRIVATE int sqlite3BtreeCursor(
7483   Btree*,                              /* BTree containing table to open */
7484   int iTable,                          /* Index of root page */
7485   int wrFlag,                          /* 1 for writing.  0 for read-only */
7486   struct KeyInfo*,                     /* First argument to compare function */
7487   BtCursor *pCursor                    /* Space to write cursor structure */
7488 );
7489 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
7490 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
7491
7492 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
7493 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
7494   BtCursor*,
7495   UnpackedRecord *pUnKey,
7496   i64 intKey,
7497   int bias,
7498   int *pRes
7499 );
7500 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*);
7501 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
7502 SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
7503                                   const void *pData, int nData,
7504                                   int nZero, int bias, int seekResult);
7505 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
7506 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
7507 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
7508 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
7509 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
7510 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
7511 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
7512 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt);
7513 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt);
7514 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
7515 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
7516 SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor*, sqlite3_int64);
7517 SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor*);
7518
7519 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
7520 SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
7521
7522 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
7523 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *);
7524 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
7525
7526 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
7527
7528 #ifndef NDEBUG
7529 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
7530 #endif
7531
7532 #ifndef SQLITE_OMIT_BTREECOUNT
7533 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
7534 #endif
7535
7536 #ifdef SQLITE_TEST
7537 SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
7538 SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
7539 #endif
7540
7541 #ifndef SQLITE_OMIT_WAL
7542 SQLITE_PRIVATE   int sqlite3BtreeCheckpoint(Btree*);
7543 #endif
7544
7545 /*
7546 ** If we are not using shared cache, then there is no need to
7547 ** use mutexes to access the BtShared structures.  So make the
7548 ** Enter and Leave procedures no-ops.
7549 */
7550 #ifndef SQLITE_OMIT_SHARED_CACHE
7551 SQLITE_PRIVATE   void sqlite3BtreeEnter(Btree*);
7552 SQLITE_PRIVATE   void sqlite3BtreeEnterAll(sqlite3*);
7553 #else
7554 # define sqlite3BtreeEnter(X) 
7555 # define sqlite3BtreeEnterAll(X)
7556 #endif
7557
7558 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
7559 SQLITE_PRIVATE   void sqlite3BtreeLeave(Btree*);
7560 SQLITE_PRIVATE   void sqlite3BtreeEnterCursor(BtCursor*);
7561 SQLITE_PRIVATE   void sqlite3BtreeLeaveCursor(BtCursor*);
7562 SQLITE_PRIVATE   void sqlite3BtreeLeaveAll(sqlite3*);
7563 SQLITE_PRIVATE   void sqlite3BtreeMutexArrayEnter(BtreeMutexArray*);
7564 SQLITE_PRIVATE   void sqlite3BtreeMutexArrayLeave(BtreeMutexArray*);
7565 SQLITE_PRIVATE   void sqlite3BtreeMutexArrayInsert(BtreeMutexArray*, Btree*);
7566 #ifndef NDEBUG
7567   /* These routines are used inside assert() statements only. */
7568 SQLITE_PRIVATE   int sqlite3BtreeHoldsMutex(Btree*);
7569 SQLITE_PRIVATE   int sqlite3BtreeHoldsAllMutexes(sqlite3*);
7570 #endif
7571 #else
7572
7573 # define sqlite3BtreeLeave(X)
7574 # define sqlite3BtreeEnterCursor(X)
7575 # define sqlite3BtreeLeaveCursor(X)
7576 # define sqlite3BtreeLeaveAll(X)
7577 # define sqlite3BtreeMutexArrayEnter(X)
7578 # define sqlite3BtreeMutexArrayLeave(X)
7579 # define sqlite3BtreeMutexArrayInsert(X,Y)
7580
7581 # define sqlite3BtreeHoldsMutex(X) 1
7582 # define sqlite3BtreeHoldsAllMutexes(X) 1
7583 #endif
7584
7585
7586 #endif /* _BTREE_H_ */
7587
7588 /************** End of btree.h ***********************************************/
7589 /************** Continuing where we left off in sqliteInt.h ******************/
7590 /************** Include vdbe.h in the middle of sqliteInt.h ******************/
7591 /************** Begin file vdbe.h ********************************************/
7592 /*
7593 ** 2001 September 15
7594 **
7595 ** The author disclaims copyright to this source code.  In place of
7596 ** a legal notice, here is a blessing:
7597 **
7598 **    May you do good and not evil.
7599 **    May you find forgiveness for yourself and forgive others.
7600 **    May you share freely, never taking more than you give.
7601 **
7602 *************************************************************************
7603 ** Header file for the Virtual DataBase Engine (VDBE)
7604 **
7605 ** This header defines the interface to the virtual database engine
7606 ** or VDBE.  The VDBE implements an abstract machine that runs a
7607 ** simple program to access and modify the underlying database.
7608 */
7609 #ifndef _SQLITE_VDBE_H_
7610 #define _SQLITE_VDBE_H_
7611
7612 /*
7613 ** A single VDBE is an opaque structure named "Vdbe".  Only routines
7614 ** in the source file sqliteVdbe.c are allowed to see the insides
7615 ** of this structure.
7616 */
7617 typedef struct Vdbe Vdbe;
7618
7619 /*
7620 ** The names of the following types declared in vdbeInt.h are required
7621 ** for the VdbeOp definition.
7622 */
7623 typedef struct VdbeFunc VdbeFunc;
7624 typedef struct Mem Mem;
7625 typedef struct SubProgram SubProgram;
7626
7627 /*
7628 ** A single instruction of the virtual machine has an opcode
7629 ** and as many as three operands.  The instruction is recorded
7630 ** as an instance of the following structure:
7631 */
7632 struct VdbeOp {
7633   u8 opcode;          /* What operation to perform */
7634   signed char p4type; /* One of the P4_xxx constants for p4 */
7635   u8 opflags;         /* Mask of the OPFLG_* flags in opcodes.h */
7636   u8 p5;              /* Fifth parameter is an unsigned character */
7637   int p1;             /* First operand */
7638   int p2;             /* Second parameter (often the jump destination) */
7639   int p3;             /* The third parameter */
7640   union {             /* fourth parameter */
7641     int i;                 /* Integer value if p4type==P4_INT32 */
7642     void *p;               /* Generic pointer */
7643     char *z;               /* Pointer to data for string (char array) types */
7644     i64 *pI64;             /* Used when p4type is P4_INT64 */
7645     double *pReal;         /* Used when p4type is P4_REAL */
7646     FuncDef *pFunc;        /* Used when p4type is P4_FUNCDEF */
7647     VdbeFunc *pVdbeFunc;   /* Used when p4type is P4_VDBEFUNC */
7648     CollSeq *pColl;        /* Used when p4type is P4_COLLSEQ */
7649     Mem *pMem;             /* Used when p4type is P4_MEM */
7650     VTable *pVtab;         /* Used when p4type is P4_VTAB */
7651     KeyInfo *pKeyInfo;     /* Used when p4type is P4_KEYINFO */
7652     int *ai;               /* Used when p4type is P4_INTARRAY */
7653     SubProgram *pProgram;  /* Used when p4type is P4_SUBPROGRAM */
7654   } p4;
7655 #ifdef SQLITE_DEBUG
7656   char *zComment;          /* Comment to improve readability */
7657 #endif
7658 #ifdef VDBE_PROFILE
7659   int cnt;                 /* Number of times this instruction was executed */
7660   u64 cycles;              /* Total time spent executing this instruction */
7661 #endif
7662 };
7663 typedef struct VdbeOp VdbeOp;
7664
7665
7666 /*
7667 ** A sub-routine used to implement a trigger program.
7668 */
7669 struct SubProgram {
7670   VdbeOp *aOp;                  /* Array of opcodes for sub-program */
7671   int nOp;                      /* Elements in aOp[] */
7672   int nMem;                     /* Number of memory cells required */
7673   int nCsr;                     /* Number of cursors required */
7674   void *token;                  /* id that may be used to recursive triggers */
7675   SubProgram *pNext;            /* Next sub-program already visited */
7676 };
7677
7678 /*
7679 ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
7680 ** it takes up less space.
7681 */
7682 struct VdbeOpList {
7683   u8 opcode;          /* What operation to perform */
7684   signed char p1;     /* First operand */
7685   signed char p2;     /* Second parameter (often the jump destination) */
7686   signed char p3;     /* Third parameter */
7687 };
7688 typedef struct VdbeOpList VdbeOpList;
7689
7690 /*
7691 ** Allowed values of VdbeOp.p4type
7692 */
7693 #define P4_NOTUSED    0   /* The P4 parameter is not used */
7694 #define P4_DYNAMIC  (-1)  /* Pointer to a string obtained from sqliteMalloc() */
7695 #define P4_STATIC   (-2)  /* Pointer to a static string */
7696 #define P4_COLLSEQ  (-4)  /* P4 is a pointer to a CollSeq structure */
7697 #define P4_FUNCDEF  (-5)  /* P4 is a pointer to a FuncDef structure */
7698 #define P4_KEYINFO  (-6)  /* P4 is a pointer to a KeyInfo structure */
7699 #define P4_VDBEFUNC (-7)  /* P4 is a pointer to a VdbeFunc structure */
7700 #define P4_MEM      (-8)  /* P4 is a pointer to a Mem*    structure */
7701 #define P4_TRANSIENT (-9) /* P4 is a pointer to a transient string */
7702 #define P4_VTAB     (-10) /* P4 is a pointer to an sqlite3_vtab structure */
7703 #define P4_MPRINTF  (-11) /* P4 is a string obtained from sqlite3_mprintf() */
7704 #define P4_REAL     (-12) /* P4 is a 64-bit floating point value */
7705 #define P4_INT64    (-13) /* P4 is a 64-bit signed integer */
7706 #define P4_INT32    (-14) /* P4 is a 32-bit signed integer */
7707 #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
7708 #define P4_SUBPROGRAM  (-18) /* P4 is a pointer to a SubProgram structure */
7709
7710 /* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure
7711 ** is made.  That copy is freed when the Vdbe is finalized.  But if the
7712 ** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used.  It still
7713 ** gets freed when the Vdbe is finalized so it still should be obtained
7714 ** from a single sqliteMalloc().  But no copy is made and the calling
7715 ** function should *not* try to free the KeyInfo.
7716 */
7717 #define P4_KEYINFO_HANDOFF (-16)
7718 #define P4_KEYINFO_STATIC  (-17)
7719
7720 /*
7721 ** The Vdbe.aColName array contains 5n Mem structures, where n is the 
7722 ** number of columns of data returned by the statement.
7723 */
7724 #define COLNAME_NAME     0
7725 #define COLNAME_DECLTYPE 1
7726 #define COLNAME_DATABASE 2
7727 #define COLNAME_TABLE    3
7728 #define COLNAME_COLUMN   4
7729 #ifdef SQLITE_ENABLE_COLUMN_METADATA
7730 # define COLNAME_N        5      /* Number of COLNAME_xxx symbols */
7731 #else
7732 # ifdef SQLITE_OMIT_DECLTYPE
7733 #   define COLNAME_N      1      /* Store only the name */
7734 # else
7735 #   define COLNAME_N      2      /* Store the name and decltype */
7736 # endif
7737 #endif
7738
7739 /*
7740 ** The following macro converts a relative address in the p2 field
7741 ** of a VdbeOp structure into a negative number so that 
7742 ** sqlite3VdbeAddOpList() knows that the address is relative.  Calling
7743 ** the macro again restores the address.
7744 */
7745 #define ADDR(X)  (-1-(X))
7746
7747 /*
7748 ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
7749 ** header file that defines a number for each opcode used by the VDBE.
7750 */
7751 /************** Include opcodes.h in the middle of vdbe.h ********************/
7752 /************** Begin file opcodes.h *****************************************/
7753 /* Automatically generated.  Do not edit */
7754 /* See the mkopcodeh.awk script for details */
7755 #define OP_Goto                                 1
7756 #define OP_Gosub                                2
7757 #define OP_Return                               3
7758 #define OP_Yield                                4
7759 #define OP_HaltIfNull                           5
7760 #define OP_Halt                                 6
7761 #define OP_Integer                              7
7762 #define OP_Int64                                8
7763 #define OP_Real                               130   /* same as TK_FLOAT    */
7764 #define OP_String8                             94   /* same as TK_STRING   */
7765 #define OP_String                               9
7766 #define OP_Null                                10
7767 #define OP_Blob                                11
7768 #define OP_Variable                            12
7769 #define OP_Move                                13
7770 #define OP_Copy                                14
7771 #define OP_SCopy                               15
7772 #define OP_ResultRow                           16
7773 #define OP_Concat                              91   /* same as TK_CONCAT   */
7774 #define OP_Add                                 86   /* same as TK_PLUS     */
7775 #define OP_Subtract                            87   /* same as TK_MINUS    */
7776 #define OP_Multiply                            88   /* same as TK_STAR     */
7777 #define OP_Divide                              89   /* same as TK_SLASH    */
7778 #define OP_Remainder                           90   /* same as TK_REM      */
7779 #define OP_CollSeq                             17
7780 #define OP_Function                            18
7781 #define OP_BitAnd                              82   /* same as TK_BITAND   */
7782 #define OP_BitOr                               83   /* same as TK_BITOR    */
7783 #define OP_ShiftLeft                           84   /* same as TK_LSHIFT   */
7784 #define OP_ShiftRight                          85   /* same as TK_RSHIFT   */
7785 #define OP_AddImm                              20
7786 #define OP_MustBeInt                           21
7787 #define OP_RealAffinity                        22
7788 #define OP_ToText                             141   /* same as TK_TO_TEXT  */
7789 #define OP_ToBlob                             142   /* same as TK_TO_BLOB  */
7790 #define OP_ToNumeric                          143   /* same as TK_TO_NUMERIC*/
7791 #define OP_ToInt                              144   /* same as TK_TO_INT   */
7792 #define OP_ToReal                             145   /* same as TK_TO_REAL  */
7793 #define OP_Eq                                  76   /* same as TK_EQ       */
7794 #define OP_Ne                                  75   /* same as TK_NE       */
7795 #define OP_Lt                                  79   /* same as TK_LT       */
7796 #define OP_Le                                  78   /* same as TK_LE       */
7797 #define OP_Gt                                  77   /* same as TK_GT       */
7798 #define OP_Ge                                  80   /* same as TK_GE       */
7799 #define OP_Permutation                         23
7800 #define OP_Compare                             24
7801 #define OP_Jump                                25
7802 #define OP_And                                 69   /* same as TK_AND      */
7803 #define OP_Or                                  68   /* same as TK_OR       */
7804 #define OP_Not                                 19   /* same as TK_NOT      */
7805 #define OP_BitNot                              93   /* same as TK_BITNOT   */
7806 #define OP_If                                  26
7807 #define OP_IfNot                               27
7808 #define OP_IsNull                              73   /* same as TK_ISNULL   */
7809 #define OP_NotNull                             74   /* same as TK_NOTNULL  */
7810 #define OP_Column                              28
7811 #define OP_Affinity                            29
7812 #define OP_MakeRecord                          30
7813 #define OP_Count                               31
7814 #define OP_Savepoint                           32
7815 #define OP_AutoCommit                          33
7816 #define OP_Transaction                         34
7817 #define OP_ReadCookie                          35
7818 #define OP_SetCookie                           36
7819 #define OP_VerifyCookie                        37
7820 #define OP_OpenRead                            38
7821 #define OP_OpenWrite                           39
7822 #define OP_OpenAutoindex                       40
7823 #define OP_OpenEphemeral                       41
7824 #define OP_OpenPseudo                          42
7825 #define OP_Close                               43
7826 #define OP_SeekLt                              44
7827 #define OP_SeekLe                              45
7828 #define OP_SeekGe                              46
7829 #define OP_SeekGt                              47
7830 #define OP_Seek                                48
7831 #define OP_NotFound                            49
7832 #define OP_Found                               50
7833 #define OP_IsUnique                            51
7834 #define OP_NotExists                           52
7835 #define OP_Sequence                            53
7836 #define OP_NewRowid                            54
7837 #define OP_Insert                              55
7838 #define OP_InsertInt                           56
7839 #define OP_Delete                              57
7840 #define OP_ResetCount                          58
7841 #define OP_RowKey                              59
7842 #define OP_RowData                             60
7843 #define OP_Rowid                               61
7844 #define OP_NullRow                             62
7845 #define OP_Last                                63
7846 #define OP_Sort                                64
7847 #define OP_Rewind                              65
7848 #define OP_Prev                                66
7849 #define OP_Next                                67
7850 #define OP_IdxInsert                           70
7851 #define OP_IdxDelete                           71
7852 #define OP_IdxRowid                            72
7853 #define OP_IdxLT                               81
7854 #define OP_IdxGE                               92
7855 #define OP_Destroy                             95
7856 #define OP_Clear                               96
7857 #define OP_CreateIndex                         97
7858 #define OP_CreateTable                         98
7859 #define OP_ParseSchema                         99
7860 #define OP_LoadAnalysis                       100
7861 #define OP_DropTable                          101
7862 #define OP_DropIndex                          102
7863 #define OP_DropTrigger                        103
7864 #define OP_IntegrityCk                        104
7865 #define OP_RowSetAdd                          105
7866 #define OP_RowSetRead                         106
7867 #define OP_RowSetTest                         107
7868 #define OP_Program                            108
7869 #define OP_Param                              109
7870 #define OP_FkCounter                          110
7871 #define OP_FkIfZero                           111
7872 #define OP_MemMax                             112
7873 #define OP_IfPos                              113
7874 #define OP_IfNeg                              114
7875 #define OP_IfZero                             115
7876 #define OP_AggStep                            116
7877 #define OP_AggFinal                           117
7878 #define OP_Checkpoint                         118
7879 #define OP_JournalMode                        119
7880 #define OP_Vacuum                             120
7881 #define OP_IncrVacuum                         121
7882 #define OP_Expire                             122
7883 #define OP_TableLock                          123
7884 #define OP_VBegin                             124
7885 #define OP_VCreate                            125
7886 #define OP_VDestroy                           126
7887 #define OP_VOpen                              127
7888 #define OP_VFilter                            128
7889 #define OP_VColumn                            129
7890 #define OP_VNext                              131
7891 #define OP_VRename                            132
7892 #define OP_VUpdate                            133
7893 #define OP_Pagecount                          134
7894 #define OP_Trace                              135
7895 #define OP_Noop                               136
7896 #define OP_Explain                            137
7897
7898 /* The following opcode values are never used */
7899 #define OP_NotUsed_138                        138
7900 #define OP_NotUsed_139                        139
7901 #define OP_NotUsed_140                        140
7902
7903
7904 /* Properties such as "out2" or "jump" that are specified in
7905 ** comments following the "case" for each opcode in the vdbe.c
7906 ** are encoded into bitvectors as follows:
7907 */
7908 #define OPFLG_JUMP            0x0001  /* jump:  P2 holds jmp target */
7909 #define OPFLG_OUT2_PRERELEASE 0x0002  /* out2-prerelease: */
7910 #define OPFLG_IN1             0x0004  /* in1:   P1 is an input */
7911 #define OPFLG_IN2             0x0008  /* in2:   P2 is an input */
7912 #define OPFLG_IN3             0x0010  /* in3:   P3 is an input */
7913 #define OPFLG_OUT2            0x0020  /* out2:  P2 is an output */
7914 #define OPFLG_OUT3            0x0040  /* out3:  P3 is an output */
7915 #define OPFLG_INITIALIZER {\
7916 /*   0 */ 0x00, 0x01, 0x05, 0x04, 0x04, 0x10, 0x00, 0x02,\
7917 /*   8 */ 0x02, 0x02, 0x02, 0x02, 0x02, 0x00, 0x24, 0x24,\
7918 /*  16 */ 0x00, 0x00, 0x00, 0x24, 0x04, 0x05, 0x04, 0x00,\
7919 /*  24 */ 0x00, 0x01, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02,\
7920 /*  32 */ 0x00, 0x00, 0x00, 0x02, 0x10, 0x00, 0x00, 0x00,\
7921 /*  40 */ 0x00, 0x00, 0x00, 0x00, 0x11, 0x11, 0x11, 0x11,\
7922 /*  48 */ 0x08, 0x11, 0x11, 0x11, 0x11, 0x02, 0x02, 0x00,\
7923 /*  56 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01,\
7924 /*  64 */ 0x01, 0x01, 0x01, 0x01, 0x4c, 0x4c, 0x08, 0x00,\
7925 /*  72 */ 0x02, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15, 0x15,\
7926 /*  80 */ 0x15, 0x01, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c,\
7927 /*  88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x01, 0x24, 0x02, 0x02,\
7928 /*  96 */ 0x00, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,\
7929 /* 104 */ 0x00, 0x0c, 0x45, 0x15, 0x01, 0x02, 0x00, 0x01,\
7930 /* 112 */ 0x08, 0x05, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02,\
7931 /* 120 */ 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
7932 /* 128 */ 0x01, 0x00, 0x02, 0x01, 0x00, 0x00, 0x02, 0x00,\
7933 /* 136 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x04, 0x04,\
7934 /* 144 */ 0x04, 0x04,}
7935
7936 /************** End of opcodes.h *********************************************/
7937 /************** Continuing where we left off in vdbe.h ***********************/
7938
7939 /*
7940 ** Prototypes for the VDBE interface.  See comments on the implementation
7941 ** for a description of what each of these routines does.
7942 */
7943 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*);
7944 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
7945 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
7946 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
7947 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
7948 SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
7949 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
7950 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
7951 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, int addr, int P1);
7952 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, int addr, int P2);
7953 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, int addr, int P3);
7954 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
7955 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
7956 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr, int N);
7957 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
7958 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
7959 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
7960 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
7961 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
7962 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
7963 SQLITE_PRIVATE void sqlite3VdbeDeleteObject(sqlite3*,Vdbe*);
7964 SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,int,int,int,int,int,int);
7965 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
7966 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
7967 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
7968 #ifdef SQLITE_DEBUG
7969 SQLITE_PRIVATE   int sqlite3VdbeAssertMayAbort(Vdbe *, int);
7970 SQLITE_PRIVATE   void sqlite3VdbeTrace(Vdbe*,FILE*);
7971 #endif
7972 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
7973 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
7974 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
7975 SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
7976 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
7977 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
7978 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
7979 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
7980 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
7981 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe*, int, u8);
7982 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
7983 #ifndef SQLITE_OMIT_TRACE
7984 SQLITE_PRIVATE   char *sqlite3VdbeExpandSql(Vdbe*, const char*);
7985 #endif
7986
7987 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,char*,int);
7988 SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord*);
7989 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
7990
7991 #ifndef SQLITE_OMIT_TRIGGER
7992 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
7993 #endif
7994
7995
7996 #ifndef NDEBUG
7997 SQLITE_PRIVATE   void sqlite3VdbeComment(Vdbe*, const char*, ...);
7998 # define VdbeComment(X)  sqlite3VdbeComment X
7999 SQLITE_PRIVATE   void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
8000 # define VdbeNoopComment(X)  sqlite3VdbeNoopComment X
8001 #else
8002 # define VdbeComment(X)
8003 # define VdbeNoopComment(X)
8004 #endif
8005
8006 #endif
8007
8008 /************** End of vdbe.h ************************************************/
8009 /************** Continuing where we left off in sqliteInt.h ******************/
8010 /************** Include pager.h in the middle of sqliteInt.h *****************/
8011 /************** Begin file pager.h *******************************************/
8012 /*
8013 ** 2001 September 15
8014 **
8015 ** The author disclaims copyright to this source code.  In place of
8016 ** a legal notice, here is a blessing:
8017 **
8018 **    May you do good and not evil.
8019 **    May you find forgiveness for yourself and forgive others.
8020 **    May you share freely, never taking more than you give.
8021 **
8022 *************************************************************************
8023 ** This header file defines the interface that the sqlite page cache
8024 ** subsystem.  The page cache subsystem reads and writes a file a page
8025 ** at a time and provides a journal for rollback.
8026 */
8027
8028 #ifndef _PAGER_H_
8029 #define _PAGER_H_
8030
8031 /*
8032 ** Default maximum size for persistent journal files. A negative 
8033 ** value means no limit. This value may be overridden using the 
8034 ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
8035 */
8036 #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
8037   #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
8038 #endif
8039
8040 /*
8041 ** The type used to represent a page number.  The first page in a file
8042 ** is called page 1.  0 is used to represent "not a page".
8043 */
8044 typedef u32 Pgno;
8045
8046 /*
8047 ** Each open file is managed by a separate instance of the "Pager" structure.
8048 */
8049 typedef struct Pager Pager;
8050
8051 /*
8052 ** Handle type for pages.
8053 */
8054 typedef struct PgHdr DbPage;
8055
8056 /*
8057 ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
8058 ** reserved for working around a windows/posix incompatibility). It is
8059 ** used in the journal to signify that the remainder of the journal file 
8060 ** is devoted to storing a master journal name - there are no more pages to
8061 ** roll back. See comments for function writeMasterJournal() in pager.c 
8062 ** for details.
8063 */
8064 #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
8065
8066 /*
8067 ** Allowed values for the flags parameter to sqlite3PagerOpen().
8068 **
8069 ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
8070 */
8071 #define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */
8072 #define PAGER_NO_READLOCK   0x0002    /* Omit readlocks on readonly files */
8073 #define PAGER_MEMORY        0x0004    /* In-memory database */
8074
8075 /*
8076 ** Valid values for the second argument to sqlite3PagerLockingMode().
8077 */
8078 #define PAGER_LOCKINGMODE_QUERY      -1
8079 #define PAGER_LOCKINGMODE_NORMAL      0
8080 #define PAGER_LOCKINGMODE_EXCLUSIVE   1
8081
8082 /*
8083 ** Numeric constants that encode the journalmode.  
8084 */
8085 #define PAGER_JOURNALMODE_QUERY     (-1)  /* Query the value of journalmode */
8086 #define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */
8087 #define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */
8088 #define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */
8089 #define PAGER_JOURNALMODE_TRUNCATE    3   /* Commit by truncating journal */
8090 #define PAGER_JOURNALMODE_MEMORY      4   /* In-memory journal file */
8091 #define PAGER_JOURNALMODE_WAL         5   /* Use write-ahead logging */
8092
8093 /*
8094 ** The remainder of this file contains the declarations of the functions
8095 ** that make up the Pager sub-system API. See source code comments for 
8096 ** a detailed description of each routine.
8097 */
8098
8099 /* Open and close a Pager connection. */ 
8100 SQLITE_PRIVATE int sqlite3PagerOpen(
8101   sqlite3_vfs*,
8102   Pager **ppPager,
8103   const char*,
8104   int,
8105   int,
8106   int,
8107   void(*)(DbPage*)
8108 );
8109 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
8110 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
8111
8112 /* Functions used to configure a Pager object. */
8113 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
8114 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
8115 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
8116 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
8117 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager*,int,int);
8118 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
8119 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
8120 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
8121 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
8122 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
8123 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
8124
8125 /* Functions used to obtain and release page references. */ 
8126 SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
8127 #define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
8128 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
8129 SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
8130 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
8131
8132 /* Operations on page references. */
8133 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
8134 SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
8135 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
8136 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
8137 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *); 
8138 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *); 
8139
8140 /* Functions used to manage pager transactions and savepoints. */
8141 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
8142 SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
8143 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
8144 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
8145 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager);
8146 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
8147 SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
8148 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
8149 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
8150 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
8151
8152 SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager);
8153 SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager);
8154 SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager);
8155 SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
8156 SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager);
8157
8158 /* Functions used to query pager state and configuration. */
8159 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
8160 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
8161 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
8162 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*);
8163 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
8164 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
8165 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
8166 SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
8167 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
8168 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
8169
8170 /* Functions used to truncate the database file. */
8171 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
8172
8173 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
8174 SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
8175 #endif
8176
8177 /* Functions to support testing and debugging. */
8178 #if !defined(NDEBUG) || defined(SQLITE_TEST)
8179 SQLITE_PRIVATE   Pgno sqlite3PagerPagenumber(DbPage*);
8180 SQLITE_PRIVATE   int sqlite3PagerIswriteable(DbPage*);
8181 #endif
8182 #ifdef SQLITE_TEST
8183 SQLITE_PRIVATE   int *sqlite3PagerStats(Pager*);
8184 SQLITE_PRIVATE   void sqlite3PagerRefdump(Pager*);
8185   void disable_simulated_io_errors(void);
8186   void enable_simulated_io_errors(void);
8187 #else
8188 # define disable_simulated_io_errors()
8189 # define enable_simulated_io_errors()
8190 #endif
8191
8192 #endif /* _PAGER_H_ */
8193
8194 /************** End of pager.h ***********************************************/
8195 /************** Continuing where we left off in sqliteInt.h ******************/
8196 /************** Include pcache.h in the middle of sqliteInt.h ****************/
8197 /************** Begin file pcache.h ******************************************/
8198 /*
8199 ** 2008 August 05
8200 **
8201 ** The author disclaims copyright to this source code.  In place of
8202 ** a legal notice, here is a blessing:
8203 **
8204 **    May you do good and not evil.
8205 **    May you find forgiveness for yourself and forgive others.
8206 **    May you share freely, never taking more than you give.
8207 **
8208 *************************************************************************
8209 ** This header file defines the interface that the sqlite page cache
8210 ** subsystem. 
8211 */
8212
8213 #ifndef _PCACHE_H_
8214
8215 typedef struct PgHdr PgHdr;
8216 typedef struct PCache PCache;
8217
8218 /*
8219 ** Every page in the cache is controlled by an instance of the following
8220 ** structure.
8221 */
8222 struct PgHdr {
8223   void *pData;                   /* Content of this page */
8224   void *pExtra;                  /* Extra content */
8225   PgHdr *pDirty;                 /* Transient list of dirty pages */
8226   Pgno pgno;                     /* Page number for this page */
8227   Pager *pPager;                 /* The pager this page is part of */
8228 #ifdef SQLITE_CHECK_PAGES
8229   u32 pageHash;                  /* Hash of page content */
8230 #endif
8231   u16 flags;                     /* PGHDR flags defined below */
8232
8233   /**********************************************************************
8234   ** Elements above are public.  All that follows is private to pcache.c
8235   ** and should not be accessed by other modules.
8236   */
8237   i16 nRef;                      /* Number of users of this page */
8238   PCache *pCache;                /* Cache that owns this page */
8239
8240   PgHdr *pDirtyNext;             /* Next element in list of dirty pages */
8241   PgHdr *pDirtyPrev;             /* Previous element in list of dirty pages */
8242 };
8243
8244 /* Bit values for PgHdr.flags */
8245 #define PGHDR_DIRTY             0x002  /* Page has changed */
8246 #define PGHDR_NEED_SYNC         0x004  /* Fsync the rollback journal before
8247                                        ** writing this page to the database */
8248 #define PGHDR_NEED_READ         0x008  /* Content is unread */
8249 #define PGHDR_REUSE_UNLIKELY    0x010  /* A hint that reuse is unlikely */
8250 #define PGHDR_DONT_WRITE        0x020  /* Do not write content to disk */
8251
8252 /* Initialize and shutdown the page cache subsystem */
8253 SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
8254 SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
8255
8256 /* Page cache buffer management:
8257 ** These routines implement SQLITE_CONFIG_PAGECACHE.
8258 */
8259 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
8260
8261 /* Create a new pager cache.
8262 ** Under memory stress, invoke xStress to try to make pages clean.
8263 ** Only clean and unpinned pages can be reclaimed.
8264 */
8265 SQLITE_PRIVATE void sqlite3PcacheOpen(
8266   int szPage,                    /* Size of every page */
8267   int szExtra,                   /* Extra space associated with each page */
8268   int bPurgeable,                /* True if pages are on backing store */
8269   int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
8270   void *pStress,                 /* Argument to xStress */
8271   PCache *pToInit                /* Preallocated space for the PCache */
8272 );
8273
8274 /* Modify the page-size after the cache has been created. */
8275 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *, int);
8276
8277 /* Return the size in bytes of a PCache object.  Used to preallocate
8278 ** storage space.
8279 */
8280 SQLITE_PRIVATE int sqlite3PcacheSize(void);
8281
8282 /* One release per successful fetch.  Page is pinned until released.
8283 ** Reference counted. 
8284 */
8285 SQLITE_PRIVATE int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**);
8286 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
8287
8288 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*);         /* Remove page from cache */
8289 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*);    /* Make sure page is marked dirty */
8290 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*);    /* Mark a single page as clean */
8291 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*);    /* Mark all dirty list pages as clean */
8292
8293 /* Change a page number.  Used by incr-vacuum. */
8294 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
8295
8296 /* Remove all pages with pgno>x.  Reset the cache if x==0 */
8297 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
8298
8299 /* Get a list of all dirty pages in the cache, sorted by page number */
8300 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
8301
8302 /* Reset and close the cache object */
8303 SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
8304
8305 /* Clear flags from pages of the page cache */
8306 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
8307
8308 /* Discard the contents of the cache */
8309 SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
8310
8311 /* Return the total number of outstanding page references */
8312 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
8313
8314 /* Increment the reference count of an existing page */
8315 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
8316
8317 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
8318
8319 /* Return the total number of pages stored in the cache */
8320 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
8321
8322 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
8323 /* Iterate through all dirty pages currently stored in the cache. This
8324 ** interface is only available if SQLITE_CHECK_PAGES is defined when the 
8325 ** library is built.
8326 */
8327 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
8328 #endif
8329
8330 /* Set and get the suggested cache-size for the specified pager-cache.
8331 **
8332 ** If no global maximum is configured, then the system attempts to limit
8333 ** the total number of pages cached by purgeable pager-caches to the sum
8334 ** of the suggested cache-sizes.
8335 */
8336 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
8337 #ifdef SQLITE_TEST
8338 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
8339 #endif
8340
8341 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
8342 /* Try to return memory used by the pcache module to the main memory heap */
8343 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
8344 #endif
8345
8346 #ifdef SQLITE_TEST
8347 SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
8348 #endif
8349
8350 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
8351
8352 #endif /* _PCACHE_H_ */
8353
8354 /************** End of pcache.h **********************************************/
8355 /************** Continuing where we left off in sqliteInt.h ******************/
8356
8357 /************** Include os.h in the middle of sqliteInt.h ********************/
8358 /************** Begin file os.h **********************************************/
8359 /*
8360 ** 2001 September 16
8361 **
8362 ** The author disclaims copyright to this source code.  In place of
8363 ** a legal notice, here is a blessing:
8364 **
8365 **    May you do good and not evil.
8366 **    May you find forgiveness for yourself and forgive others.
8367 **    May you share freely, never taking more than you give.
8368 **
8369 ******************************************************************************
8370 **
8371 ** This header file (together with is companion C source-code file
8372 ** "os.c") attempt to abstract the underlying operating system so that
8373 ** the SQLite library will work on both POSIX and windows systems.
8374 **
8375 ** This header file is #include-ed by sqliteInt.h and thus ends up
8376 ** being included by every source file.
8377 */
8378 #ifndef _SQLITE_OS_H_
8379 #define _SQLITE_OS_H_
8380
8381 /*
8382 ** Figure out if we are dealing with Unix, Windows, or some other
8383 ** operating system.  After the following block of preprocess macros,
8384 ** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, SQLITE_OS_OS2, and SQLITE_OS_OTHER 
8385 ** will defined to either 1 or 0.  One of the four will be 1.  The other 
8386 ** three will be 0.
8387 */
8388 #if defined(SQLITE_OS_OTHER)
8389 # if SQLITE_OS_OTHER==1
8390 #   undef SQLITE_OS_UNIX
8391 #   define SQLITE_OS_UNIX 0
8392 #   undef SQLITE_OS_WIN
8393 #   define SQLITE_OS_WIN 0
8394 #   undef SQLITE_OS_OS2
8395 #   define SQLITE_OS_OS2 0
8396 # else
8397 #   undef SQLITE_OS_OTHER
8398 # endif
8399 #endif
8400 #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
8401 # define SQLITE_OS_OTHER 0
8402 # ifndef SQLITE_OS_WIN
8403 #   if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
8404 #     define SQLITE_OS_WIN 1
8405 #     define SQLITE_OS_UNIX 0
8406 #     define SQLITE_OS_OS2 0
8407 #   elif defined(__EMX__) || defined(_OS2) || defined(OS2) || defined(_OS2_) || defined(__OS2__)
8408 #     define SQLITE_OS_WIN 0
8409 #     define SQLITE_OS_UNIX 0
8410 #     define SQLITE_OS_OS2 1
8411 #   else
8412 #     define SQLITE_OS_WIN 0
8413 #     define SQLITE_OS_UNIX 1
8414 #     define SQLITE_OS_OS2 0
8415 #  endif
8416 # else
8417 #  define SQLITE_OS_UNIX 0
8418 #  define SQLITE_OS_OS2 0
8419 # endif
8420 #else
8421 # ifndef SQLITE_OS_WIN
8422 #  define SQLITE_OS_WIN 0
8423 # endif
8424 #endif
8425
8426 /*
8427 ** Determine if we are dealing with WindowsCE - which has a much
8428 ** reduced API.
8429 */
8430 #if defined(_WIN32_WCE)
8431 # define SQLITE_OS_WINCE 1
8432 #else
8433 # define SQLITE_OS_WINCE 0
8434 #endif
8435
8436
8437 /*
8438 ** Define the maximum size of a temporary filename
8439 */
8440 #if SQLITE_OS_WIN
8441 # include <windows.h>
8442 # define SQLITE_TEMPNAME_SIZE (MAX_PATH+50)
8443 #elif SQLITE_OS_OS2
8444 # if (__GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ >= 3) && defined(OS2_HIGH_MEMORY)
8445 #  include <os2safe.h> /* has to be included before os2.h for linking to work */
8446 # endif
8447 # define INCL_DOSDATETIME
8448 # define INCL_DOSFILEMGR
8449 # define INCL_DOSERRORS
8450 # define INCL_DOSMISC
8451 # define INCL_DOSPROCESS
8452 # define INCL_DOSMODULEMGR
8453 # define INCL_DOSSEMAPHORES
8454 # include <os2.h>
8455 # include <uconv.h>
8456 # define SQLITE_TEMPNAME_SIZE (CCHMAXPATHCOMP)
8457 #else
8458 # define SQLITE_TEMPNAME_SIZE 200
8459 #endif
8460
8461 /* If the SET_FULLSYNC macro is not defined above, then make it
8462 ** a no-op
8463 */
8464 #ifndef SET_FULLSYNC
8465 # define SET_FULLSYNC(x,y)
8466 #endif
8467
8468 /*
8469 ** The default size of a disk sector
8470 */
8471 #ifndef SQLITE_DEFAULT_SECTOR_SIZE
8472 # define SQLITE_DEFAULT_SECTOR_SIZE 512
8473 #endif
8474
8475 /*
8476 ** Temporary files are named starting with this prefix followed by 16 random
8477 ** alphanumeric characters, and no file extension. They are stored in the
8478 ** OS's standard temporary file directory, and are deleted prior to exit.
8479 ** If sqlite is being embedded in another program, you may wish to change the
8480 ** prefix to reflect your program's name, so that if your program exits
8481 ** prematurely, old temporary files can be easily identified. This can be done
8482 ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
8483 **
8484 ** 2006-10-31:  The default prefix used to be "sqlite_".  But then
8485 ** Mcafee started using SQLite in their anti-virus product and it
8486 ** started putting files with the "sqlite" name in the c:/temp folder.
8487 ** This annoyed many windows users.  Those users would then do a 
8488 ** Google search for "sqlite", find the telephone numbers of the
8489 ** developers and call to wake them up at night and complain.
8490 ** For this reason, the default name prefix is changed to be "sqlite" 
8491 ** spelled backwards.  So the temp files are still identified, but
8492 ** anybody smart enough to figure out the code is also likely smart
8493 ** enough to know that calling the developer will not help get rid
8494 ** of the file.
8495 */
8496 #ifndef SQLITE_TEMP_FILE_PREFIX
8497 # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
8498 #endif
8499
8500 /*
8501 ** The following values may be passed as the second argument to
8502 ** sqlite3OsLock(). The various locks exhibit the following semantics:
8503 **
8504 ** SHARED:    Any number of processes may hold a SHARED lock simultaneously.
8505 ** RESERVED:  A single process may hold a RESERVED lock on a file at
8506 **            any time. Other processes may hold and obtain new SHARED locks.
8507 ** PENDING:   A single process may hold a PENDING lock on a file at
8508 **            any one time. Existing SHARED locks may persist, but no new
8509 **            SHARED locks may be obtained by other processes.
8510 ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
8511 **
8512 ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
8513 ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
8514 ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
8515 ** sqlite3OsLock().
8516 */
8517 #define NO_LOCK         0
8518 #define SHARED_LOCK     1
8519 #define RESERVED_LOCK   2
8520 #define PENDING_LOCK    3
8521 #define EXCLUSIVE_LOCK  4
8522
8523 /*
8524 ** File Locking Notes:  (Mostly about windows but also some info for Unix)
8525 **
8526 ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
8527 ** those functions are not available.  So we use only LockFile() and
8528 ** UnlockFile().
8529 **
8530 ** LockFile() prevents not just writing but also reading by other processes.
8531 ** A SHARED_LOCK is obtained by locking a single randomly-chosen 
8532 ** byte out of a specific range of bytes. The lock byte is obtained at 
8533 ** random so two separate readers can probably access the file at the 
8534 ** same time, unless they are unlucky and choose the same lock byte.
8535 ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
8536 ** There can only be one writer.  A RESERVED_LOCK is obtained by locking
8537 ** a single byte of the file that is designated as the reserved lock byte.
8538 ** A PENDING_LOCK is obtained by locking a designated byte different from
8539 ** the RESERVED_LOCK byte.
8540 **
8541 ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
8542 ** which means we can use reader/writer locks.  When reader/writer locks
8543 ** are used, the lock is placed on the same range of bytes that is used
8544 ** for probabilistic locking in Win95/98/ME.  Hence, the locking scheme
8545 ** will support two or more Win95 readers or two or more WinNT readers.
8546 ** But a single Win95 reader will lock out all WinNT readers and a single
8547 ** WinNT reader will lock out all other Win95 readers.
8548 **
8549 ** The following #defines specify the range of bytes used for locking.
8550 ** SHARED_SIZE is the number of bytes available in the pool from which
8551 ** a random byte is selected for a shared lock.  The pool of bytes for
8552 ** shared locks begins at SHARED_FIRST. 
8553 **
8554 ** The same locking strategy and
8555 ** byte ranges are used for Unix.  This leaves open the possiblity of having
8556 ** clients on win95, winNT, and unix all talking to the same shared file
8557 ** and all locking correctly.  To do so would require that samba (or whatever
8558 ** tool is being used for file sharing) implements locks correctly between
8559 ** windows and unix.  I'm guessing that isn't likely to happen, but by
8560 ** using the same locking range we are at least open to the possibility.
8561 **
8562 ** Locking in windows is manditory.  For this reason, we cannot store
8563 ** actual data in the bytes used for locking.  The pager never allocates
8564 ** the pages involved in locking therefore.  SHARED_SIZE is selected so
8565 ** that all locks will fit on a single page even at the minimum page size.
8566 ** PENDING_BYTE defines the beginning of the locks.  By default PENDING_BYTE
8567 ** is set high so that we don't have to allocate an unused page except
8568 ** for very large databases.  But one should test the page skipping logic 
8569 ** by setting PENDING_BYTE low and running the entire regression suite.
8570 **
8571 ** Changing the value of PENDING_BYTE results in a subtly incompatible
8572 ** file format.  Depending on how it is changed, you might not notice
8573 ** the incompatibility right away, even running a full regression test.
8574 ** The default location of PENDING_BYTE is the first byte past the
8575 ** 1GB boundary.
8576 **
8577 */
8578 #ifdef SQLITE_OMIT_WSD
8579 # define PENDING_BYTE     (0x40000000)
8580 #else
8581 # define PENDING_BYTE      sqlite3PendingByte
8582 #endif
8583 #define RESERVED_BYTE     (PENDING_BYTE+1)
8584 #define SHARED_FIRST      (PENDING_BYTE+2)
8585 #define SHARED_SIZE       510
8586
8587 /*
8588 ** Wrapper around OS specific sqlite3_os_init() function.
8589 */
8590 SQLITE_PRIVATE int sqlite3OsInit(void);
8591
8592 /* 
8593 ** Functions for accessing sqlite3_file methods 
8594 */
8595 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
8596 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
8597 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
8598 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
8599 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
8600 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
8601 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
8602 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
8603 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
8604 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
8605 #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
8606 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
8607 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
8608 SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
8609 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
8610 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
8611 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
8612
8613 /* 
8614 ** Functions for accessing sqlite3_vfs methods 
8615 */
8616 SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
8617 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
8618 SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
8619 SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
8620 #ifndef SQLITE_OMIT_LOAD_EXTENSION
8621 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
8622 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
8623 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
8624 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
8625 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
8626 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
8627 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
8628 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
8629
8630 /*
8631 ** Convenience functions for opening and closing files using 
8632 ** sqlite3_malloc() to obtain space for the file-handle structure.
8633 */
8634 SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
8635 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
8636
8637 #endif /* _SQLITE_OS_H_ */
8638
8639 /************** End of os.h **************************************************/
8640 /************** Continuing where we left off in sqliteInt.h ******************/
8641 /************** Include mutex.h in the middle of sqliteInt.h *****************/
8642 /************** Begin file mutex.h *******************************************/
8643 /*
8644 ** 2007 August 28
8645 **
8646 ** The author disclaims copyright to this source code.  In place of
8647 ** a legal notice, here is a blessing:
8648 **
8649 **    May you do good and not evil.
8650 **    May you find forgiveness for yourself and forgive others.
8651 **    May you share freely, never taking more than you give.
8652 **
8653 *************************************************************************
8654 **
8655 ** This file contains the common header for all mutex implementations.
8656 ** The sqliteInt.h header #includes this file so that it is available
8657 ** to all source files.  We break it out in an effort to keep the code
8658 ** better organized.
8659 **
8660 ** NOTE:  source files should *not* #include this header file directly.
8661 ** Source files should #include the sqliteInt.h file and let that file
8662 ** include this one indirectly.
8663 */
8664
8665
8666 /*
8667 ** Figure out what version of the code to use.  The choices are
8668 **
8669 **   SQLITE_MUTEX_OMIT         No mutex logic.  Not even stubs.  The
8670 **                             mutexes implemention cannot be overridden
8671 **                             at start-time.
8672 **
8673 **   SQLITE_MUTEX_NOOP         For single-threaded applications.  No
8674 **                             mutual exclusion is provided.  But this
8675 **                             implementation can be overridden at
8676 **                             start-time.
8677 **
8678 **   SQLITE_MUTEX_PTHREADS     For multi-threaded applications on Unix.
8679 **
8680 **   SQLITE_MUTEX_W32          For multi-threaded applications on Win32.
8681 **
8682 **   SQLITE_MUTEX_OS2          For multi-threaded applications on OS/2.
8683 */
8684 #if !SQLITE_THREADSAFE
8685 # define SQLITE_MUTEX_OMIT
8686 #endif
8687 #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
8688 #  if SQLITE_OS_UNIX
8689 #    define SQLITE_MUTEX_PTHREADS
8690 #  elif SQLITE_OS_WIN
8691 #    define SQLITE_MUTEX_W32
8692 #  elif SQLITE_OS_OS2
8693 #    define SQLITE_MUTEX_OS2
8694 #  else
8695 #    define SQLITE_MUTEX_NOOP
8696 #  endif
8697 #endif
8698
8699 #ifdef SQLITE_MUTEX_OMIT
8700 /*
8701 ** If this is a no-op implementation, implement everything as macros.
8702 */
8703 #define sqlite3_mutex_alloc(X)    ((sqlite3_mutex*)8)
8704 #define sqlite3_mutex_free(X)
8705 #define sqlite3_mutex_enter(X)
8706 #define sqlite3_mutex_try(X)      SQLITE_OK
8707 #define sqlite3_mutex_leave(X)
8708 #define sqlite3_mutex_held(X)     ((void)(X),1)
8709 #define sqlite3_mutex_notheld(X)  ((void)(X),1)
8710 #define sqlite3MutexAlloc(X)      ((sqlite3_mutex*)8)
8711 #define sqlite3MutexInit()        SQLITE_OK
8712 #define sqlite3MutexEnd()
8713 #endif /* defined(SQLITE_MUTEX_OMIT) */
8714
8715 /************** End of mutex.h ***********************************************/
8716 /************** Continuing where we left off in sqliteInt.h ******************/
8717
8718
8719 /*
8720 ** Each database file to be accessed by the system is an instance
8721 ** of the following structure.  There are normally two of these structures
8722 ** in the sqlite.aDb[] array.  aDb[0] is the main database file and
8723 ** aDb[1] is the database file used to hold temporary tables.  Additional
8724 ** databases may be attached.
8725 */
8726 struct Db {
8727   char *zName;         /* Name of this database */
8728   Btree *pBt;          /* The B*Tree structure for this database file */
8729   u8 inTrans;          /* 0: not writable.  1: Transaction.  2: Checkpoint */
8730   u8 safety_level;     /* How aggressive at syncing data to disk */
8731   Schema *pSchema;     /* Pointer to database schema (possibly shared) */
8732 };
8733
8734 /*
8735 ** An instance of the following structure stores a database schema.
8736 */
8737 struct Schema {
8738   int schema_cookie;   /* Database schema version number for this file */
8739   Hash tblHash;        /* All tables indexed by name */
8740   Hash idxHash;        /* All (named) indices indexed by name */
8741   Hash trigHash;       /* All triggers indexed by name */
8742   Hash fkeyHash;       /* All foreign keys by referenced table name */
8743   Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */
8744   u8 file_format;      /* Schema format version for this file */
8745   u8 enc;              /* Text encoding used by this database */
8746   u16 flags;           /* Flags associated with this schema */
8747   int cache_size;      /* Number of pages to use in the cache */
8748 };
8749
8750 /*
8751 ** These macros can be used to test, set, or clear bits in the 
8752 ** Db.pSchema->flags field.
8753 */
8754 #define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->flags&(P))==(P))
8755 #define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->flags&(P))!=0)
8756 #define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->flags|=(P)
8757 #define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->flags&=~(P)
8758
8759 /*
8760 ** Allowed values for the DB.pSchema->flags field.
8761 **
8762 ** The DB_SchemaLoaded flag is set after the database schema has been
8763 ** read into internal hash tables.
8764 **
8765 ** DB_UnresetViews means that one or more views have column names that
8766 ** have been filled out.  If the schema changes, these column names might
8767 ** changes and so the view will need to be reset.
8768 */
8769 #define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
8770 #define DB_UnresetViews    0x0002  /* Some views have defined column names */
8771 #define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */
8772
8773 /*
8774 ** The number of different kinds of things that can be limited
8775 ** using the sqlite3_limit() interface.
8776 */
8777 #define SQLITE_N_LIMIT (SQLITE_LIMIT_TRIGGER_DEPTH+1)
8778
8779 /*
8780 ** Lookaside malloc is a set of fixed-size buffers that can be used
8781 ** to satisfy small transient memory allocation requests for objects
8782 ** associated with a particular database connection.  The use of
8783 ** lookaside malloc provides a significant performance enhancement
8784 ** (approx 10%) by avoiding numerous malloc/free requests while parsing
8785 ** SQL statements.
8786 **
8787 ** The Lookaside structure holds configuration information about the
8788 ** lookaside malloc subsystem.  Each available memory allocation in
8789 ** the lookaside subsystem is stored on a linked list of LookasideSlot
8790 ** objects.
8791 **
8792 ** Lookaside allocations are only allowed for objects that are associated
8793 ** with a particular database connection.  Hence, schema information cannot
8794 ** be stored in lookaside because in shared cache mode the schema information
8795 ** is shared by multiple database connections.  Therefore, while parsing
8796 ** schema information, the Lookaside.bEnabled flag is cleared so that
8797 ** lookaside allocations are not used to construct the schema objects.
8798 */
8799 struct Lookaside {
8800   u16 sz;                 /* Size of each buffer in bytes */
8801   u8 bEnabled;            /* False to disable new lookaside allocations */
8802   u8 bMalloced;           /* True if pStart obtained from sqlite3_malloc() */
8803   int nOut;               /* Number of buffers currently checked out */
8804   int mxOut;              /* Highwater mark for nOut */
8805   LookasideSlot *pFree;   /* List of available buffers */
8806   void *pStart;           /* First byte of available memory space */
8807   void *pEnd;             /* First byte past end of available space */
8808 };
8809 struct LookasideSlot {
8810   LookasideSlot *pNext;    /* Next buffer in the list of free buffers */
8811 };
8812
8813 /*
8814 ** A hash table for function definitions.
8815 **
8816 ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
8817 ** Collisions are on the FuncDef.pHash chain.
8818 */
8819 struct FuncDefHash {
8820   FuncDef *a[23];       /* Hash table for functions */
8821 };
8822
8823 /*
8824 ** Each database connection is an instance of the following structure.
8825 **
8826 ** The sqlite.lastRowid records the last insert rowid generated by an
8827 ** insert statement.  Inserts on views do not affect its value.  Each
8828 ** trigger has its own context, so that lastRowid can be updated inside
8829 ** triggers as usual.  The previous value will be restored once the trigger
8830 ** exits.  Upon entering a before or instead of trigger, lastRowid is no
8831 ** longer (since after version 2.8.12) reset to -1.
8832 **
8833 ** The sqlite.nChange does not count changes within triggers and keeps no
8834 ** context.  It is reset at start of sqlite3_exec.
8835 ** The sqlite.lsChange represents the number of changes made by the last
8836 ** insert, update, or delete statement.  It remains constant throughout the
8837 ** length of a statement and is then updated by OP_SetCounts.  It keeps a
8838 ** context stack just like lastRowid so that the count of changes
8839 ** within a trigger is not seen outside the trigger.  Changes to views do not
8840 ** affect the value of lsChange.
8841 ** The sqlite.csChange keeps track of the number of current changes (since
8842 ** the last statement) and is used to update sqlite_lsChange.
8843 **
8844 ** The member variables sqlite.errCode, sqlite.zErrMsg and sqlite.zErrMsg16
8845 ** store the most recent error code and, if applicable, string. The
8846 ** internal function sqlite3Error() is used to set these variables
8847 ** consistently.
8848 */
8849 struct sqlite3 {
8850   sqlite3_vfs *pVfs;            /* OS Interface */
8851   int nDb;                      /* Number of backends currently in use */
8852   Db *aDb;                      /* All backends */
8853   int flags;                    /* Miscellaneous flags. See below */
8854   int openFlags;                /* Flags passed to sqlite3_vfs.xOpen() */
8855   int errCode;                  /* Most recent error code (SQLITE_*) */
8856   int errMask;                  /* & result codes with this before returning */
8857   u8 autoCommit;                /* The auto-commit flag. */
8858   u8 temp_store;                /* 1: file 2: memory 0: default */
8859   u8 mallocFailed;              /* True if we have seen a malloc failure */
8860   u8 dfltLockMode;              /* Default locking-mode for attached dbs */
8861   signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
8862   u8 suppressErr;               /* Do not issue error messages if true */
8863   int nextPagesize;             /* Pagesize after VACUUM if >0 */
8864   int nTable;                   /* Number of tables in the database */
8865   CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
8866   i64 lastRowid;                /* ROWID of most recent insert (see above) */
8867   u32 magic;                    /* Magic number for detect library misuse */
8868   int nChange;                  /* Value returned by sqlite3_changes() */
8869   int nTotalChange;             /* Value returned by sqlite3_total_changes() */
8870   sqlite3_mutex *mutex;         /* Connection mutex */
8871   int aLimit[SQLITE_N_LIMIT];   /* Limits */
8872   struct sqlite3InitInfo {      /* Information used during initialization */
8873     int iDb;                    /* When back is being initialized */
8874     int newTnum;                /* Rootpage of table being initialized */
8875     u8 busy;                    /* TRUE if currently initializing */
8876     u8 orphanTrigger;           /* Last statement is orphaned TEMP trigger */
8877   } init;
8878   int nExtension;               /* Number of loaded extensions */
8879   void **aExtension;            /* Array of shared library handles */
8880   struct Vdbe *pVdbe;           /* List of active virtual machines */
8881   int activeVdbeCnt;            /* Number of VDBEs currently executing */
8882   int writeVdbeCnt;             /* Number of active VDBEs that are writing */
8883   void (*xTrace)(void*,const char*);        /* Trace function */
8884   void *pTraceArg;                          /* Argument to the trace function */
8885   void (*xProfile)(void*,const char*,u64);  /* Profiling function */
8886   void *pProfileArg;                        /* Argument to profile function */
8887   void *pCommitArg;                 /* Argument to xCommitCallback() */   
8888   int (*xCommitCallback)(void*);    /* Invoked at every commit. */
8889   void *pRollbackArg;               /* Argument to xRollbackCallback() */   
8890   void (*xRollbackCallback)(void*); /* Invoked at every commit. */
8891   void *pUpdateArg;
8892   void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
8893 #ifndef SQLITE_OMIT_WAL
8894   int (*xWalCallback)(void *, sqlite3 *, const char *, int);
8895   void *pWalArg;
8896 #endif
8897   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
8898   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
8899   void *pCollNeededArg;
8900   sqlite3_value *pErr;          /* Most recent error message */
8901   char *zErrMsg;                /* Most recent error message (UTF-8 encoded) */
8902   char *zErrMsg16;              /* Most recent error message (UTF-16 encoded) */
8903   union {
8904     volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
8905     double notUsed1;            /* Spacer */
8906   } u1;
8907   Lookaside lookaside;          /* Lookaside malloc configuration */
8908 #ifndef SQLITE_OMIT_AUTHORIZATION
8909   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
8910                                 /* Access authorization function */
8911   void *pAuthArg;               /* 1st argument to the access auth function */
8912 #endif
8913 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
8914   int (*xProgress)(void *);     /* The progress callback */
8915   void *pProgressArg;           /* Argument to the progress callback */
8916   int nProgressOps;             /* Number of opcodes for progress callback */
8917 #endif
8918 #ifndef SQLITE_OMIT_VIRTUALTABLE
8919   Hash aModule;                 /* populated by sqlite3_create_module() */
8920   Table *pVTab;                 /* vtab with active Connect/Create method */
8921   VTable **aVTrans;             /* Virtual tables with open transactions */
8922   int nVTrans;                  /* Allocated size of aVTrans */
8923   VTable *pDisconnect;    /* Disconnect these in next sqlite3_prepare() */
8924 #endif
8925   FuncDefHash aFunc;            /* Hash table of connection functions */
8926   Hash aCollSeq;                /* All collating sequences */
8927   BusyHandler busyHandler;      /* Busy callback */
8928   int busyTimeout;              /* Busy handler timeout, in msec */
8929   Db aDbStatic[2];              /* Static space for the 2 default backends */
8930   Savepoint *pSavepoint;        /* List of active savepoints */
8931   int nSavepoint;               /* Number of non-transaction savepoints */
8932   int nStatement;               /* Number of nested statement-transactions  */
8933   u8 isTransactionSavepoint;    /* True if the outermost savepoint is a TS */
8934   i64 nDeferredCons;            /* Net deferred constraints this transaction. */
8935   int *pnBytesFreed;            /* If not NULL, increment this in DbFree() */
8936
8937 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
8938   /* The following variables are all protected by the STATIC_MASTER 
8939   ** mutex, not by sqlite3.mutex. They are used by code in notify.c. 
8940   **
8941   ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
8942   ** unlock so that it can proceed.
8943   **
8944   ** When X.pBlockingConnection==Y, that means that something that X tried
8945   ** tried to do recently failed with an SQLITE_LOCKED error due to locks
8946   ** held by Y.
8947   */
8948   sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
8949   sqlite3 *pUnlockConnection;           /* Connection to watch for unlock */
8950   void *pUnlockArg;                     /* Argument to xUnlockNotify */
8951   void (*xUnlockNotify)(void **, int);  /* Unlock notify callback */
8952   sqlite3 *pNextBlocked;        /* Next in list of all blocked connections */
8953 #endif
8954 };
8955
8956 /*
8957 ** A macro to discover the encoding of a database.
8958 */
8959 #define ENC(db) ((db)->aDb[0].pSchema->enc)
8960
8961 /*
8962 ** Possible values for the sqlite3.flags.
8963 */
8964 #define SQLITE_VdbeTrace      0x00000100  /* True to trace VDBE execution */
8965 #define SQLITE_InternChanges  0x00000200  /* Uncommitted Hash table changes */
8966 #define SQLITE_FullColNames   0x00000400  /* Show full column names on SELECT */
8967 #define SQLITE_ShortColNames  0x00000800  /* Show short columns names */
8968 #define SQLITE_CountRows      0x00001000  /* Count rows changed by INSERT, */
8969                                           /*   DELETE, or UPDATE and return */
8970                                           /*   the count using a callback. */
8971 #define SQLITE_NullCallback   0x00002000  /* Invoke the callback once if the */
8972                                           /*   result set is empty */
8973 #define SQLITE_SqlTrace       0x00004000  /* Debug print SQL as it executes */
8974 #define SQLITE_VdbeListing    0x00008000  /* Debug listings of VDBE programs */
8975 #define SQLITE_WriteSchema    0x00010000  /* OK to update SQLITE_MASTER */
8976 #define SQLITE_NoReadlock     0x00020000  /* Readlocks are omitted when 
8977                                           ** accessing read-only databases */
8978 #define SQLITE_IgnoreChecks   0x00040000  /* Do not enforce check constraints */
8979 #define SQLITE_ReadUncommitted 0x0080000  /* For shared-cache mode */
8980 #define SQLITE_LegacyFileFmt  0x00100000  /* Create new databases in format 1 */
8981 #define SQLITE_FullFSync      0x00200000  /* Use full fsync on the backend */
8982 #define SQLITE_LoadExtension  0x00400000  /* Enable load_extension */
8983 #define SQLITE_RecoveryMode   0x00800000  /* Ignore schema errors */
8984 #define SQLITE_ReverseOrder   0x01000000  /* Reverse unordered SELECTs */
8985 #define SQLITE_RecTriggers    0x02000000  /* Enable recursive triggers */
8986 #define SQLITE_ForeignKeys    0x04000000  /* Enforce foreign key constraints  */
8987 #define SQLITE_AutoIndex      0x08000000  /* Enable automatic indexes */
8988 #define SQLITE_PreferBuiltin  0x10000000  /* Preference to built-in funcs */
8989
8990 /*
8991 ** Bits of the sqlite3.flags field that are used by the
8992 ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface.
8993 ** These must be the low-order bits of the flags field.
8994 */
8995 #define SQLITE_QueryFlattener 0x01        /* Disable query flattening */
8996 #define SQLITE_ColumnCache    0x02        /* Disable the column cache */
8997 #define SQLITE_IndexSort      0x04        /* Disable indexes for sorting */
8998 #define SQLITE_IndexSearch    0x08        /* Disable indexes for searching */
8999 #define SQLITE_IndexCover     0x10        /* Disable index covering table */
9000 #define SQLITE_GroupByOrder   0x20        /* Disable GROUPBY cover of ORDERBY */
9001 #define SQLITE_OptMask        0xff        /* Mask of all disablable opts */
9002
9003 /*
9004 ** Possible values for the sqlite.magic field.
9005 ** The numbers are obtained at random and have no special meaning, other
9006 ** than being distinct from one another.
9007 */
9008 #define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
9009 #define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
9010 #define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
9011 #define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
9012 #define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
9013
9014 /*
9015 ** Each SQL function is defined by an instance of the following
9016 ** structure.  A pointer to this structure is stored in the sqlite.aFunc
9017 ** hash table.  When multiple functions have the same name, the hash table
9018 ** points to a linked list of these structures.
9019 */
9020 struct FuncDef {
9021   i16 nArg;            /* Number of arguments.  -1 means unlimited */
9022   u8 iPrefEnc;         /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */
9023   u8 flags;            /* Some combination of SQLITE_FUNC_* */
9024   void *pUserData;     /* User data parameter */
9025   FuncDef *pNext;      /* Next function with same name */
9026   void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
9027   void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
9028   void (*xFinalize)(sqlite3_context*);                /* Aggregate finalizer */
9029   char *zName;         /* SQL name of the function. */
9030   FuncDef *pHash;      /* Next with a different name but the same hash */
9031   FuncDestructor *pDestructor;   /* Reference counted destructor function */
9032 };
9033
9034 /*
9035 ** This structure encapsulates a user-function destructor callback (as
9036 ** configured using create_function_v2()) and a reference counter. When
9037 ** create_function_v2() is called to create a function with a destructor,
9038 ** a single object of this type is allocated. FuncDestructor.nRef is set to 
9039 ** the number of FuncDef objects created (either 1 or 3, depending on whether
9040 ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
9041 ** member of each of the new FuncDef objects is set to point to the allocated
9042 ** FuncDestructor.
9043 **
9044 ** Thereafter, when one of the FuncDef objects is deleted, the reference
9045 ** count on this object is decremented. When it reaches 0, the destructor
9046 ** is invoked and the FuncDestructor structure freed.
9047 */
9048 struct FuncDestructor {
9049   int nRef;
9050   void (*xDestroy)(void *);
9051   void *pUserData;
9052 };
9053
9054 /*
9055 ** Possible values for FuncDef.flags
9056 */
9057 #define SQLITE_FUNC_LIKE     0x01 /* Candidate for the LIKE optimization */
9058 #define SQLITE_FUNC_CASE     0x02 /* Case-sensitive LIKE-type function */
9059 #define SQLITE_FUNC_EPHEM    0x04 /* Ephemeral.  Delete with VDBE */
9060 #define SQLITE_FUNC_NEEDCOLL 0x08 /* sqlite3GetFuncCollSeq() might be called */
9061 #define SQLITE_FUNC_PRIVATE  0x10 /* Allowed for internal use only */
9062 #define SQLITE_FUNC_COUNT    0x20 /* Built-in count(*) aggregate */
9063 #define SQLITE_FUNC_COALESCE 0x40 /* Built-in coalesce() or ifnull() function */
9064
9065 /*
9066 ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
9067 ** used to create the initializers for the FuncDef structures.
9068 **
9069 **   FUNCTION(zName, nArg, iArg, bNC, xFunc)
9070 **     Used to create a scalar function definition of a function zName 
9071 **     implemented by C function xFunc that accepts nArg arguments. The
9072 **     value passed as iArg is cast to a (void*) and made available
9073 **     as the user-data (sqlite3_user_data()) for the function. If 
9074 **     argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
9075 **
9076 **   AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
9077 **     Used to create an aggregate function definition implemented by
9078 **     the C functions xStep and xFinal. The first four parameters
9079 **     are interpreted in the same way as the first 4 parameters to
9080 **     FUNCTION().
9081 **
9082 **   LIKEFUNC(zName, nArg, pArg, flags)
9083 **     Used to create a scalar function definition of a function zName 
9084 **     that accepts nArg arguments and is implemented by a call to C 
9085 **     function likeFunc. Argument pArg is cast to a (void *) and made
9086 **     available as the function user-data (sqlite3_user_data()). The
9087 **     FuncDef.flags variable is set to the value passed as the flags
9088 **     parameter.
9089 */
9090 #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
9091   {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
9092    SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
9093 #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
9094   {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
9095    pArg, 0, xFunc, 0, 0, #zName, 0, 0}
9096 #define LIKEFUNC(zName, nArg, arg, flags) \
9097   {nArg, SQLITE_UTF8, flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0, 0}
9098 #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
9099   {nArg, SQLITE_UTF8, nc*SQLITE_FUNC_NEEDCOLL, \
9100    SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
9101
9102 /*
9103 ** All current savepoints are stored in a linked list starting at
9104 ** sqlite3.pSavepoint. The first element in the list is the most recently
9105 ** opened savepoint. Savepoints are added to the list by the vdbe
9106 ** OP_Savepoint instruction.
9107 */
9108 struct Savepoint {
9109   char *zName;                        /* Savepoint name (nul-terminated) */
9110   i64 nDeferredCons;                  /* Number of deferred fk violations */
9111   Savepoint *pNext;                   /* Parent savepoint (if any) */
9112 };
9113
9114 /*
9115 ** The following are used as the second parameter to sqlite3Savepoint(),
9116 ** and as the P1 argument to the OP_Savepoint instruction.
9117 */
9118 #define SAVEPOINT_BEGIN      0
9119 #define SAVEPOINT_RELEASE    1
9120 #define SAVEPOINT_ROLLBACK   2
9121
9122
9123 /*
9124 ** Each SQLite module (virtual table definition) is defined by an
9125 ** instance of the following structure, stored in the sqlite3.aModule
9126 ** hash table.
9127 */
9128 struct Module {
9129   const sqlite3_module *pModule;       /* Callback pointers */
9130   const char *zName;                   /* Name passed to create_module() */
9131   void *pAux;                          /* pAux passed to create_module() */
9132   void (*xDestroy)(void *);            /* Module destructor function */
9133 };
9134
9135 /*
9136 ** information about each column of an SQL table is held in an instance
9137 ** of this structure.
9138 */
9139 struct Column {
9140   char *zName;     /* Name of this column */
9141   Expr *pDflt;     /* Default value of this column */
9142   char *zDflt;     /* Original text of the default value */
9143   char *zType;     /* Data type for this column */
9144   char *zColl;     /* Collating sequence.  If NULL, use the default */
9145   u8 notNull;      /* True if there is a NOT NULL constraint */
9146   u8 isPrimKey;    /* True if this column is part of the PRIMARY KEY */
9147   char affinity;   /* One of the SQLITE_AFF_... values */
9148 #ifndef SQLITE_OMIT_VIRTUALTABLE
9149   u8 isHidden;     /* True if this column is 'hidden' */
9150 #endif
9151 };
9152
9153 /*
9154 ** A "Collating Sequence" is defined by an instance of the following
9155 ** structure. Conceptually, a collating sequence consists of a name and
9156 ** a comparison routine that defines the order of that sequence.
9157 **
9158 ** There may two separate implementations of the collation function, one
9159 ** that processes text in UTF-8 encoding (CollSeq.xCmp) and another that
9160 ** processes text encoded in UTF-16 (CollSeq.xCmp16), using the machine
9161 ** native byte order. When a collation sequence is invoked, SQLite selects
9162 ** the version that will require the least expensive encoding
9163 ** translations, if any.
9164 **
9165 ** The CollSeq.pUser member variable is an extra parameter that passed in
9166 ** as the first argument to the UTF-8 comparison function, xCmp.
9167 ** CollSeq.pUser16 is the equivalent for the UTF-16 comparison function,
9168 ** xCmp16.
9169 **
9170 ** If both CollSeq.xCmp and CollSeq.xCmp16 are NULL, it means that the
9171 ** collating sequence is undefined.  Indices built on an undefined
9172 ** collating sequence may not be read or written.
9173 */
9174 struct CollSeq {
9175   char *zName;          /* Name of the collating sequence, UTF-8 encoded */
9176   u8 enc;               /* Text encoding handled by xCmp() */
9177   u8 type;              /* One of the SQLITE_COLL_... values below */
9178   void *pUser;          /* First argument to xCmp() */
9179   int (*xCmp)(void*,int, const void*, int, const void*);
9180   void (*xDel)(void*);  /* Destructor for pUser */
9181 };
9182
9183 /*
9184 ** Allowed values of CollSeq.type:
9185 */
9186 #define SQLITE_COLL_BINARY  1  /* The default memcmp() collating sequence */
9187 #define SQLITE_COLL_NOCASE  2  /* The built-in NOCASE collating sequence */
9188 #define SQLITE_COLL_REVERSE 3  /* The built-in REVERSE collating sequence */
9189 #define SQLITE_COLL_USER    0  /* Any other user-defined collating sequence */
9190
9191 /*
9192 ** A sort order can be either ASC or DESC.
9193 */
9194 #define SQLITE_SO_ASC       0  /* Sort in ascending order */
9195 #define SQLITE_SO_DESC      1  /* Sort in ascending order */
9196
9197 /*
9198 ** Column affinity types.
9199 **
9200 ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
9201 ** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve
9202 ** the speed a little by numbering the values consecutively.  
9203 **
9204 ** But rather than start with 0 or 1, we begin with 'a'.  That way,
9205 ** when multiple affinity types are concatenated into a string and
9206 ** used as the P4 operand, they will be more readable.
9207 **
9208 ** Note also that the numeric types are grouped together so that testing
9209 ** for a numeric type is a single comparison.
9210 */
9211 #define SQLITE_AFF_TEXT     'a'
9212 #define SQLITE_AFF_NONE     'b'
9213 #define SQLITE_AFF_NUMERIC  'c'
9214 #define SQLITE_AFF_INTEGER  'd'
9215 #define SQLITE_AFF_REAL     'e'
9216
9217 #define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)
9218
9219 /*
9220 ** The SQLITE_AFF_MASK values masks off the significant bits of an
9221 ** affinity value. 
9222 */
9223 #define SQLITE_AFF_MASK     0x67
9224
9225 /*
9226 ** Additional bit values that can be ORed with an affinity without
9227 ** changing the affinity.
9228 */
9229 #define SQLITE_JUMPIFNULL   0x08  /* jumps if either operand is NULL */
9230 #define SQLITE_STOREP2      0x10  /* Store result in reg[P2] rather than jump */
9231 #define SQLITE_NULLEQ       0x80  /* NULL=NULL */
9232
9233 /*
9234 ** An object of this type is created for each virtual table present in
9235 ** the database schema. 
9236 **
9237 ** If the database schema is shared, then there is one instance of this
9238 ** structure for each database connection (sqlite3*) that uses the shared
9239 ** schema. This is because each database connection requires its own unique
9240 ** instance of the sqlite3_vtab* handle used to access the virtual table 
9241 ** implementation. sqlite3_vtab* handles can not be shared between 
9242 ** database connections, even when the rest of the in-memory database 
9243 ** schema is shared, as the implementation often stores the database
9244 ** connection handle passed to it via the xConnect() or xCreate() method
9245 ** during initialization internally. This database connection handle may
9246 ** then used by the virtual table implementation to access real tables 
9247 ** within the database. So that they appear as part of the callers 
9248 ** transaction, these accesses need to be made via the same database 
9249 ** connection as that used to execute SQL operations on the virtual table.
9250 **
9251 ** All VTable objects that correspond to a single table in a shared
9252 ** database schema are initially stored in a linked-list pointed to by
9253 ** the Table.pVTable member variable of the corresponding Table object.
9254 ** When an sqlite3_prepare() operation is required to access the virtual
9255 ** table, it searches the list for the VTable that corresponds to the
9256 ** database connection doing the preparing so as to use the correct
9257 ** sqlite3_vtab* handle in the compiled query.
9258 **
9259 ** When an in-memory Table object is deleted (for example when the
9260 ** schema is being reloaded for some reason), the VTable objects are not 
9261 ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed 
9262 ** immediately. Instead, they are moved from the Table.pVTable list to
9263 ** another linked list headed by the sqlite3.pDisconnect member of the
9264 ** corresponding sqlite3 structure. They are then deleted/xDisconnected 
9265 ** next time a statement is prepared using said sqlite3*. This is done
9266 ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
9267 ** Refer to comments above function sqlite3VtabUnlockList() for an
9268 ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
9269 ** list without holding the corresponding sqlite3.mutex mutex.
9270 **
9271 ** The memory for objects of this type is always allocated by 
9272 ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as 
9273 ** the first argument.
9274 */
9275 struct VTable {
9276   sqlite3 *db;              /* Database connection associated with this table */
9277   Module *pMod;             /* Pointer to module implementation */
9278   sqlite3_vtab *pVtab;      /* Pointer to vtab instance */
9279   int nRef;                 /* Number of pointers to this structure */
9280   VTable *pNext;            /* Next in linked list (see above) */
9281 };
9282
9283 /*
9284 ** Each SQL table is represented in memory by an instance of the
9285 ** following structure.
9286 **
9287 ** Table.zName is the name of the table.  The case of the original
9288 ** CREATE TABLE statement is stored, but case is not significant for
9289 ** comparisons.
9290 **
9291 ** Table.nCol is the number of columns in this table.  Table.aCol is a
9292 ** pointer to an array of Column structures, one for each column.
9293 **
9294 ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
9295 ** the column that is that key.   Otherwise Table.iPKey is negative.  Note
9296 ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
9297 ** be set.  An INTEGER PRIMARY KEY is used as the rowid for each row of
9298 ** the table.  If a table has no INTEGER PRIMARY KEY, then a random rowid
9299 ** is generated for each row of the table.  TF_HasPrimaryKey is set if
9300 ** the table has any PRIMARY KEY, INTEGER or otherwise.
9301 **
9302 ** Table.tnum is the page number for the root BTree page of the table in the
9303 ** database file.  If Table.iDb is the index of the database table backend
9304 ** in sqlite.aDb[].  0 is for the main database and 1 is for the file that
9305 ** holds temporary tables and indices.  If TF_Ephemeral is set
9306 ** then the table is stored in a file that is automatically deleted
9307 ** when the VDBE cursor to the table is closed.  In this case Table.tnum 
9308 ** refers VDBE cursor number that holds the table open, not to the root
9309 ** page number.  Transient tables are used to hold the results of a
9310 ** sub-query that appears instead of a real table name in the FROM clause 
9311 ** of a SELECT statement.
9312 */
9313 struct Table {
9314   char *zName;         /* Name of the table or view */
9315   int iPKey;           /* If not negative, use aCol[iPKey] as the primary key */
9316   int nCol;            /* Number of columns in this table */
9317   Column *aCol;        /* Information about each column */
9318   Index *pIndex;       /* List of SQL indexes on this table. */
9319   int tnum;            /* Root BTree node for this table (see note above) */
9320   unsigned nRowEst;    /* Estimated rows in table - from sqlite_stat1 table */
9321   Select *pSelect;     /* NULL for tables.  Points to definition if a view. */
9322   u16 nRef;            /* Number of pointers to this Table */
9323   u8 tabFlags;         /* Mask of TF_* values */
9324   u8 keyConf;          /* What to do in case of uniqueness conflict on iPKey */
9325   FKey *pFKey;         /* Linked list of all foreign keys in this table */
9326   char *zColAff;       /* String defining the affinity of each column */
9327 #ifndef SQLITE_OMIT_CHECK
9328   Expr *pCheck;        /* The AND of all CHECK constraints */
9329 #endif
9330 #ifndef SQLITE_OMIT_ALTERTABLE
9331   int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */
9332 #endif
9333 #ifndef SQLITE_OMIT_VIRTUALTABLE
9334   VTable *pVTable;     /* List of VTable objects. */
9335   int nModuleArg;      /* Number of arguments to the module */
9336   char **azModuleArg;  /* Text of all module args. [0] is module name */
9337 #endif
9338   Trigger *pTrigger;   /* List of triggers stored in pSchema */
9339   Schema *pSchema;     /* Schema that contains this table */
9340   Table *pNextZombie;  /* Next on the Parse.pZombieTab list */
9341 };
9342
9343 /*
9344 ** Allowed values for Tabe.tabFlags.
9345 */
9346 #define TF_Readonly        0x01    /* Read-only system table */
9347 #define TF_Ephemeral       0x02    /* An ephemeral table */
9348 #define TF_HasPrimaryKey   0x04    /* Table has a primary key */
9349 #define TF_Autoincrement   0x08    /* Integer primary key is autoincrement */
9350 #define TF_Virtual         0x10    /* Is a virtual table */
9351 #define TF_NeedMetadata    0x20    /* aCol[].zType and aCol[].pColl missing */
9352
9353
9354
9355 /*
9356 ** Test to see whether or not a table is a virtual table.  This is
9357 ** done as a macro so that it will be optimized out when virtual
9358 ** table support is omitted from the build.
9359 */
9360 #ifndef SQLITE_OMIT_VIRTUALTABLE
9361 #  define IsVirtual(X)      (((X)->tabFlags & TF_Virtual)!=0)
9362 #  define IsHiddenColumn(X) ((X)->isHidden)
9363 #else
9364 #  define IsVirtual(X)      0
9365 #  define IsHiddenColumn(X) 0
9366 #endif
9367
9368 /*
9369 ** Each foreign key constraint is an instance of the following structure.
9370 **
9371 ** A foreign key is associated with two tables.  The "from" table is
9372 ** the table that contains the REFERENCES clause that creates the foreign
9373 ** key.  The "to" table is the table that is named in the REFERENCES clause.
9374 ** Consider this example:
9375 **
9376 **     CREATE TABLE ex1(
9377 **       a INTEGER PRIMARY KEY,
9378 **       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
9379 **     );
9380 **
9381 ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
9382 **
9383 ** Each REFERENCES clause generates an instance of the following structure
9384 ** which is attached to the from-table.  The to-table need not exist when
9385 ** the from-table is created.  The existence of the to-table is not checked.
9386 */
9387 struct FKey {
9388   Table *pFrom;     /* Table containing the REFERENCES clause (aka: Child) */
9389   FKey *pNextFrom;  /* Next foreign key in pFrom */
9390   char *zTo;        /* Name of table that the key points to (aka: Parent) */
9391   FKey *pNextTo;    /* Next foreign key on table named zTo */
9392   FKey *pPrevTo;    /* Previous foreign key on table named zTo */
9393   int nCol;         /* Number of columns in this key */
9394   /* EV: R-30323-21917 */
9395   u8 isDeferred;    /* True if constraint checking is deferred till COMMIT */
9396   u8 aAction[2];          /* ON DELETE and ON UPDATE actions, respectively */
9397   Trigger *apTrigger[2];  /* Triggers for aAction[] actions */
9398   struct sColMap {  /* Mapping of columns in pFrom to columns in zTo */
9399     int iFrom;         /* Index of column in pFrom */
9400     char *zCol;        /* Name of column in zTo.  If 0 use PRIMARY KEY */
9401   } aCol[1];        /* One entry for each of nCol column s */
9402 };
9403
9404 /*
9405 ** SQLite supports many different ways to resolve a constraint
9406 ** error.  ROLLBACK processing means that a constraint violation
9407 ** causes the operation in process to fail and for the current transaction
9408 ** to be rolled back.  ABORT processing means the operation in process
9409 ** fails and any prior changes from that one operation are backed out,
9410 ** but the transaction is not rolled back.  FAIL processing means that
9411 ** the operation in progress stops and returns an error code.  But prior
9412 ** changes due to the same operation are not backed out and no rollback
9413 ** occurs.  IGNORE means that the particular row that caused the constraint
9414 ** error is not inserted or updated.  Processing continues and no error
9415 ** is returned.  REPLACE means that preexisting database rows that caused
9416 ** a UNIQUE constraint violation are removed so that the new insert or
9417 ** update can proceed.  Processing continues and no error is reported.
9418 **
9419 ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
9420 ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
9421 ** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
9422 ** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
9423 ** referenced table row is propagated into the row that holds the
9424 ** foreign key.
9425 ** 
9426 ** The following symbolic values are used to record which type
9427 ** of action to take.
9428 */
9429 #define OE_None     0   /* There is no constraint to check */
9430 #define OE_Rollback 1   /* Fail the operation and rollback the transaction */
9431 #define OE_Abort    2   /* Back out changes but do no rollback transaction */
9432 #define OE_Fail     3   /* Stop the operation but leave all prior changes */
9433 #define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
9434 #define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
9435
9436 #define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
9437 #define OE_SetNull  7   /* Set the foreign key value to NULL */
9438 #define OE_SetDflt  8   /* Set the foreign key value to its default */
9439 #define OE_Cascade  9   /* Cascade the changes */
9440
9441 #define OE_Default  99  /* Do whatever the default action is */
9442
9443
9444 /*
9445 ** An instance of the following structure is passed as the first
9446 ** argument to sqlite3VdbeKeyCompare and is used to control the 
9447 ** comparison of the two index keys.
9448 */
9449 struct KeyInfo {
9450   sqlite3 *db;        /* The database connection */
9451   u8 enc;             /* Text encoding - one of the SQLITE_UTF* values */
9452   u16 nField;         /* Number of entries in aColl[] */
9453   u8 *aSortOrder;     /* Sort order for each column.  May be NULL */
9454   CollSeq *aColl[1];  /* Collating sequence for each term of the key */
9455 };
9456
9457 /*
9458 ** An instance of the following structure holds information about a
9459 ** single index record that has already been parsed out into individual
9460 ** values.
9461 **
9462 ** A record is an object that contains one or more fields of data.
9463 ** Records are used to store the content of a table row and to store
9464 ** the key of an index.  A blob encoding of a record is created by
9465 ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
9466 ** OP_Column opcode.
9467 **
9468 ** This structure holds a record that has already been disassembled
9469 ** into its constituent fields.
9470 */
9471 struct UnpackedRecord {
9472   KeyInfo *pKeyInfo;  /* Collation and sort-order information */
9473   u16 nField;         /* Number of entries in apMem[] */
9474   u16 flags;          /* Boolean settings.  UNPACKED_... below */
9475   i64 rowid;          /* Used by UNPACKED_PREFIX_SEARCH */
9476   Mem *aMem;          /* Values */
9477 };
9478
9479 /*
9480 ** Allowed values of UnpackedRecord.flags
9481 */
9482 #define UNPACKED_NEED_FREE     0x0001  /* Memory is from sqlite3Malloc() */
9483 #define UNPACKED_NEED_DESTROY  0x0002  /* apMem[]s should all be destroyed */
9484 #define UNPACKED_IGNORE_ROWID  0x0004  /* Ignore trailing rowid on key1 */
9485 #define UNPACKED_INCRKEY       0x0008  /* Make this key an epsilon larger */
9486 #define UNPACKED_PREFIX_MATCH  0x0010  /* A prefix match is considered OK */
9487 #define UNPACKED_PREFIX_SEARCH 0x0020  /* A prefix match is considered OK */
9488
9489 /*
9490 ** Each SQL index is represented in memory by an
9491 ** instance of the following structure.
9492 **
9493 ** The columns of the table that are to be indexed are described
9494 ** by the aiColumn[] field of this structure.  For example, suppose
9495 ** we have the following table and index:
9496 **
9497 **     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
9498 **     CREATE INDEX Ex2 ON Ex1(c3,c1);
9499 **
9500 ** In the Table structure describing Ex1, nCol==3 because there are
9501 ** three columns in the table.  In the Index structure describing
9502 ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
9503 ** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the 
9504 ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
9505 ** The second column to be indexed (c1) has an index of 0 in
9506 ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
9507 **
9508 ** The Index.onError field determines whether or not the indexed columns
9509 ** must be unique and what to do if they are not.  When Index.onError=OE_None,
9510 ** it means this is not a unique index.  Otherwise it is a unique index
9511 ** and the value of Index.onError indicate the which conflict resolution 
9512 ** algorithm to employ whenever an attempt is made to insert a non-unique
9513 ** element.
9514 */
9515 struct Index {
9516   char *zName;     /* Name of this index */
9517   int nColumn;     /* Number of columns in the table used by this index */
9518   int *aiColumn;   /* Which columns are used by this index.  1st is 0 */
9519   unsigned *aiRowEst; /* Result of ANALYZE: Est. rows selected by each column */
9520   Table *pTable;   /* The SQL table being indexed */
9521   int tnum;        /* Page containing root of this index in database file */
9522   u8 onError;      /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
9523   u8 autoIndex;    /* True if is automatically created (ex: by UNIQUE) */
9524   char *zColAff;   /* String defining the affinity of each column */
9525   Index *pNext;    /* The next index associated with the same table */
9526   Schema *pSchema; /* Schema containing this index */
9527   u8 *aSortOrder;  /* Array of size Index.nColumn. True==DESC, False==ASC */
9528   char **azColl;   /* Array of collation sequence names for index */
9529   IndexSample *aSample;    /* Array of SQLITE_INDEX_SAMPLES samples */
9530 };
9531
9532 /*
9533 ** Each sample stored in the sqlite_stat2 table is represented in memory 
9534 ** using a structure of this type.
9535 */
9536 struct IndexSample {
9537   union {
9538     char *z;        /* Value if eType is SQLITE_TEXT or SQLITE_BLOB */
9539     double r;       /* Value if eType is SQLITE_FLOAT or SQLITE_INTEGER */
9540   } u;
9541   u8 eType;         /* SQLITE_NULL, SQLITE_INTEGER ... etc. */
9542   u8 nByte;         /* Size in byte of text or blob. */
9543 };
9544
9545 /*
9546 ** Each token coming out of the lexer is an instance of
9547 ** this structure.  Tokens are also used as part of an expression.
9548 **
9549 ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
9550 ** may contain random values.  Do not make any assumptions about Token.dyn
9551 ** and Token.n when Token.z==0.
9552 */
9553 struct Token {
9554   const char *z;     /* Text of the token.  Not NULL-terminated! */
9555   unsigned int n;    /* Number of characters in this token */
9556 };
9557
9558 /*
9559 ** An instance of this structure contains information needed to generate
9560 ** code for a SELECT that contains aggregate functions.
9561 **
9562 ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
9563 ** pointer to this structure.  The Expr.iColumn field is the index in
9564 ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
9565 ** code for that node.
9566 **
9567 ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
9568 ** original Select structure that describes the SELECT statement.  These
9569 ** fields do not need to be freed when deallocating the AggInfo structure.
9570 */
9571 struct AggInfo {
9572   u8 directMode;          /* Direct rendering mode means take data directly
9573                           ** from source tables rather than from accumulators */
9574   u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
9575                           ** than the source table */
9576   int sortingIdx;         /* Cursor number of the sorting index */
9577   ExprList *pGroupBy;     /* The group by clause */
9578   int nSortingColumn;     /* Number of columns in the sorting index */
9579   struct AggInfo_col {    /* For each column used in source tables */
9580     Table *pTab;             /* Source table */
9581     int iTable;              /* Cursor number of the source table */
9582     int iColumn;             /* Column number within the source table */
9583     int iSorterColumn;       /* Column number in the sorting index */
9584     int iMem;                /* Memory location that acts as accumulator */
9585     Expr *pExpr;             /* The original expression */
9586   } *aCol;
9587   int nColumn;            /* Number of used entries in aCol[] */
9588   int nColumnAlloc;       /* Number of slots allocated for aCol[] */
9589   int nAccumulator;       /* Number of columns that show through to the output.
9590                           ** Additional columns are used only as parameters to
9591                           ** aggregate functions */
9592   struct AggInfo_func {   /* For each aggregate function */
9593     Expr *pExpr;             /* Expression encoding the function */
9594     FuncDef *pFunc;          /* The aggregate function implementation */
9595     int iMem;                /* Memory location that acts as accumulator */
9596     int iDistinct;           /* Ephemeral table used to enforce DISTINCT */
9597   } *aFunc;
9598   int nFunc;              /* Number of entries in aFunc[] */
9599   int nFuncAlloc;         /* Number of slots allocated for aFunc[] */
9600 };
9601
9602 /*
9603 ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
9604 ** Usually it is 16-bits.  But if SQLITE_MAX_VARIABLE_NUMBER is greater
9605 ** than 32767 we have to make it 32-bit.  16-bit is preferred because
9606 ** it uses less memory in the Expr object, which is a big memory user
9607 ** in systems with lots of prepared statements.  And few applications
9608 ** need more than about 10 or 20 variables.  But some extreme users want
9609 ** to have prepared statements with over 32767 variables, and for them
9610 ** the option is available (at compile-time).
9611 */
9612 #if SQLITE_MAX_VARIABLE_NUMBER<=32767
9613 typedef i16 ynVar;
9614 #else
9615 typedef int ynVar;
9616 #endif
9617
9618 /*
9619 ** Each node of an expression in the parse tree is an instance
9620 ** of this structure.
9621 **
9622 ** Expr.op is the opcode. The integer parser token codes are reused
9623 ** as opcodes here. For example, the parser defines TK_GE to be an integer
9624 ** code representing the ">=" operator. This same integer code is reused
9625 ** to represent the greater-than-or-equal-to operator in the expression
9626 ** tree.
9627 **
9628 ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB, 
9629 ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
9630 ** the expression is a variable (TK_VARIABLE), then Expr.token contains the 
9631 ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
9632 ** then Expr.token contains the name of the function.
9633 **
9634 ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
9635 ** binary operator. Either or both may be NULL.
9636 **
9637 ** Expr.x.pList is a list of arguments if the expression is an SQL function,
9638 ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
9639 ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
9640 ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
9641 ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is 
9642 ** valid.
9643 **
9644 ** An expression of the form ID or ID.ID refers to a column in a table.
9645 ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
9646 ** the integer cursor number of a VDBE cursor pointing to that table and
9647 ** Expr.iColumn is the column number for the specific column.  If the
9648 ** expression is used as a result in an aggregate SELECT, then the
9649 ** value is also stored in the Expr.iAgg column in the aggregate so that
9650 ** it can be accessed after all aggregates are computed.
9651 **
9652 ** If the expression is an unbound variable marker (a question mark 
9653 ** character '?' in the original SQL) then the Expr.iTable holds the index 
9654 ** number for that variable.
9655 **
9656 ** If the expression is a subquery then Expr.iColumn holds an integer
9657 ** register number containing the result of the subquery.  If the
9658 ** subquery gives a constant result, then iTable is -1.  If the subquery
9659 ** gives a different answer at different times during statement processing
9660 ** then iTable is the address of a subroutine that computes the subquery.
9661 **
9662 ** If the Expr is of type OP_Column, and the table it is selecting from
9663 ** is a disk table or the "old.*" pseudo-table, then pTab points to the
9664 ** corresponding table definition.
9665 **
9666 ** ALLOCATION NOTES:
9667 **
9668 ** Expr objects can use a lot of memory space in database schema.  To
9669 ** help reduce memory requirements, sometimes an Expr object will be
9670 ** truncated.  And to reduce the number of memory allocations, sometimes
9671 ** two or more Expr objects will be stored in a single memory allocation,
9672 ** together with Expr.zToken strings.
9673 **
9674 ** If the EP_Reduced and EP_TokenOnly flags are set when
9675 ** an Expr object is truncated.  When EP_Reduced is set, then all
9676 ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
9677 ** are contained within the same memory allocation.  Note, however, that
9678 ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
9679 ** allocated, regardless of whether or not EP_Reduced is set.
9680 */
9681 struct Expr {
9682   u8 op;                 /* Operation performed by this node */
9683   char affinity;         /* The affinity of the column or 0 if not a column */
9684   u16 flags;             /* Various flags.  EP_* See below */
9685   union {
9686     char *zToken;          /* Token value. Zero terminated and dequoted */
9687     int iValue;            /* Integer value if EP_IntValue */
9688   } u;
9689
9690   /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
9691   ** space is allocated for the fields below this point. An attempt to
9692   ** access them will result in a segfault or malfunction. 
9693   *********************************************************************/
9694
9695   Expr *pLeft;           /* Left subnode */
9696   Expr *pRight;          /* Right subnode */
9697   union {
9698     ExprList *pList;     /* Function arguments or in "<expr> IN (<expr-list)" */
9699     Select *pSelect;     /* Used for sub-selects and "<expr> IN (<select>)" */
9700   } x;
9701   CollSeq *pColl;        /* The collation type of the column or 0 */
9702
9703   /* If the EP_Reduced flag is set in the Expr.flags mask, then no
9704   ** space is allocated for the fields below this point. An attempt to
9705   ** access them will result in a segfault or malfunction.
9706   *********************************************************************/
9707
9708   int iTable;            /* TK_COLUMN: cursor number of table holding column
9709                          ** TK_REGISTER: register number
9710                          ** TK_TRIGGER: 1 -> new, 0 -> old */
9711   ynVar iColumn;         /* TK_COLUMN: column index.  -1 for rowid.
9712                          ** TK_VARIABLE: variable number (always >= 1). */
9713   i16 iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
9714   i16 iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
9715   u8 flags2;             /* Second set of flags.  EP2_... */
9716   u8 op2;                /* If a TK_REGISTER, the original value of Expr.op */
9717   AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
9718   Table *pTab;           /* Table for TK_COLUMN expressions. */
9719 #if SQLITE_MAX_EXPR_DEPTH>0
9720   int nHeight;           /* Height of the tree headed by this node */
9721 #endif
9722 };
9723
9724 /*
9725 ** The following are the meanings of bits in the Expr.flags field.
9726 */
9727 #define EP_FromJoin   0x0001  /* Originated in ON or USING clause of a join */
9728 #define EP_Agg        0x0002  /* Contains one or more aggregate functions */
9729 #define EP_Resolved   0x0004  /* IDs have been resolved to COLUMNs */
9730 #define EP_Error      0x0008  /* Expression contains one or more errors */
9731 #define EP_Distinct   0x0010  /* Aggregate function with DISTINCT keyword */
9732 #define EP_VarSelect  0x0020  /* pSelect is correlated, not constant */
9733 #define EP_DblQuoted  0x0040  /* token.z was originally in "..." */
9734 #define EP_InfixFunc  0x0080  /* True for an infix function: LIKE, GLOB, etc */
9735 #define EP_ExpCollate 0x0100  /* Collating sequence specified explicitly */
9736 #define EP_FixedDest  0x0200  /* Result needed in a specific register */
9737 #define EP_IntValue   0x0400  /* Integer value contained in u.iValue */
9738 #define EP_xIsSelect  0x0800  /* x.pSelect is valid (otherwise x.pList is) */
9739
9740 #define EP_Reduced    0x1000  /* Expr struct is EXPR_REDUCEDSIZE bytes only */
9741 #define EP_TokenOnly  0x2000  /* Expr struct is EXPR_TOKENONLYSIZE bytes only */
9742 #define EP_Static     0x4000  /* Held in memory not obtained from malloc() */
9743
9744 /*
9745 ** The following are the meanings of bits in the Expr.flags2 field.
9746 */
9747 #define EP2_MallocedToken  0x0001  /* Need to sqlite3DbFree() Expr.zToken */
9748 #define EP2_Irreducible    0x0002  /* Cannot EXPRDUP_REDUCE this Expr */
9749
9750 /*
9751 ** The pseudo-routine sqlite3ExprSetIrreducible sets the EP2_Irreducible
9752 ** flag on an expression structure.  This flag is used for VV&A only.  The
9753 ** routine is implemented as a macro that only works when in debugging mode,
9754 ** so as not to burden production code.
9755 */
9756 #ifdef SQLITE_DEBUG
9757 # define ExprSetIrreducible(X)  (X)->flags2 |= EP2_Irreducible
9758 #else
9759 # define ExprSetIrreducible(X)
9760 #endif
9761
9762 /*
9763 ** These macros can be used to test, set, or clear bits in the 
9764 ** Expr.flags field.
9765 */
9766 #define ExprHasProperty(E,P)     (((E)->flags&(P))==(P))
9767 #define ExprHasAnyProperty(E,P)  (((E)->flags&(P))!=0)
9768 #define ExprSetProperty(E,P)     (E)->flags|=(P)
9769 #define ExprClearProperty(E,P)   (E)->flags&=~(P)
9770
9771 /*
9772 ** Macros to determine the number of bytes required by a normal Expr 
9773 ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags 
9774 ** and an Expr struct with the EP_TokenOnly flag set.
9775 */
9776 #define EXPR_FULLSIZE           sizeof(Expr)           /* Full size */
9777 #define EXPR_REDUCEDSIZE        offsetof(Expr,iTable)  /* Common features */
9778 #define EXPR_TOKENONLYSIZE      offsetof(Expr,pLeft)   /* Fewer features */
9779
9780 /*
9781 ** Flags passed to the sqlite3ExprDup() function. See the header comment 
9782 ** above sqlite3ExprDup() for details.
9783 */
9784 #define EXPRDUP_REDUCE         0x0001  /* Used reduced-size Expr nodes */
9785
9786 /*
9787 ** A list of expressions.  Each expression may optionally have a
9788 ** name.  An expr/name combination can be used in several ways, such
9789 ** as the list of "expr AS ID" fields following a "SELECT" or in the
9790 ** list of "ID = expr" items in an UPDATE.  A list of expressions can
9791 ** also be used as the argument to a function, in which case the a.zName
9792 ** field is not used.
9793 */
9794 struct ExprList {
9795   int nExpr;             /* Number of expressions on the list */
9796   int nAlloc;            /* Number of entries allocated below */
9797   int iECursor;          /* VDBE Cursor associated with this ExprList */
9798   struct ExprList_item {
9799     Expr *pExpr;           /* The list of expressions */
9800     char *zName;           /* Token associated with this expression */
9801     char *zSpan;           /* Original text of the expression */
9802     u8 sortOrder;          /* 1 for DESC or 0 for ASC */
9803     u8 done;               /* A flag to indicate when processing is finished */
9804     u16 iCol;              /* For ORDER BY, column number in result set */
9805     u16 iAlias;            /* Index into Parse.aAlias[] for zName */
9806   } *a;                  /* One entry for each expression */
9807 };
9808
9809 /*
9810 ** An instance of this structure is used by the parser to record both
9811 ** the parse tree for an expression and the span of input text for an
9812 ** expression.
9813 */
9814 struct ExprSpan {
9815   Expr *pExpr;          /* The expression parse tree */
9816   const char *zStart;   /* First character of input text */
9817   const char *zEnd;     /* One character past the end of input text */
9818 };
9819
9820 /*
9821 ** An instance of this structure can hold a simple list of identifiers,
9822 ** such as the list "a,b,c" in the following statements:
9823 **
9824 **      INSERT INTO t(a,b,c) VALUES ...;
9825 **      CREATE INDEX idx ON t(a,b,c);
9826 **      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
9827 **
9828 ** The IdList.a.idx field is used when the IdList represents the list of
9829 ** column names after a table name in an INSERT statement.  In the statement
9830 **
9831 **     INSERT INTO t(a,b,c) ...
9832 **
9833 ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
9834 */
9835 struct IdList {
9836   struct IdList_item {
9837     char *zName;      /* Name of the identifier */
9838     int idx;          /* Index in some Table.aCol[] of a column named zName */
9839   } *a;
9840   int nId;         /* Number of identifiers on the list */
9841   int nAlloc;      /* Number of entries allocated for a[] below */
9842 };
9843
9844 /*
9845 ** The bitmask datatype defined below is used for various optimizations.
9846 **
9847 ** Changing this from a 64-bit to a 32-bit type limits the number of
9848 ** tables in a join to 32 instead of 64.  But it also reduces the size
9849 ** of the library by 738 bytes on ix86.
9850 */
9851 typedef u64 Bitmask;
9852
9853 /*
9854 ** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
9855 */
9856 #define BMS  ((int)(sizeof(Bitmask)*8))
9857
9858 /*
9859 ** The following structure describes the FROM clause of a SELECT statement.
9860 ** Each table or subquery in the FROM clause is a separate element of
9861 ** the SrcList.a[] array.
9862 **
9863 ** With the addition of multiple database support, the following structure
9864 ** can also be used to describe a particular table such as the table that
9865 ** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
9866 ** such a table must be a simple name: ID.  But in SQLite, the table can
9867 ** now be identified by a database name, a dot, then the table name: ID.ID.
9868 **
9869 ** The jointype starts out showing the join type between the current table
9870 ** and the next table on the list.  The parser builds the list this way.
9871 ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
9872 ** jointype expresses the join between the table and the previous table.
9873 **
9874 ** In the colUsed field, the high-order bit (bit 63) is set if the table
9875 ** contains more than 63 columns and the 64-th or later column is used.
9876 */
9877 struct SrcList {
9878   i16 nSrc;        /* Number of tables or subqueries in the FROM clause */
9879   i16 nAlloc;      /* Number of entries allocated in a[] below */
9880   struct SrcList_item {
9881     char *zDatabase;  /* Name of database holding this table */
9882     char *zName;      /* Name of the table */
9883     char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
9884     Table *pTab;      /* An SQL table corresponding to zName */
9885     Select *pSelect;  /* A SELECT statement used in place of a table name */
9886     u8 isPopulated;   /* Temporary table associated with SELECT is populated */
9887     u8 jointype;      /* Type of join between this able and the previous */
9888     u8 notIndexed;    /* True if there is a NOT INDEXED clause */
9889     int iCursor;      /* The VDBE cursor number used to access this table */
9890     Expr *pOn;        /* The ON clause of a join */
9891     IdList *pUsing;   /* The USING clause of a join */
9892     Bitmask colUsed;  /* Bit N (1<<N) set if column N of pTab is used */
9893     char *zIndex;     /* Identifier from "INDEXED BY <zIndex>" clause */
9894     Index *pIndex;    /* Index structure corresponding to zIndex, if any */
9895   } a[1];             /* One entry for each identifier on the list */
9896 };
9897
9898 /*
9899 ** Permitted values of the SrcList.a.jointype field
9900 */
9901 #define JT_INNER     0x0001    /* Any kind of inner or cross join */
9902 #define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */
9903 #define JT_NATURAL   0x0004    /* True for a "natural" join */
9904 #define JT_LEFT      0x0008    /* Left outer join */
9905 #define JT_RIGHT     0x0010    /* Right outer join */
9906 #define JT_OUTER     0x0020    /* The "OUTER" keyword is present */
9907 #define JT_ERROR     0x0040    /* unknown or unsupported join type */
9908
9909
9910 /*
9911 ** A WherePlan object holds information that describes a lookup
9912 ** strategy.
9913 **
9914 ** This object is intended to be opaque outside of the where.c module.
9915 ** It is included here only so that that compiler will know how big it
9916 ** is.  None of the fields in this object should be used outside of
9917 ** the where.c module.
9918 **
9919 ** Within the union, pIdx is only used when wsFlags&WHERE_INDEXED is true.
9920 ** pTerm is only used when wsFlags&WHERE_MULTI_OR is true.  And pVtabIdx
9921 ** is only used when wsFlags&WHERE_VIRTUALTABLE is true.  It is never the
9922 ** case that more than one of these conditions is true.
9923 */
9924 struct WherePlan {
9925   u32 wsFlags;                   /* WHERE_* flags that describe the strategy */
9926   u32 nEq;                       /* Number of == constraints */
9927   union {
9928     Index *pIdx;                   /* Index when WHERE_INDEXED is true */
9929     struct WhereTerm *pTerm;       /* WHERE clause term for OR-search */
9930     sqlite3_index_info *pVtabIdx;  /* Virtual table index to use */
9931   } u;
9932 };
9933
9934 /*
9935 ** For each nested loop in a WHERE clause implementation, the WhereInfo
9936 ** structure contains a single instance of this structure.  This structure
9937 ** is intended to be private the the where.c module and should not be
9938 ** access or modified by other modules.
9939 **
9940 ** The pIdxInfo field is used to help pick the best index on a
9941 ** virtual table.  The pIdxInfo pointer contains indexing
9942 ** information for the i-th table in the FROM clause before reordering.
9943 ** All the pIdxInfo pointers are freed by whereInfoFree() in where.c.
9944 ** All other information in the i-th WhereLevel object for the i-th table
9945 ** after FROM clause ordering.
9946 */
9947 struct WhereLevel {
9948   WherePlan plan;       /* query plan for this element of the FROM clause */
9949   int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
9950   int iTabCur;          /* The VDBE cursor used to access the table */
9951   int iIdxCur;          /* The VDBE cursor used to access pIdx */
9952   int addrBrk;          /* Jump here to break out of the loop */
9953   int addrNxt;          /* Jump here to start the next IN combination */
9954   int addrCont;         /* Jump here to continue with the next loop cycle */
9955   int addrFirst;        /* First instruction of interior of the loop */
9956   u8 iFrom;             /* Which entry in the FROM clause */
9957   u8 op, p5;            /* Opcode and P5 of the opcode that ends the loop */
9958   int p1, p2;           /* Operands of the opcode used to ends the loop */
9959   union {               /* Information that depends on plan.wsFlags */
9960     struct {
9961       int nIn;              /* Number of entries in aInLoop[] */
9962       struct InLoop {
9963         int iCur;              /* The VDBE cursor used by this IN operator */
9964         int addrInTop;         /* Top of the IN loop */
9965       } *aInLoop;           /* Information about each nested IN operator */
9966     } in;                 /* Used when plan.wsFlags&WHERE_IN_ABLE */
9967   } u;
9968
9969   /* The following field is really not part of the current level.  But
9970   ** we need a place to cache virtual table index information for each
9971   ** virtual table in the FROM clause and the WhereLevel structure is
9972   ** a convenient place since there is one WhereLevel for each FROM clause
9973   ** element.
9974   */
9975   sqlite3_index_info *pIdxInfo;  /* Index info for n-th source table */
9976 };
9977
9978 /*
9979 ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
9980 ** and the WhereInfo.wctrlFlags member.
9981 */
9982 #define WHERE_ORDERBY_NORMAL   0x0000 /* No-op */
9983 #define WHERE_ORDERBY_MIN      0x0001 /* ORDER BY processing for min() func */
9984 #define WHERE_ORDERBY_MAX      0x0002 /* ORDER BY processing for max() func */
9985 #define WHERE_ONEPASS_DESIRED  0x0004 /* Want to do one-pass UPDATE/DELETE */
9986 #define WHERE_DUPLICATES_OK    0x0008 /* Ok to return a row more than once */
9987 #define WHERE_OMIT_OPEN        0x0010 /* Table cursors are already open */
9988 #define WHERE_OMIT_CLOSE       0x0020 /* Omit close of table & index cursors */
9989 #define WHERE_FORCE_TABLE      0x0040 /* Do not use an index-only search */
9990 #define WHERE_ONETABLE_ONLY    0x0080 /* Only code the 1st table in pTabList */
9991
9992 /*
9993 ** The WHERE clause processing routine has two halves.  The
9994 ** first part does the start of the WHERE loop and the second
9995 ** half does the tail of the WHERE loop.  An instance of
9996 ** this structure is returned by the first half and passed
9997 ** into the second half to give some continuity.
9998 */
9999 struct WhereInfo {
10000   Parse *pParse;       /* Parsing and code generating context */
10001   u16 wctrlFlags;      /* Flags originally passed to sqlite3WhereBegin() */
10002   u8 okOnePass;        /* Ok to use one-pass algorithm for UPDATE or DELETE */
10003   u8 untestedTerms;    /* Not all WHERE terms resolved by outer loop */
10004   SrcList *pTabList;             /* List of tables in the join */
10005   int iTop;                      /* The very beginning of the WHERE loop */
10006   int iContinue;                 /* Jump here to continue with next record */
10007   int iBreak;                    /* Jump here to break out of the loop */
10008   int nLevel;                    /* Number of nested loop */
10009   struct WhereClause *pWC;       /* Decomposition of the WHERE clause */
10010   double savedNQueryLoop;        /* pParse->nQueryLoop outside the WHERE loop */
10011   WhereLevel a[1];               /* Information about each nest loop in WHERE */
10012 };
10013
10014 /*
10015 ** A NameContext defines a context in which to resolve table and column
10016 ** names.  The context consists of a list of tables (the pSrcList) field and
10017 ** a list of named expression (pEList).  The named expression list may
10018 ** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
10019 ** to the table being operated on by INSERT, UPDATE, or DELETE.  The
10020 ** pEList corresponds to the result set of a SELECT and is NULL for
10021 ** other statements.
10022 **
10023 ** NameContexts can be nested.  When resolving names, the inner-most 
10024 ** context is searched first.  If no match is found, the next outer
10025 ** context is checked.  If there is still no match, the next context
10026 ** is checked.  This process continues until either a match is found
10027 ** or all contexts are check.  When a match is found, the nRef member of
10028 ** the context containing the match is incremented. 
10029 **
10030 ** Each subquery gets a new NameContext.  The pNext field points to the
10031 ** NameContext in the parent query.  Thus the process of scanning the
10032 ** NameContext list corresponds to searching through successively outer
10033 ** subqueries looking for a match.
10034 */
10035 struct NameContext {
10036   Parse *pParse;       /* The parser */
10037   SrcList *pSrcList;   /* One or more tables used to resolve names */
10038   ExprList *pEList;    /* Optional list of named expressions */
10039   int nRef;            /* Number of names resolved by this context */
10040   int nErr;            /* Number of errors encountered while resolving names */
10041   u8 allowAgg;         /* Aggregate functions allowed here */
10042   u8 hasAgg;           /* True if aggregates are seen */
10043   u8 isCheck;          /* True if resolving names in a CHECK constraint */
10044   int nDepth;          /* Depth of subquery recursion. 1 for no recursion */
10045   AggInfo *pAggInfo;   /* Information about aggregates at this level */
10046   NameContext *pNext;  /* Next outer name context.  NULL for outermost */
10047 };
10048
10049 /*
10050 ** An instance of the following structure contains all information
10051 ** needed to generate code for a single SELECT statement.
10052 **
10053 ** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
10054 ** If there is a LIMIT clause, the parser sets nLimit to the value of the
10055 ** limit and nOffset to the value of the offset (or 0 if there is not
10056 ** offset).  But later on, nLimit and nOffset become the memory locations
10057 ** in the VDBE that record the limit and offset counters.
10058 **
10059 ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
10060 ** These addresses must be stored so that we can go back and fill in
10061 ** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
10062 ** the number of columns in P2 can be computed at the same time
10063 ** as the OP_OpenEphm instruction is coded because not
10064 ** enough information about the compound query is known at that point.
10065 ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
10066 ** for the result set.  The KeyInfo for addrOpenTran[2] contains collating
10067 ** sequences for the ORDER BY clause.
10068 */
10069 struct Select {
10070   ExprList *pEList;      /* The fields of the result */
10071   u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
10072   char affinity;         /* MakeRecord with this affinity for SRT_Set */
10073   u16 selFlags;          /* Various SF_* values */
10074   SrcList *pSrc;         /* The FROM clause */
10075   Expr *pWhere;          /* The WHERE clause */
10076   ExprList *pGroupBy;    /* The GROUP BY clause */
10077   Expr *pHaving;         /* The HAVING clause */
10078   ExprList *pOrderBy;    /* The ORDER BY clause */
10079   Select *pPrior;        /* Prior select in a compound select statement */
10080   Select *pNext;         /* Next select to the left in a compound */
10081   Select *pRightmost;    /* Right-most select in a compound select statement */
10082   Expr *pLimit;          /* LIMIT expression. NULL means not used. */
10083   Expr *pOffset;         /* OFFSET expression. NULL means not used. */
10084   int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
10085   int addrOpenEphm[3];   /* OP_OpenEphem opcodes related to this select */
10086 };
10087
10088 /*
10089 ** Allowed values for Select.selFlags.  The "SF" prefix stands for
10090 ** "Select Flag".
10091 */
10092 #define SF_Distinct        0x0001  /* Output should be DISTINCT */
10093 #define SF_Resolved        0x0002  /* Identifiers have been resolved */
10094 #define SF_Aggregate       0x0004  /* Contains aggregate functions */
10095 #define SF_UsesEphemeral   0x0008  /* Uses the OpenEphemeral opcode */
10096 #define SF_Expanded        0x0010  /* sqlite3SelectExpand() called on this */
10097 #define SF_HasTypeInfo     0x0020  /* FROM subqueries have Table metadata */
10098
10099
10100 /*
10101 ** The results of a select can be distributed in several ways.  The
10102 ** "SRT" prefix means "SELECT Result Type".
10103 */
10104 #define SRT_Union        1  /* Store result as keys in an index */
10105 #define SRT_Except       2  /* Remove result from a UNION index */
10106 #define SRT_Exists       3  /* Store 1 if the result is not empty */
10107 #define SRT_Discard      4  /* Do not save the results anywhere */
10108
10109 /* The ORDER BY clause is ignored for all of the above */
10110 #define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard)
10111
10112 #define SRT_Output       5  /* Output each row of result */
10113 #define SRT_Mem          6  /* Store result in a memory cell */
10114 #define SRT_Set          7  /* Store results as keys in an index */
10115 #define SRT_Table        8  /* Store result as data with an automatic rowid */
10116 #define SRT_EphemTab     9  /* Create transient tab and store like SRT_Table */
10117 #define SRT_Coroutine   10  /* Generate a single row of result */
10118
10119 /*
10120 ** A structure used to customize the behavior of sqlite3Select(). See
10121 ** comments above sqlite3Select() for details.
10122 */
10123 typedef struct SelectDest SelectDest;
10124 struct SelectDest {
10125   u8 eDest;         /* How to dispose of the results */
10126   u8 affinity;      /* Affinity used when eDest==SRT_Set */
10127   int iParm;        /* A parameter used by the eDest disposal method */
10128   int iMem;         /* Base register where results are written */
10129   int nMem;         /* Number of registers allocated */
10130 };
10131
10132 /*
10133 ** During code generation of statements that do inserts into AUTOINCREMENT 
10134 ** tables, the following information is attached to the Table.u.autoInc.p
10135 ** pointer of each autoincrement table to record some side information that
10136 ** the code generator needs.  We have to keep per-table autoincrement
10137 ** information in case inserts are down within triggers.  Triggers do not
10138 ** normally coordinate their activities, but we do need to coordinate the
10139 ** loading and saving of autoincrement information.
10140 */
10141 struct AutoincInfo {
10142   AutoincInfo *pNext;   /* Next info block in a list of them all */
10143   Table *pTab;          /* Table this info block refers to */
10144   int iDb;              /* Index in sqlite3.aDb[] of database holding pTab */
10145   int regCtr;           /* Memory register holding the rowid counter */
10146 };
10147
10148 /*
10149 ** Size of the column cache
10150 */
10151 #ifndef SQLITE_N_COLCACHE
10152 # define SQLITE_N_COLCACHE 10
10153 #endif
10154
10155 /*
10156 ** At least one instance of the following structure is created for each 
10157 ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
10158 ** statement. All such objects are stored in the linked list headed at
10159 ** Parse.pTriggerPrg and deleted once statement compilation has been
10160 ** completed.
10161 **
10162 ** A Vdbe sub-program that implements the body and WHEN clause of trigger
10163 ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
10164 ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
10165 ** The Parse.pTriggerPrg list never contains two entries with the same
10166 ** values for both pTrigger and orconf.
10167 **
10168 ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
10169 ** accessed (or set to 0 for triggers fired as a result of INSERT 
10170 ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
10171 ** a mask of new.* columns used by the program.
10172 */
10173 struct TriggerPrg {
10174   Trigger *pTrigger;      /* Trigger this program was coded from */
10175   int orconf;             /* Default ON CONFLICT policy */
10176   SubProgram *pProgram;   /* Program implementing pTrigger/orconf */
10177   u32 aColmask[2];        /* Masks of old.*, new.* columns accessed */
10178   TriggerPrg *pNext;      /* Next entry in Parse.pTriggerPrg list */
10179 };
10180
10181 /*
10182 ** An SQL parser context.  A copy of this structure is passed through
10183 ** the parser and down into all the parser action routine in order to
10184 ** carry around information that is global to the entire parse.
10185 **
10186 ** The structure is divided into two parts.  When the parser and code
10187 ** generate call themselves recursively, the first part of the structure
10188 ** is constant but the second part is reset at the beginning and end of
10189 ** each recursion.
10190 **
10191 ** The nTableLock and aTableLock variables are only used if the shared-cache 
10192 ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
10193 ** used to store the set of table-locks required by the statement being
10194 ** compiled. Function sqlite3TableLock() is used to add entries to the
10195 ** list.
10196 */
10197 struct Parse {
10198   sqlite3 *db;         /* The main database structure */
10199   int rc;              /* Return code from execution */
10200   char *zErrMsg;       /* An error message */
10201   Vdbe *pVdbe;         /* An engine for executing database bytecode */
10202   u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
10203   u8 nameClash;        /* A permanent table name clashes with temp table name */
10204   u8 checkSchema;      /* Causes schema cookie check after an error */
10205   u8 nested;           /* Number of nested calls to the parser/code generator */
10206   u8 parseError;       /* True after a parsing error.  Ticket #1794 */
10207   u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
10208   u8 nTempInUse;       /* Number of aTempReg[] currently checked out */
10209   int aTempReg[8];     /* Holding area for temporary registers */
10210   int nRangeReg;       /* Size of the temporary register block */
10211   int iRangeReg;       /* First register in temporary register block */
10212   int nErr;            /* Number of errors seen */
10213   int nTab;            /* Number of previously allocated VDBE cursors */
10214   int nMem;            /* Number of memory cells used so far */
10215   int nSet;            /* Number of sets used so far */
10216   int ckBase;          /* Base register of data during check constraints */
10217   int iCacheLevel;     /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
10218   int iCacheCnt;       /* Counter used to generate aColCache[].lru values */
10219   u8 nColCache;        /* Number of entries in the column cache */
10220   u8 iColCache;        /* Next entry of the cache to replace */
10221   struct yColCache {
10222     int iTable;           /* Table cursor number */
10223     int iColumn;          /* Table column number */
10224     u8 tempReg;           /* iReg is a temp register that needs to be freed */
10225     int iLevel;           /* Nesting level */
10226     int iReg;             /* Reg with value of this column. 0 means none. */
10227     int lru;              /* Least recently used entry has the smallest value */
10228   } aColCache[SQLITE_N_COLCACHE];  /* One for each column cache entry */
10229   u32 writeMask;       /* Start a write transaction on these databases */
10230   u32 cookieMask;      /* Bitmask of schema verified databases */
10231   u8 isMultiWrite;     /* True if statement may affect/insert multiple rows */
10232   u8 mayAbort;         /* True if statement may throw an ABORT exception */
10233   int cookieGoto;      /* Address of OP_Goto to cookie verifier subroutine */
10234   int cookieValue[SQLITE_MAX_ATTACHED+2];  /* Values of cookies to verify */
10235 #ifndef SQLITE_OMIT_SHARED_CACHE
10236   int nTableLock;        /* Number of locks in aTableLock */
10237   TableLock *aTableLock; /* Required table locks for shared-cache mode */
10238 #endif
10239   int regRowid;        /* Register holding rowid of CREATE TABLE entry */
10240   int regRoot;         /* Register holding root page number for new objects */
10241   AutoincInfo *pAinc;  /* Information about AUTOINCREMENT counters */
10242   int nMaxArg;         /* Max args passed to user function by sub-program */
10243
10244   /* Information used while coding trigger programs. */
10245   Parse *pToplevel;    /* Parse structure for main program (or NULL) */
10246   Table *pTriggerTab;  /* Table triggers are being coded for */
10247   u32 oldmask;         /* Mask of old.* columns referenced */
10248   u32 newmask;         /* Mask of new.* columns referenced */
10249   u8 eTriggerOp;       /* TK_UPDATE, TK_INSERT or TK_DELETE */
10250   u8 eOrconf;          /* Default ON CONFLICT policy for trigger steps */
10251   u8 disableTriggers;  /* True to disable triggers */
10252   double nQueryLoop;   /* Estimated number of iterations of a query */
10253
10254   /* Above is constant between recursions.  Below is reset before and after
10255   ** each recursion */
10256
10257   int nVar;            /* Number of '?' variables seen in the SQL so far */
10258   int nVarExpr;        /* Number of used slots in apVarExpr[] */
10259   int nVarExprAlloc;   /* Number of allocated slots in apVarExpr[] */
10260   Expr **apVarExpr;    /* Pointers to :aaa and $aaaa wildcard expressions */
10261   Vdbe *pReprepare;    /* VM being reprepared (sqlite3Reprepare()) */
10262   int nAlias;          /* Number of aliased result set columns */
10263   int nAliasAlloc;     /* Number of allocated slots for aAlias[] */
10264   int *aAlias;         /* Register used to hold aliased result */
10265   u8 explain;          /* True if the EXPLAIN flag is found on the query */
10266   Token sNameToken;    /* Token with unqualified schema object name */
10267   Token sLastToken;    /* The last token parsed */
10268   const char *zTail;   /* All SQL text past the last semicolon parsed */
10269   Table *pNewTable;    /* A table being constructed by CREATE TABLE */
10270   Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
10271   const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
10272 #ifndef SQLITE_OMIT_VIRTUALTABLE
10273   Token sArg;                /* Complete text of a module argument */
10274   u8 declareVtab;            /* True if inside sqlite3_declare_vtab() */
10275   int nVtabLock;             /* Number of virtual tables to lock */
10276   Table **apVtabLock;        /* Pointer to virtual tables needing locking */
10277 #endif
10278   int nHeight;            /* Expression tree height of current sub-select */
10279   Table *pZombieTab;      /* List of Table objects to delete after code gen */
10280   TriggerPrg *pTriggerPrg;    /* Linked list of coded triggers */
10281 };
10282
10283 #ifdef SQLITE_OMIT_VIRTUALTABLE
10284   #define IN_DECLARE_VTAB 0
10285 #else
10286   #define IN_DECLARE_VTAB (pParse->declareVtab)
10287 #endif
10288
10289 /*
10290 ** An instance of the following structure can be declared on a stack and used
10291 ** to save the Parse.zAuthContext value so that it can be restored later.
10292 */
10293 struct AuthContext {
10294   const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
10295   Parse *pParse;              /* The Parse structure */
10296 };
10297
10298 /*
10299 ** Bitfield flags for P5 value in OP_Insert and OP_Delete
10300 */
10301 #define OPFLAG_NCHANGE       0x01    /* Set to update db->nChange */
10302 #define OPFLAG_LASTROWID     0x02    /* Set to update db->lastRowid */
10303 #define OPFLAG_ISUPDATE      0x04    /* This OP_Insert is an sql UPDATE */
10304 #define OPFLAG_APPEND        0x08    /* This is likely to be an append */
10305 #define OPFLAG_USESEEKRESULT 0x10    /* Try to avoid a seek in BtreeInsert() */
10306 #define OPFLAG_CLEARCACHE    0x20    /* Clear pseudo-table cache in OP_Column */
10307
10308 /*
10309  * Each trigger present in the database schema is stored as an instance of
10310  * struct Trigger. 
10311  *
10312  * Pointers to instances of struct Trigger are stored in two ways.
10313  * 1. In the "trigHash" hash table (part of the sqlite3* that represents the 
10314  *    database). This allows Trigger structures to be retrieved by name.
10315  * 2. All triggers associated with a single table form a linked list, using the
10316  *    pNext member of struct Trigger. A pointer to the first element of the
10317  *    linked list is stored as the "pTrigger" member of the associated
10318  *    struct Table.
10319  *
10320  * The "step_list" member points to the first element of a linked list
10321  * containing the SQL statements specified as the trigger program.
10322  */
10323 struct Trigger {
10324   char *zName;            /* The name of the trigger                        */
10325   char *table;            /* The table or view to which the trigger applies */
10326   u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
10327   u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
10328   Expr *pWhen;            /* The WHEN clause of the expression (may be NULL) */
10329   IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
10330                              the <column-list> is stored here */
10331   Schema *pSchema;        /* Schema containing the trigger */
10332   Schema *pTabSchema;     /* Schema containing the table */
10333   TriggerStep *step_list; /* Link list of trigger program steps             */
10334   Trigger *pNext;         /* Next trigger associated with the table */
10335 };
10336
10337 /*
10338 ** A trigger is either a BEFORE or an AFTER trigger.  The following constants
10339 ** determine which. 
10340 **
10341 ** If there are multiple triggers, you might of some BEFORE and some AFTER.
10342 ** In that cases, the constants below can be ORed together.
10343 */
10344 #define TRIGGER_BEFORE  1
10345 #define TRIGGER_AFTER   2
10346
10347 /*
10348  * An instance of struct TriggerStep is used to store a single SQL statement
10349  * that is a part of a trigger-program. 
10350  *
10351  * Instances of struct TriggerStep are stored in a singly linked list (linked
10352  * using the "pNext" member) referenced by the "step_list" member of the 
10353  * associated struct Trigger instance. The first element of the linked list is
10354  * the first step of the trigger-program.
10355  * 
10356  * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
10357  * "SELECT" statement. The meanings of the other members is determined by the 
10358  * value of "op" as follows:
10359  *
10360  * (op == TK_INSERT)
10361  * orconf    -> stores the ON CONFLICT algorithm
10362  * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
10363  *              this stores a pointer to the SELECT statement. Otherwise NULL.
10364  * target    -> A token holding the quoted name of the table to insert into.
10365  * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
10366  *              this stores values to be inserted. Otherwise NULL.
10367  * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ... 
10368  *              statement, then this stores the column-names to be
10369  *              inserted into.
10370  *
10371  * (op == TK_DELETE)
10372  * target    -> A token holding the quoted name of the table to delete from.
10373  * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
10374  *              Otherwise NULL.
10375  * 
10376  * (op == TK_UPDATE)
10377  * target    -> A token holding the quoted name of the table to update rows of.
10378  * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
10379  *              Otherwise NULL.
10380  * pExprList -> A list of the columns to update and the expressions to update
10381  *              them to. See sqlite3Update() documentation of "pChanges"
10382  *              argument.
10383  * 
10384  */
10385 struct TriggerStep {
10386   u8 op;               /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
10387   u8 orconf;           /* OE_Rollback etc. */
10388   Trigger *pTrig;      /* The trigger that this step is a part of */
10389   Select *pSelect;     /* SELECT statment or RHS of INSERT INTO .. SELECT ... */
10390   Token target;        /* Target table for DELETE, UPDATE, INSERT */
10391   Expr *pWhere;        /* The WHERE clause for DELETE or UPDATE steps */
10392   ExprList *pExprList; /* SET clause for UPDATE.  VALUES clause for INSERT */
10393   IdList *pIdList;     /* Column names for INSERT */
10394   TriggerStep *pNext;  /* Next in the link-list */
10395   TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
10396 };
10397
10398 /*
10399 ** The following structure contains information used by the sqliteFix...
10400 ** routines as they walk the parse tree to make database references
10401 ** explicit.  
10402 */
10403 typedef struct DbFixer DbFixer;
10404 struct DbFixer {
10405   Parse *pParse;      /* The parsing context.  Error messages written here */
10406   const char *zDb;    /* Make sure all objects are contained in this database */
10407   const char *zType;  /* Type of the container - used for error messages */
10408   const Token *pName; /* Name of the container - used for error messages */
10409 };
10410
10411 /*
10412 ** An objected used to accumulate the text of a string where we
10413 ** do not necessarily know how big the string will be in the end.
10414 */
10415 struct StrAccum {
10416   sqlite3 *db;         /* Optional database for lookaside.  Can be NULL */
10417   char *zBase;         /* A base allocation.  Not from malloc. */
10418   char *zText;         /* The string collected so far */
10419   int  nChar;          /* Length of the string so far */
10420   int  nAlloc;         /* Amount of space allocated in zText */
10421   int  mxAlloc;        /* Maximum allowed string length */
10422   u8   mallocFailed;   /* Becomes true if any memory allocation fails */
10423   u8   useMalloc;      /* 0: none,  1: sqlite3DbMalloc,  2: sqlite3_malloc */
10424   u8   tooBig;         /* Becomes true if string size exceeds limits */
10425 };
10426
10427 /*
10428 ** A pointer to this structure is used to communicate information
10429 ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
10430 */
10431 typedef struct {
10432   sqlite3 *db;        /* The database being initialized */
10433   int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
10434   char **pzErrMsg;    /* Error message stored here */
10435   int rc;             /* Result code stored here */
10436 } InitData;
10437
10438 /*
10439 ** Structure containing global configuration data for the SQLite library.
10440 **
10441 ** This structure also contains some state information.
10442 */
10443 struct Sqlite3Config {
10444   int bMemstat;                     /* True to enable memory status */
10445   int bCoreMutex;                   /* True to enable core mutexing */
10446   int bFullMutex;                   /* True to enable full mutexing */
10447   int mxStrlen;                     /* Maximum string length */
10448   int szLookaside;                  /* Default lookaside buffer size */
10449   int nLookaside;                   /* Default lookaside buffer count */
10450   sqlite3_mem_methods m;            /* Low-level memory allocation interface */
10451   sqlite3_mutex_methods mutex;      /* Low-level mutex interface */
10452   sqlite3_pcache_methods pcache;    /* Low-level page-cache interface */
10453   void *pHeap;                      /* Heap storage space */
10454   int nHeap;                        /* Size of pHeap[] */
10455   int mnReq, mxReq;                 /* Min and max heap requests sizes */
10456   void *pScratch;                   /* Scratch memory */
10457   int szScratch;                    /* Size of each scratch buffer */
10458   int nScratch;                     /* Number of scratch buffers */
10459   void *pPage;                      /* Page cache memory */
10460   int szPage;                       /* Size of each page in pPage[] */
10461   int nPage;                        /* Number of pages in pPage[] */
10462   int mxParserStack;                /* maximum depth of the parser stack */
10463   int sharedCacheEnabled;           /* true if shared-cache mode enabled */
10464   /* The above might be initialized to non-zero.  The following need to always
10465   ** initially be zero, however. */
10466   int isInit;                       /* True after initialization has finished */
10467   int inProgress;                   /* True while initialization in progress */
10468   int isMutexInit;                  /* True after mutexes are initialized */
10469   int isMallocInit;                 /* True after malloc is initialized */
10470   int isPCacheInit;                 /* True after malloc is initialized */
10471   sqlite3_mutex *pInitMutex;        /* Mutex used by sqlite3_initialize() */
10472   int nRefInitMutex;                /* Number of users of pInitMutex */
10473   void (*xLog)(void*,int,const char*); /* Function for logging */
10474   void *pLogArg;                       /* First argument to xLog() */
10475 };
10476
10477 /*
10478 ** Context pointer passed down through the tree-walk.
10479 */
10480 struct Walker {
10481   int (*xExprCallback)(Walker*, Expr*);     /* Callback for expressions */
10482   int (*xSelectCallback)(Walker*,Select*);  /* Callback for SELECTs */
10483   Parse *pParse;                            /* Parser context.  */
10484   union {                                   /* Extra data for callback */
10485     NameContext *pNC;                          /* Naming context */
10486     int i;                                     /* Integer value */
10487   } u;
10488 };
10489
10490 /* Forward declarations */
10491 SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
10492 SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
10493 SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
10494 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
10495 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
10496
10497 /*
10498 ** Return code from the parse-tree walking primitives and their
10499 ** callbacks.
10500 */
10501 #define WRC_Continue    0   /* Continue down into children */
10502 #define WRC_Prune       1   /* Omit children but continue walking siblings */
10503 #define WRC_Abort       2   /* Abandon the tree walk */
10504
10505 /*
10506 ** Assuming zIn points to the first byte of a UTF-8 character,
10507 ** advance zIn to point to the first byte of the next UTF-8 character.
10508 */
10509 #define SQLITE_SKIP_UTF8(zIn) {                        \
10510   if( (*(zIn++))>=0xc0 ){                              \
10511     while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \
10512   }                                                    \
10513 }
10514
10515 /*
10516 ** The SQLITE_*_BKPT macros are substitutes for the error codes with
10517 ** the same name but without the _BKPT suffix.  These macros invoke
10518 ** routines that report the line-number on which the error originated
10519 ** using sqlite3_log().  The routines also provide a convenient place
10520 ** to set a debugger breakpoint.
10521 */
10522 SQLITE_PRIVATE int sqlite3CorruptError(int);
10523 SQLITE_PRIVATE int sqlite3MisuseError(int);
10524 SQLITE_PRIVATE int sqlite3CantopenError(int);
10525 #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
10526 #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
10527 #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
10528
10529
10530 /*
10531 ** FTS4 is really an extension for FTS3.  It is enabled using the
10532 ** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also all
10533 ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
10534 */
10535 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
10536 # define SQLITE_ENABLE_FTS3
10537 #endif
10538
10539 /*
10540 ** The ctype.h header is needed for non-ASCII systems.  It is also
10541 ** needed by FTS3 when FTS3 is included in the amalgamation.
10542 */
10543 #if !defined(SQLITE_ASCII) || \
10544     (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
10545 # include <ctype.h>
10546 #endif
10547
10548 /*
10549 ** The following macros mimic the standard library functions toupper(),
10550 ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
10551 ** sqlite versions only work for ASCII characters, regardless of locale.
10552 */
10553 #ifdef SQLITE_ASCII
10554 # define sqlite3Toupper(x)  ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
10555 # define sqlite3Isspace(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
10556 # define sqlite3Isalnum(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
10557 # define sqlite3Isalpha(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
10558 # define sqlite3Isdigit(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
10559 # define sqlite3Isxdigit(x)  (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
10560 # define sqlite3Tolower(x)   (sqlite3UpperToLower[(unsigned char)(x)])
10561 #else
10562 # define sqlite3Toupper(x)   toupper((unsigned char)(x))
10563 # define sqlite3Isspace(x)   isspace((unsigned char)(x))
10564 # define sqlite3Isalnum(x)   isalnum((unsigned char)(x))
10565 # define sqlite3Isalpha(x)   isalpha((unsigned char)(x))
10566 # define sqlite3Isdigit(x)   isdigit((unsigned char)(x))
10567 # define sqlite3Isxdigit(x)  isxdigit((unsigned char)(x))
10568 # define sqlite3Tolower(x)   tolower((unsigned char)(x))
10569 #endif
10570
10571 /*
10572 ** Internal function prototypes
10573 */
10574 SQLITE_PRIVATE int sqlite3StrICmp(const char *, const char *);
10575 SQLITE_PRIVATE int sqlite3Strlen30(const char*);
10576 #define sqlite3StrNICmp sqlite3_strnicmp
10577
10578 SQLITE_PRIVATE int sqlite3MallocInit(void);
10579 SQLITE_PRIVATE void sqlite3MallocEnd(void);
10580 SQLITE_PRIVATE void *sqlite3Malloc(int);
10581 SQLITE_PRIVATE void *sqlite3MallocZero(int);
10582 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, int);
10583 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, int);
10584 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
10585 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, int);
10586 SQLITE_PRIVATE void *sqlite3Realloc(void*, int);
10587 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
10588 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, int);
10589 SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
10590 SQLITE_PRIVATE int sqlite3MallocSize(void*);
10591 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
10592 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
10593 SQLITE_PRIVATE void sqlite3ScratchFree(void*);
10594 SQLITE_PRIVATE void *sqlite3PageMalloc(int);
10595 SQLITE_PRIVATE void sqlite3PageFree(void*);
10596 SQLITE_PRIVATE void sqlite3MemSetDefault(void);
10597 SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
10598 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
10599
10600 /*
10601 ** On systems with ample stack space and that support alloca(), make
10602 ** use of alloca() to obtain space for large automatic objects.  By default,
10603 ** obtain space from malloc().
10604 **
10605 ** The alloca() routine never returns NULL.  This will cause code paths
10606 ** that deal with sqlite3StackAlloc() failures to be unreachable.
10607 */
10608 #ifdef SQLITE_USE_ALLOCA
10609 # define sqlite3StackAllocRaw(D,N)   alloca(N)
10610 # define sqlite3StackAllocZero(D,N)  memset(alloca(N), 0, N)
10611 # define sqlite3StackFree(D,P)       
10612 #else
10613 # define sqlite3StackAllocRaw(D,N)   sqlite3DbMallocRaw(D,N)
10614 # define sqlite3StackAllocZero(D,N)  sqlite3DbMallocZero(D,N)
10615 # define sqlite3StackFree(D,P)       sqlite3DbFree(D,P)
10616 #endif
10617
10618 #ifdef SQLITE_ENABLE_MEMSYS3
10619 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
10620 #endif
10621 #ifdef SQLITE_ENABLE_MEMSYS5
10622 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
10623 #endif
10624
10625
10626 #ifndef SQLITE_MUTEX_OMIT
10627 SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
10628 SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3NoopMutex(void);
10629 SQLITE_PRIVATE   sqlite3_mutex *sqlite3MutexAlloc(int);
10630 SQLITE_PRIVATE   int sqlite3MutexInit(void);
10631 SQLITE_PRIVATE   int sqlite3MutexEnd(void);
10632 #endif
10633
10634 SQLITE_PRIVATE int sqlite3StatusValue(int);
10635 SQLITE_PRIVATE void sqlite3StatusAdd(int, int);
10636 SQLITE_PRIVATE void sqlite3StatusSet(int, int);
10637
10638 #ifndef SQLITE_OMIT_FLOATING_POINT
10639 SQLITE_PRIVATE   int sqlite3IsNaN(double);
10640 #else
10641 # define sqlite3IsNaN(X)  0
10642 #endif
10643
10644 SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, int, const char*, va_list);
10645 #ifndef SQLITE_OMIT_TRACE
10646 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...);
10647 #endif
10648 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
10649 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
10650 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
10651 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
10652 SQLITE_PRIVATE   void sqlite3DebugPrintf(const char*, ...);
10653 #endif
10654 #if defined(SQLITE_TEST)
10655 SQLITE_PRIVATE   void *sqlite3TestTextToPtr(const char*);
10656 #endif
10657 SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
10658 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
10659 SQLITE_PRIVATE int sqlite3Dequote(char*);
10660 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
10661 SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
10662 SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
10663 SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
10664 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
10665 SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
10666 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
10667 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
10668 SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
10669 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
10670 SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
10671 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
10672 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
10673 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
10674 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
10675 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
10676 SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
10677 SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
10678 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
10679 SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
10680 SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
10681 SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
10682 SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3*, int);
10683 SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
10684 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
10685 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
10686 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
10687 SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
10688 SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
10689 SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
10690 SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
10691 SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
10692 SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
10693 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
10694 SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
10695 SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,Select*);
10696
10697 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
10698 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
10699 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
10700 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
10701 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
10702 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
10703 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
10704
10705 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
10706 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
10707 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
10708 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, u8 iBatch, i64);
10709 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
10710
10711 SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
10712
10713 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
10714 SQLITE_PRIVATE   int sqlite3ViewGetColumnNames(Parse*,Table*);
10715 #else
10716 # define sqlite3ViewGetColumnNames(A,B) 0
10717 #endif
10718
10719 SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
10720 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
10721 #ifndef SQLITE_OMIT_AUTOINCREMENT
10722 SQLITE_PRIVATE   void sqlite3AutoincrementBegin(Parse *pParse);
10723 SQLITE_PRIVATE   void sqlite3AutoincrementEnd(Parse *pParse);
10724 #else
10725 # define sqlite3AutoincrementBegin(X)
10726 # define sqlite3AutoincrementEnd(X)
10727 #endif
10728 SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
10729 SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int,int*,int*,int*);
10730 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
10731 SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
10732 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
10733 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
10734 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
10735                                       Token*, Select*, Expr*, IdList*);
10736 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
10737 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
10738 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
10739 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
10740 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
10741 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
10742 SQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
10743                         Token*, int, int);
10744 SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
10745 SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
10746 SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
10747                          Expr*,ExprList*,int,Expr*,Expr*);
10748 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
10749 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
10750 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
10751 SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
10752 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
10753 SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse *, SrcList *, Expr *, ExprList *, Expr *, Expr *, char *);
10754 #endif
10755 SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
10756 SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
10757 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*, SrcList*, Expr*, ExprList**, u16);
10758 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
10759 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int);
10760 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
10761 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
10762 SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, int, int, int);
10763 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
10764 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
10765 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*, int);
10766 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
10767 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
10768 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
10769 SQLITE_PRIVATE int sqlite3ExprCode(Parse*, Expr*, int);
10770 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
10771 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
10772 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
10773 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse*, Expr*);
10774 SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int);
10775 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
10776 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
10777 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
10778 SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
10779 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
10780 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
10781 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
10782 SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
10783 SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
10784 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
10785 SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*);
10786 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*);
10787 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
10788 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
10789 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
10790 SQLITE_PRIVATE void sqlite3PrngSaveState(void);
10791 SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
10792 SQLITE_PRIVATE void sqlite3PrngResetState(void);
10793 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*);
10794 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
10795 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
10796 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
10797 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
10798 SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
10799 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
10800 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
10801 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
10802 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*);
10803 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
10804 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
10805 SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(Vdbe*, const Expr*, int, int);
10806 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
10807 SQLITE_PRIVATE int sqlite3IsRowid(const char*);
10808 SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int, Trigger *, int);
10809 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*);
10810 SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int);
10811 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,
10812                                      int*,int,int,int,int,int*);
10813 SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*, int, int, int);
10814 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
10815 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
10816 SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
10817 SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
10818 SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, char*, int);
10819 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
10820 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
10821 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
10822 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
10823 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
10824 SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
10825 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,int);
10826 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
10827 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
10828 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
10829 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
10830 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
10831 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
10832
10833 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
10834 SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
10835 #endif
10836
10837 #ifndef SQLITE_OMIT_TRIGGER
10838 SQLITE_PRIVATE   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
10839                            Expr*,int, int);
10840 SQLITE_PRIVATE   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
10841 SQLITE_PRIVATE   void sqlite3DropTrigger(Parse*, SrcList*, int);
10842 SQLITE_PRIVATE   void sqlite3DropTriggerPtr(Parse*, Trigger*);
10843 SQLITE_PRIVATE   Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
10844 SQLITE_PRIVATE   Trigger *sqlite3TriggerList(Parse *, Table *);
10845 SQLITE_PRIVATE   void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
10846                             int, int, int);
10847 SQLITE_PRIVATE   void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
10848   void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
10849 SQLITE_PRIVATE   void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
10850 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
10851 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
10852                                         ExprList*,Select*,u8);
10853 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
10854 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
10855 SQLITE_PRIVATE   void sqlite3DeleteTrigger(sqlite3*, Trigger*);
10856 SQLITE_PRIVATE   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
10857 SQLITE_PRIVATE   u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
10858 # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
10859 #else
10860 # define sqlite3TriggersExist(B,C,D,E,F) 0
10861 # define sqlite3DeleteTrigger(A,B)
10862 # define sqlite3DropTriggerPtr(A,B)
10863 # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
10864 # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
10865 # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
10866 # define sqlite3TriggerList(X, Y) 0
10867 # define sqlite3ParseToplevel(p) p
10868 # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
10869 #endif
10870
10871 SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
10872 SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
10873 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
10874 #ifndef SQLITE_OMIT_AUTHORIZATION
10875 SQLITE_PRIVATE   void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
10876 SQLITE_PRIVATE   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
10877 SQLITE_PRIVATE   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
10878 SQLITE_PRIVATE   void sqlite3AuthContextPop(AuthContext*);
10879 SQLITE_PRIVATE   int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
10880 #else
10881 # define sqlite3AuthRead(a,b,c,d)
10882 # define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
10883 # define sqlite3AuthContextPush(a,b,c)
10884 # define sqlite3AuthContextPop(a)  ((void)(a))
10885 #endif
10886 SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
10887 SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
10888 SQLITE_PRIVATE int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
10889 SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
10890 SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
10891 SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
10892 SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
10893 SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
10894 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
10895 SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
10896 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
10897 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
10898 SQLITE_PRIVATE int sqlite3Utf8Read(const u8*, const u8**);
10899
10900 /*
10901 ** Routines to read and write variable-length integers.  These used to
10902 ** be defined locally, but now we use the varint routines in the util.c
10903 ** file.  Code should use the MACRO forms below, as the Varint32 versions
10904 ** are coded to assume the single byte case is already handled (which 
10905 ** the MACRO form does).
10906 */
10907 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
10908 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char*, u32);
10909 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
10910 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
10911 SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
10912
10913 /*
10914 ** The header of a record consists of a sequence variable-length integers.
10915 ** These integers are almost always small and are encoded as a single byte.
10916 ** The following macros take advantage this fact to provide a fast encode
10917 ** and decode of the integers in a record header.  It is faster for the common
10918 ** case where the integer is a single byte.  It is a little slower when the
10919 ** integer is two or more bytes.  But overall it is faster.
10920 **
10921 ** The following expressions are equivalent:
10922 **
10923 **     x = sqlite3GetVarint32( A, &B );
10924 **     x = sqlite3PutVarint32( A, B );
10925 **
10926 **     x = getVarint32( A, B );
10927 **     x = putVarint32( A, B );
10928 **
10929 */
10930 #define getVarint32(A,B)  (u8)((*(A)<(u8)0x80) ? ((B) = (u32)*(A)),1 : sqlite3GetVarint32((A), (u32 *)&(B)))
10931 #define putVarint32(A,B)  (u8)(((u32)(B)<(u32)0x80) ? (*(A) = (unsigned char)(B)),1 : sqlite3PutVarint32((A), (B)))
10932 #define getVarint    sqlite3GetVarint
10933 #define putVarint    sqlite3PutVarint
10934
10935
10936 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *, Index *);
10937 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *, Table *);
10938 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
10939 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
10940 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
10941 SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
10942 SQLITE_PRIVATE void sqlite3Error(sqlite3*, int, const char*,...);
10943 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
10944 SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
10945 SQLITE_PRIVATE const char *sqlite3ErrStr(int);
10946 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
10947 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
10948 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
10949 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
10950 SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Expr*, CollSeq*);
10951 SQLITE_PRIVATE Expr *sqlite3ExprSetCollByToken(Parse *pParse, Expr*, Token*);
10952 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
10953 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
10954 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
10955
10956 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
10957 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
10958 SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8, 
10959                         void(*)(void*));
10960 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
10961 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
10962 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
10963 #ifdef SQLITE_ENABLE_STAT2
10964 SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *, u8, char *, int, int *);
10965 #endif
10966 SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
10967 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
10968 #ifndef SQLITE_AMALGAMATION
10969 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
10970 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
10971 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
10972 SQLITE_PRIVATE const Token sqlite3IntTokens[];
10973 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
10974 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
10975 #ifndef SQLITE_OMIT_WSD
10976 SQLITE_PRIVATE int sqlite3PendingByte;
10977 #endif
10978 #endif
10979 SQLITE_PRIVATE void sqlite3RootPageMoved(Db*, int, int);
10980 SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
10981 SQLITE_PRIVATE void sqlite3AlterFunctions(void);
10982 SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
10983 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
10984 SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
10985 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
10986 SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
10987 SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
10988 SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
10989 SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
10990 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
10991 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
10992 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
10993 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
10994 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(sqlite3*, u8, CollSeq *, const char*);
10995 SQLITE_PRIVATE char sqlite3AffinityType(const char*);
10996 SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
10997 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
10998 SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
10999 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
11000 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
11001 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
11002 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
11003 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
11004 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
11005 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
11006 SQLITE_PRIVATE void sqlite3SchemaFree(void *);
11007 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
11008 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
11009 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
11010 SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *, 
11011   void (*)(sqlite3_context*,int,sqlite3_value **),
11012   void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
11013   FuncDestructor *pDestructor
11014 );
11015 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
11016 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
11017
11018 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);
11019 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
11020 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
11021 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
11022 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
11023 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
11024
11025 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
11026 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
11027
11028 /*
11029 ** The interface to the LEMON-generated parser
11030 */
11031 SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(size_t));
11032 SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
11033 SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
11034 #ifdef YYTRACKMAXSTACKDEPTH
11035 SQLITE_PRIVATE   int sqlite3ParserStackPeak(void*);
11036 #endif
11037
11038 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
11039 #ifndef SQLITE_OMIT_LOAD_EXTENSION
11040 SQLITE_PRIVATE   void sqlite3CloseExtensions(sqlite3*);
11041 #else
11042 # define sqlite3CloseExtensions(X)
11043 #endif
11044
11045 #ifndef SQLITE_OMIT_SHARED_CACHE
11046 SQLITE_PRIVATE   void sqlite3TableLock(Parse *, int, int, u8, const char *);
11047 #else
11048   #define sqlite3TableLock(v,w,x,y,z)
11049 #endif
11050
11051 #ifdef SQLITE_TEST
11052 SQLITE_PRIVATE   int sqlite3Utf8To8(unsigned char*);
11053 #endif
11054
11055 #ifdef SQLITE_OMIT_VIRTUALTABLE
11056 #  define sqlite3VtabClear(Y)
11057 #  define sqlite3VtabSync(X,Y) SQLITE_OK
11058 #  define sqlite3VtabRollback(X)
11059 #  define sqlite3VtabCommit(X)
11060 #  define sqlite3VtabInSync(db) 0
11061 #  define sqlite3VtabLock(X) 
11062 #  define sqlite3VtabUnlock(X)
11063 #  define sqlite3VtabUnlockList(X)
11064 #else
11065 SQLITE_PRIVATE    void sqlite3VtabClear(sqlite3 *db, Table*);
11066 SQLITE_PRIVATE    int sqlite3VtabSync(sqlite3 *db, char **);
11067 SQLITE_PRIVATE    int sqlite3VtabRollback(sqlite3 *db);
11068 SQLITE_PRIVATE    int sqlite3VtabCommit(sqlite3 *db);
11069 SQLITE_PRIVATE    void sqlite3VtabLock(VTable *);
11070 SQLITE_PRIVATE    void sqlite3VtabUnlock(VTable *);
11071 SQLITE_PRIVATE    void sqlite3VtabUnlockList(sqlite3*);
11072 #  define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
11073 #endif
11074 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
11075 SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*);
11076 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
11077 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
11078 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
11079 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
11080 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
11081 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
11082 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
11083 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
11084 SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
11085 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
11086 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
11087 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
11088 SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
11089 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
11090 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
11091 SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*);
11092 SQLITE_PRIVATE const char *sqlite3JournalModename(int);
11093 SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int);
11094 SQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
11095
11096 /* Declarations for functions in fkey.c. All of these are replaced by
11097 ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
11098 ** key functionality is available. If OMIT_TRIGGER is defined but
11099 ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
11100 ** this case foreign keys are parsed, but no other functionality is 
11101 ** provided (enforcement of FK constraints requires the triggers sub-system).
11102 */
11103 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
11104 SQLITE_PRIVATE   void sqlite3FkCheck(Parse*, Table*, int, int);
11105 SQLITE_PRIVATE   void sqlite3FkDropTable(Parse*, SrcList *, Table*);
11106 SQLITE_PRIVATE   void sqlite3FkActions(Parse*, Table*, ExprList*, int);
11107 SQLITE_PRIVATE   int sqlite3FkRequired(Parse*, Table*, int*, int);
11108 SQLITE_PRIVATE   u32 sqlite3FkOldmask(Parse*, Table*);
11109 SQLITE_PRIVATE   FKey *sqlite3FkReferences(Table *);
11110 #else
11111   #define sqlite3FkActions(a,b,c,d)
11112   #define sqlite3FkCheck(a,b,c,d)
11113   #define sqlite3FkDropTable(a,b,c)
11114   #define sqlite3FkOldmask(a,b)      0
11115   #define sqlite3FkRequired(a,b,c,d) 0
11116 #endif
11117 #ifndef SQLITE_OMIT_FOREIGN_KEY
11118 SQLITE_PRIVATE   void sqlite3FkDelete(sqlite3 *, Table*);
11119 #else
11120   #define sqlite3FkDelete(a,b)
11121 #endif
11122
11123
11124 /*
11125 ** Available fault injectors.  Should be numbered beginning with 0.
11126 */
11127 #define SQLITE_FAULTINJECTOR_MALLOC     0
11128 #define SQLITE_FAULTINJECTOR_COUNT      1
11129
11130 /*
11131 ** The interface to the code in fault.c used for identifying "benign"
11132 ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
11133 ** is not defined.
11134 */
11135 #ifndef SQLITE_OMIT_BUILTIN_TEST
11136 SQLITE_PRIVATE   void sqlite3BeginBenignMalloc(void);
11137 SQLITE_PRIVATE   void sqlite3EndBenignMalloc(void);
11138 #else
11139   #define sqlite3BeginBenignMalloc()
11140   #define sqlite3EndBenignMalloc()
11141 #endif
11142
11143 #define IN_INDEX_ROWID           1
11144 #define IN_INDEX_EPH             2
11145 #define IN_INDEX_INDEX           3
11146 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, int*);
11147
11148 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
11149 SQLITE_PRIVATE   int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
11150 SQLITE_PRIVATE   int sqlite3JournalSize(sqlite3_vfs *);
11151 SQLITE_PRIVATE   int sqlite3JournalCreate(sqlite3_file *);
11152 #else
11153   #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
11154 #endif
11155
11156 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
11157 SQLITE_PRIVATE int sqlite3MemJournalSize(void);
11158 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
11159
11160 #if SQLITE_MAX_EXPR_DEPTH>0
11161 SQLITE_PRIVATE   void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
11162 SQLITE_PRIVATE   int sqlite3SelectExprHeight(Select *);
11163 SQLITE_PRIVATE   int sqlite3ExprCheckHeight(Parse*, int);
11164 #else
11165   #define sqlite3ExprSetHeight(x,y)
11166   #define sqlite3SelectExprHeight(x) 0
11167   #define sqlite3ExprCheckHeight(x,y)
11168 #endif
11169
11170 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
11171 SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
11172
11173 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
11174 SQLITE_PRIVATE   void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
11175 SQLITE_PRIVATE   void sqlite3ConnectionUnlocked(sqlite3 *db);
11176 SQLITE_PRIVATE   void sqlite3ConnectionClosed(sqlite3 *db);
11177 #else
11178   #define sqlite3ConnectionBlocked(x,y)
11179   #define sqlite3ConnectionUnlocked(x)
11180   #define sqlite3ConnectionClosed(x)
11181 #endif
11182
11183 #ifdef SQLITE_DEBUG
11184 SQLITE_PRIVATE   void sqlite3ParserTrace(FILE*, char *);
11185 #endif
11186
11187 /*
11188 ** If the SQLITE_ENABLE IOTRACE exists then the global variable
11189 ** sqlite3IoTrace is a pointer to a printf-like routine used to
11190 ** print I/O tracing messages. 
11191 */
11192 #ifdef SQLITE_ENABLE_IOTRACE
11193 # define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }
11194 SQLITE_PRIVATE   void sqlite3VdbeIOTraceSql(Vdbe*);
11195 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*,...);
11196 #else
11197 # define IOTRACE(A)
11198 # define sqlite3VdbeIOTraceSql(X)
11199 #endif
11200
11201 /*
11202 ** These routines are available for the mem2.c debugging memory allocator
11203 ** only.  They are used to verify that different "types" of memory
11204 ** allocations are properly tracked by the system.
11205 **
11206 ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
11207 ** the MEMTYPE_* macros defined below.  The type must be a bitmask with
11208 ** a single bit set.
11209 **
11210 ** sqlite3MemdebugHasType() returns true if any of the bits in its second
11211 ** argument match the type set by the previous sqlite3MemdebugSetType().
11212 ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
11213 **
11214 ** sqlite3MemdebugNoType() returns true if none of the bits in its second
11215 ** argument match the type set by the previous sqlite3MemdebugSetType().
11216 **
11217 ** Perhaps the most important point is the difference between MEMTYPE_HEAP
11218 ** and MEMTYPE_LOOKASIDE.  If an allocation is MEMTYPE_LOOKASIDE, that means
11219 ** it might have been allocated by lookaside, except the allocation was
11220 ** too large or lookaside was already full.  It is important to verify
11221 ** that allocations that might have been satisfied by lookaside are not
11222 ** passed back to non-lookaside free() routines.  Asserts such as the
11223 ** example above are placed on the non-lookaside free() routines to verify
11224 ** this constraint. 
11225 **
11226 ** All of this is no-op for a production build.  It only comes into
11227 ** play when the SQLITE_MEMDEBUG compile-time option is used.
11228 */
11229 #ifdef SQLITE_MEMDEBUG
11230 SQLITE_PRIVATE   void sqlite3MemdebugSetType(void*,u8);
11231 SQLITE_PRIVATE   int sqlite3MemdebugHasType(void*,u8);
11232 SQLITE_PRIVATE   int sqlite3MemdebugNoType(void*,u8);
11233 #else
11234 # define sqlite3MemdebugSetType(X,Y)  /* no-op */
11235 # define sqlite3MemdebugHasType(X,Y)  1
11236 # define sqlite3MemdebugNoType(X,Y)   1
11237 #endif
11238 #define MEMTYPE_HEAP       0x01  /* General heap allocations */
11239 #define MEMTYPE_LOOKASIDE  0x02  /* Might have been lookaside memory */
11240 #define MEMTYPE_SCRATCH    0x04  /* Scratch allocations */
11241 #define MEMTYPE_PCACHE     0x08  /* Page cache allocations */
11242 #define MEMTYPE_DB         0x10  /* Uses sqlite3DbMalloc, not sqlite_malloc */
11243
11244 #endif /* _SQLITEINT_H_ */
11245
11246 /************** End of sqliteInt.h *******************************************/
11247 /************** Begin file global.c ******************************************/
11248 /*
11249 ** 2008 June 13
11250 **
11251 ** The author disclaims copyright to this source code.  In place of
11252 ** a legal notice, here is a blessing:
11253 **
11254 **    May you do good and not evil.
11255 **    May you find forgiveness for yourself and forgive others.
11256 **    May you share freely, never taking more than you give.
11257 **
11258 *************************************************************************
11259 **
11260 ** This file contains definitions of global variables and contants.
11261 */
11262
11263 /* An array to map all upper-case characters into their corresponding
11264 ** lower-case character. 
11265 **
11266 ** SQLite only considers US-ASCII (or EBCDIC) characters.  We do not
11267 ** handle case conversions for the UTF character set since the tables
11268 ** involved are nearly as big or bigger than SQLite itself.
11269 */
11270 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
11271 #ifdef SQLITE_ASCII
11272       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
11273      18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
11274      36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
11275      54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
11276     104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
11277     122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
11278     108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
11279     126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
11280     144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
11281     162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
11282     180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
11283     198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
11284     216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
11285     234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
11286     252,253,254,255
11287 #endif
11288 #ifdef SQLITE_EBCDIC
11289       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, /* 0x */
11290      16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
11291      32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
11292      48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
11293      64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
11294      80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
11295      96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
11296     112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
11297     128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
11298     144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
11299     160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
11300     176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
11301     192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
11302     208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
11303     224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
11304     239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
11305 #endif
11306 };
11307
11308 /*
11309 ** The following 256 byte lookup table is used to support SQLites built-in
11310 ** equivalents to the following standard library functions:
11311 **
11312 **   isspace()                        0x01
11313 **   isalpha()                        0x02
11314 **   isdigit()                        0x04
11315 **   isalnum()                        0x06
11316 **   isxdigit()                       0x08
11317 **   toupper()                        0x20
11318 **   SQLite identifier character      0x40
11319 **
11320 ** Bit 0x20 is set if the mapped character requires translation to upper
11321 ** case. i.e. if the character is a lower-case ASCII character.
11322 ** If x is a lower-case ASCII character, then its upper-case equivalent
11323 ** is (x - 0x20). Therefore toupper() can be implemented as:
11324 **
11325 **   (x & ~(map[x]&0x20))
11326 **
11327 ** Standard function tolower() is implemented using the sqlite3UpperToLower[]
11328 ** array. tolower() is used more often than toupper() by SQLite.
11329 **
11330 ** Bit 0x40 is set if the character non-alphanumeric and can be used in an 
11331 ** SQLite identifier.  Identifiers are alphanumerics, "_", "$", and any
11332 ** non-ASCII UTF character. Hence the test for whether or not a character is
11333 ** part of an identifier is 0x46.
11334 **
11335 ** SQLite's versions are identical to the standard versions assuming a
11336 ** locale of "C". They are implemented as macros in sqliteInt.h.
11337 */
11338 #ifdef SQLITE_ASCII
11339 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
11340   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 00..07    ........ */
11341   0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00,  /* 08..0f    ........ */
11342   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 10..17    ........ */
11343   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 18..1f    ........ */
11344   0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,  /* 20..27     !"#$%&' */
11345   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 28..2f    ()*+,-./ */
11346   0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,  /* 30..37    01234567 */
11347   0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 38..3f    89:;<=>? */
11348
11349   0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02,  /* 40..47    @ABCDEFG */
11350   0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 48..4f    HIJKLMNO */
11351   0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 50..57    PQRSTUVW */
11352   0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40,  /* 58..5f    XYZ[\]^_ */
11353   0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22,  /* 60..67    `abcdefg */
11354   0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 68..6f    hijklmno */
11355   0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 70..77    pqrstuvw */
11356   0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 78..7f    xyz{|}~. */
11357
11358   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 80..87    ........ */
11359   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 88..8f    ........ */
11360   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 90..97    ........ */
11361   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 98..9f    ........ */
11362   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a0..a7    ........ */
11363   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a8..af    ........ */
11364   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b0..b7    ........ */
11365   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b8..bf    ........ */
11366
11367   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c0..c7    ........ */
11368   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c8..cf    ........ */
11369   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d0..d7    ........ */
11370   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d8..df    ........ */
11371   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e0..e7    ........ */
11372   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e8..ef    ........ */
11373   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* f0..f7    ........ */
11374   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40   /* f8..ff    ........ */
11375 };
11376 #endif
11377
11378
11379
11380 /*
11381 ** The following singleton contains the global configuration for
11382 ** the SQLite library.
11383 */
11384 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
11385    SQLITE_DEFAULT_MEMSTATUS,  /* bMemstat */
11386    1,                         /* bCoreMutex */
11387    SQLITE_THREADSAFE==1,      /* bFullMutex */
11388    0x7ffffffe,                /* mxStrlen */
11389    100,                       /* szLookaside */
11390    500,                       /* nLookaside */
11391    {0,0,0,0,0,0,0,0},         /* m */
11392    {0,0,0,0,0,0,0,0,0},       /* mutex */
11393    {0,0,0,0,0,0,0,0,0,0,0},   /* pcache */
11394    (void*)0,                  /* pHeap */
11395    0,                         /* nHeap */
11396    0, 0,                      /* mnHeap, mxHeap */
11397    (void*)0,                  /* pScratch */
11398    0,                         /* szScratch */
11399    0,                         /* nScratch */
11400    (void*)0,                  /* pPage */
11401    0,                         /* szPage */
11402    0,                         /* nPage */
11403    0,                         /* mxParserStack */
11404    0,                         /* sharedCacheEnabled */
11405    /* All the rest should always be initialized to zero */
11406    0,                         /* isInit */
11407    0,                         /* inProgress */
11408    0,                         /* isMutexInit */
11409    0,                         /* isMallocInit */
11410    0,                         /* isPCacheInit */
11411    0,                         /* pInitMutex */
11412    0,                         /* nRefInitMutex */
11413    0,                         /* xLog */
11414    0,                         /* pLogArg */
11415 };
11416
11417
11418 /*
11419 ** Hash table for global functions - functions common to all
11420 ** database connections.  After initialization, this table is
11421 ** read-only.
11422 */
11423 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
11424
11425 /*
11426 ** Constant tokens for values 0 and 1.
11427 */
11428 SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
11429    { "0", 1 },
11430    { "1", 1 }
11431 };
11432
11433
11434 /*
11435 ** The value of the "pending" byte must be 0x40000000 (1 byte past the
11436 ** 1-gibabyte boundary) in a compatible database.  SQLite never uses
11437 ** the database page that contains the pending byte.  It never attempts
11438 ** to read or write that page.  The pending byte page is set assign
11439 ** for use by the VFS layers as space for managing file locks.
11440 **
11441 ** During testing, it is often desirable to move the pending byte to
11442 ** a different position in the file.  This allows code that has to
11443 ** deal with the pending byte to run on files that are much smaller
11444 ** than 1 GiB.  The sqlite3_test_control() interface can be used to
11445 ** move the pending byte.
11446 **
11447 ** IMPORTANT:  Changing the pending byte to any value other than
11448 ** 0x40000000 results in an incompatible database file format!
11449 ** Changing the pending byte during operating results in undefined
11450 ** and dileterious behavior.
11451 */
11452 #ifndef SQLITE_OMIT_WSD
11453 SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
11454 #endif
11455
11456 /*
11457 ** Properties of opcodes.  The OPFLG_INITIALIZER macro is
11458 ** created by mkopcodeh.awk during compilation.  Data is obtained
11459 ** from the comments following the "case OP_xxxx:" statements in
11460 ** the vdbe.c file.  
11461 */
11462 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
11463
11464 /************** End of global.c **********************************************/
11465 /************** Begin file ctime.c *******************************************/
11466 /*
11467 ** 2010 February 23
11468 **
11469 ** The author disclaims copyright to this source code.  In place of
11470 ** a legal notice, here is a blessing:
11471 **
11472 **    May you do good and not evil.
11473 **    May you find forgiveness for yourself and forgive others.
11474 **    May you share freely, never taking more than you give.
11475 **
11476 *************************************************************************
11477 **
11478 ** This file implements routines used to report what compile-time options
11479 ** SQLite was built with.
11480 */
11481
11482 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
11483
11484
11485 /*
11486 ** An array of names of all compile-time options.  This array should 
11487 ** be sorted A-Z.
11488 **
11489 ** This array looks large, but in a typical installation actually uses
11490 ** only a handful of compile-time options, so most times this array is usually
11491 ** rather short and uses little memory space.
11492 */
11493 static const char * const azCompileOpt[] = {
11494
11495 /* These macros are provided to "stringify" the value of the define
11496 ** for those options in which the value is meaningful. */
11497 #define CTIMEOPT_VAL_(opt) #opt
11498 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
11499
11500 #ifdef SQLITE_32BIT_ROWID
11501   "32BIT_ROWID",
11502 #endif
11503 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
11504   "4_BYTE_ALIGNED_MALLOC",
11505 #endif
11506 #ifdef SQLITE_CASE_SENSITIVE_LIKE
11507   "CASE_SENSITIVE_LIKE",
11508 #endif
11509 #ifdef SQLITE_CHECK_PAGES
11510   "CHECK_PAGES",
11511 #endif
11512 #ifdef SQLITE_COVERAGE_TEST
11513   "COVERAGE_TEST",
11514 #endif
11515 #ifdef SQLITE_DEBUG
11516   "DEBUG",
11517 #endif
11518 #ifdef SQLITE_DEFAULT_LOCKING_MODE
11519   "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
11520 #endif
11521 #ifdef SQLITE_DISABLE_DIRSYNC
11522   "DISABLE_DIRSYNC",
11523 #endif
11524 #ifdef SQLITE_DISABLE_LFS
11525   "DISABLE_LFS",
11526 #endif
11527 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
11528   "ENABLE_ATOMIC_WRITE",
11529 #endif
11530 #ifdef SQLITE_ENABLE_CEROD
11531   "ENABLE_CEROD",
11532 #endif
11533 #ifdef SQLITE_ENABLE_COLUMN_METADATA
11534   "ENABLE_COLUMN_METADATA",
11535 #endif
11536 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
11537   "ENABLE_EXPENSIVE_ASSERT",
11538 #endif
11539 #ifdef SQLITE_ENABLE_FTS1
11540   "ENABLE_FTS1",
11541 #endif
11542 #ifdef SQLITE_ENABLE_FTS2
11543   "ENABLE_FTS2",
11544 #endif
11545 #ifdef SQLITE_ENABLE_FTS3
11546   "ENABLE_FTS3",
11547 #endif
11548 #ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
11549   "ENABLE_FTS3_PARENTHESIS",
11550 #endif
11551 #ifdef SQLITE_ENABLE_FTS4
11552   "ENABLE_FTS4",
11553 #endif
11554 #ifdef SQLITE_ENABLE_ICU
11555   "ENABLE_ICU",
11556 #endif
11557 #ifdef SQLITE_ENABLE_IOTRACE
11558   "ENABLE_IOTRACE",
11559 #endif
11560 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
11561   "ENABLE_LOAD_EXTENSION",
11562 #endif
11563 #ifdef SQLITE_ENABLE_LOCKING_STYLE
11564   "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
11565 #endif
11566 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
11567   "ENABLE_MEMORY_MANAGEMENT",
11568 #endif
11569 #ifdef SQLITE_ENABLE_MEMSYS3
11570   "ENABLE_MEMSYS3",
11571 #endif
11572 #ifdef SQLITE_ENABLE_MEMSYS5
11573   "ENABLE_MEMSYS5",
11574 #endif
11575 #ifdef SQLITE_ENABLE_OVERSIZE_CELL_CHECK
11576   "ENABLE_OVERSIZE_CELL_CHECK",
11577 #endif
11578 #ifdef SQLITE_ENABLE_RTREE
11579   "ENABLE_RTREE",
11580 #endif
11581 #ifdef SQLITE_ENABLE_STAT2
11582   "ENABLE_STAT2",
11583 #endif
11584 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
11585   "ENABLE_UNLOCK_NOTIFY",
11586 #endif
11587 #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
11588   "ENABLE_UPDATE_DELETE_LIMIT",
11589 #endif
11590 #ifdef SQLITE_HAS_CODEC
11591   "HAS_CODEC",
11592 #endif
11593 #ifdef SQLITE_HAVE_ISNAN
11594   "HAVE_ISNAN",
11595 #endif
11596 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
11597   "HOMEGROWN_RECURSIVE_MUTEX",
11598 #endif
11599 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
11600   "IGNORE_AFP_LOCK_ERRORS",
11601 #endif
11602 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
11603   "IGNORE_FLOCK_LOCK_ERRORS",
11604 #endif
11605 #ifdef SQLITE_INT64_TYPE
11606   "INT64_TYPE",
11607 #endif
11608 #ifdef SQLITE_LOCK_TRACE
11609   "LOCK_TRACE",
11610 #endif
11611 #ifdef SQLITE_MEMDEBUG
11612   "MEMDEBUG",
11613 #endif
11614 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
11615   "MIXED_ENDIAN_64BIT_FLOAT",
11616 #endif
11617 #ifdef SQLITE_NO_SYNC
11618   "NO_SYNC",
11619 #endif
11620 #ifdef SQLITE_OMIT_ALTERTABLE
11621   "OMIT_ALTERTABLE",
11622 #endif
11623 #ifdef SQLITE_OMIT_ANALYZE
11624   "OMIT_ANALYZE",
11625 #endif
11626 #ifdef SQLITE_OMIT_ATTACH
11627   "OMIT_ATTACH",
11628 #endif
11629 #ifdef SQLITE_OMIT_AUTHORIZATION
11630   "OMIT_AUTHORIZATION",
11631 #endif
11632 #ifdef SQLITE_OMIT_AUTOINCREMENT
11633   "OMIT_AUTOINCREMENT",
11634 #endif
11635 #ifdef SQLITE_OMIT_AUTOINIT
11636   "OMIT_AUTOINIT",
11637 #endif
11638 #ifdef SQLITE_OMIT_AUTOMATIC_INDEX
11639   "OMIT_AUTOMATIC_INDEX",
11640 #endif
11641 #ifdef SQLITE_OMIT_AUTOVACUUM
11642   "OMIT_AUTOVACUUM",
11643 #endif
11644 #ifdef SQLITE_OMIT_BETWEEN_OPTIMIZATION
11645   "OMIT_BETWEEN_OPTIMIZATION",
11646 #endif
11647 #ifdef SQLITE_OMIT_BLOB_LITERAL
11648   "OMIT_BLOB_LITERAL",
11649 #endif
11650 #ifdef SQLITE_OMIT_BTREECOUNT
11651   "OMIT_BTREECOUNT",
11652 #endif
11653 #ifdef SQLITE_OMIT_BUILTIN_TEST
11654   "OMIT_BUILTIN_TEST",
11655 #endif
11656 #ifdef SQLITE_OMIT_CAST
11657   "OMIT_CAST",
11658 #endif
11659 #ifdef SQLITE_OMIT_CHECK
11660   "OMIT_CHECK",
11661 #endif
11662 /* // redundant
11663 ** #ifdef SQLITE_OMIT_COMPILEOPTION_DIAGS
11664 **   "OMIT_COMPILEOPTION_DIAGS",
11665 ** #endif
11666 */
11667 #ifdef SQLITE_OMIT_COMPLETE
11668   "OMIT_COMPLETE",
11669 #endif
11670 #ifdef SQLITE_OMIT_COMPOUND_SELECT
11671   "OMIT_COMPOUND_SELECT",
11672 #endif
11673 #ifdef SQLITE_OMIT_DATETIME_FUNCS
11674   "OMIT_DATETIME_FUNCS",
11675 #endif
11676 #ifdef SQLITE_OMIT_DECLTYPE
11677   "OMIT_DECLTYPE",
11678 #endif
11679 #ifdef SQLITE_OMIT_DEPRECATED
11680   "OMIT_DEPRECATED",
11681 #endif
11682 #ifdef SQLITE_OMIT_DISKIO
11683   "OMIT_DISKIO",
11684 #endif
11685 #ifdef SQLITE_OMIT_EXPLAIN
11686   "OMIT_EXPLAIN",
11687 #endif
11688 #ifdef SQLITE_OMIT_FLAG_PRAGMAS
11689   "OMIT_FLAG_PRAGMAS",
11690 #endif
11691 #ifdef SQLITE_OMIT_FLOATING_POINT
11692   "OMIT_FLOATING_POINT",
11693 #endif
11694 #ifdef SQLITE_OMIT_FOREIGN_KEY
11695   "OMIT_FOREIGN_KEY",
11696 #endif
11697 #ifdef SQLITE_OMIT_GET_TABLE
11698   "OMIT_GET_TABLE",
11699 #endif
11700 #ifdef SQLITE_OMIT_INCRBLOB
11701   "OMIT_INCRBLOB",
11702 #endif
11703 #ifdef SQLITE_OMIT_INTEGRITY_CHECK
11704   "OMIT_INTEGRITY_CHECK",
11705 #endif
11706 #ifdef SQLITE_OMIT_LIKE_OPTIMIZATION
11707   "OMIT_LIKE_OPTIMIZATION",
11708 #endif
11709 #ifdef SQLITE_OMIT_LOAD_EXTENSION
11710   "OMIT_LOAD_EXTENSION",
11711 #endif
11712 #ifdef SQLITE_OMIT_LOCALTIME
11713   "OMIT_LOCALTIME",
11714 #endif
11715 #ifdef SQLITE_OMIT_LOOKASIDE
11716   "OMIT_LOOKASIDE",
11717 #endif
11718 #ifdef SQLITE_OMIT_MEMORYDB
11719   "OMIT_MEMORYDB",
11720 #endif
11721 #ifdef SQLITE_OMIT_OR_OPTIMIZATION
11722   "OMIT_OR_OPTIMIZATION",
11723 #endif
11724 #ifdef SQLITE_OMIT_PAGER_PRAGMAS
11725   "OMIT_PAGER_PRAGMAS",
11726 #endif
11727 #ifdef SQLITE_OMIT_PRAGMA
11728   "OMIT_PRAGMA",
11729 #endif
11730 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
11731   "OMIT_PROGRESS_CALLBACK",
11732 #endif
11733 #ifdef SQLITE_OMIT_QUICKBALANCE
11734   "OMIT_QUICKBALANCE",
11735 #endif
11736 #ifdef SQLITE_OMIT_REINDEX
11737   "OMIT_REINDEX",
11738 #endif
11739 #ifdef SQLITE_OMIT_SCHEMA_PRAGMAS
11740   "OMIT_SCHEMA_PRAGMAS",
11741 #endif
11742 #ifdef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
11743   "OMIT_SCHEMA_VERSION_PRAGMAS",
11744 #endif
11745 #ifdef SQLITE_OMIT_SHARED_CACHE
11746   "OMIT_SHARED_CACHE",
11747 #endif
11748 #ifdef SQLITE_OMIT_SUBQUERY
11749   "OMIT_SUBQUERY",
11750 #endif
11751 #ifdef SQLITE_OMIT_TCL_VARIABLE
11752   "OMIT_TCL_VARIABLE",
11753 #endif
11754 #ifdef SQLITE_OMIT_TEMPDB
11755   "OMIT_TEMPDB",
11756 #endif
11757 #ifdef SQLITE_OMIT_TRACE
11758   "OMIT_TRACE",
11759 #endif
11760 #ifdef SQLITE_OMIT_TRIGGER
11761   "OMIT_TRIGGER",
11762 #endif
11763 #ifdef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
11764   "OMIT_TRUNCATE_OPTIMIZATION",
11765 #endif
11766 #ifdef SQLITE_OMIT_UTF16
11767   "OMIT_UTF16",
11768 #endif
11769 #ifdef SQLITE_OMIT_VACUUM
11770   "OMIT_VACUUM",
11771 #endif
11772 #ifdef SQLITE_OMIT_VIEW
11773   "OMIT_VIEW",
11774 #endif
11775 #ifdef SQLITE_OMIT_VIRTUALTABLE
11776   "OMIT_VIRTUALTABLE",
11777 #endif
11778 #ifdef SQLITE_OMIT_WAL
11779   "OMIT_WAL",
11780 #endif
11781 #ifdef SQLITE_OMIT_WSD
11782   "OMIT_WSD",
11783 #endif
11784 #ifdef SQLITE_OMIT_XFER_OPT
11785   "OMIT_XFER_OPT",
11786 #endif
11787 #ifdef SQLITE_PERFORMANCE_TRACE
11788   "PERFORMANCE_TRACE",
11789 #endif
11790 #ifdef SQLITE_PROXY_DEBUG
11791   "PROXY_DEBUG",
11792 #endif
11793 #ifdef SQLITE_SECURE_DELETE
11794   "SECURE_DELETE",
11795 #endif
11796 #ifdef SQLITE_SMALL_STACK
11797   "SMALL_STACK",
11798 #endif
11799 #ifdef SQLITE_SOUNDEX
11800   "SOUNDEX",
11801 #endif
11802 #ifdef SQLITE_TCL
11803   "TCL",
11804 #endif
11805 #ifdef SQLITE_TEMP_STORE
11806   "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
11807 #endif
11808 #ifdef SQLITE_TEST
11809   "TEST",
11810 #endif
11811 #ifdef SQLITE_THREADSAFE
11812   "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
11813 #endif
11814 #ifdef SQLITE_USE_ALLOCA
11815   "USE_ALLOCA",
11816 #endif
11817 #ifdef SQLITE_ZERO_MALLOC
11818   "ZERO_MALLOC"
11819 #endif
11820 };
11821
11822 /*
11823 ** Given the name of a compile-time option, return true if that option
11824 ** was used and false if not.
11825 **
11826 ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
11827 ** is not required for a match.
11828 */
11829 SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
11830   int i, n;
11831   if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
11832   n = sqlite3Strlen30(zOptName);
11833
11834   /* Since ArraySize(azCompileOpt) is normally in single digits, a
11835   ** linear search is adequate.  No need for a binary search. */
11836   for(i=0; i<ArraySize(azCompileOpt); i++){
11837     if(   (sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0)
11838        && ( (azCompileOpt[i][n]==0) || (azCompileOpt[i][n]=='=') ) ) return 1;
11839   }
11840   return 0;
11841 }
11842
11843 /*
11844 ** Return the N-th compile-time option string.  If N is out of range,
11845 ** return a NULL pointer.
11846 */
11847 SQLITE_API const char *sqlite3_compileoption_get(int N){
11848   if( N>=0 && N<ArraySize(azCompileOpt) ){
11849     return azCompileOpt[N];
11850   }
11851   return 0;
11852 }
11853
11854 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
11855
11856 /************** End of ctime.c ***********************************************/
11857 /************** Begin file status.c ******************************************/
11858 /*
11859 ** 2008 June 18
11860 **
11861 ** The author disclaims copyright to this source code.  In place of
11862 ** a legal notice, here is a blessing:
11863 **
11864 **    May you do good and not evil.
11865 **    May you find forgiveness for yourself and forgive others.
11866 **    May you share freely, never taking more than you give.
11867 **
11868 *************************************************************************
11869 **
11870 ** This module implements the sqlite3_status() interface and related
11871 ** functionality.
11872 */
11873 /************** Include vdbeInt.h in the middle of status.c ******************/
11874 /************** Begin file vdbeInt.h *****************************************/
11875 /*
11876 ** 2003 September 6
11877 **
11878 ** The author disclaims copyright to this source code.  In place of
11879 ** a legal notice, here is a blessing:
11880 **
11881 **    May you do good and not evil.
11882 **    May you find forgiveness for yourself and forgive others.
11883 **    May you share freely, never taking more than you give.
11884 **
11885 *************************************************************************
11886 ** This is the header file for information that is private to the
11887 ** VDBE.  This information used to all be at the top of the single
11888 ** source code file "vdbe.c".  When that file became too big (over
11889 ** 6000 lines long) it was split up into several smaller files and
11890 ** this header information was factored out.
11891 */
11892 #ifndef _VDBEINT_H_
11893 #define _VDBEINT_H_
11894
11895 /*
11896 ** SQL is translated into a sequence of instructions to be
11897 ** executed by a virtual machine.  Each instruction is an instance
11898 ** of the following structure.
11899 */
11900 typedef struct VdbeOp Op;
11901
11902 /*
11903 ** Boolean values
11904 */
11905 typedef unsigned char Bool;
11906
11907 /*
11908 ** A cursor is a pointer into a single BTree within a database file.
11909 ** The cursor can seek to a BTree entry with a particular key, or
11910 ** loop over all entries of the Btree.  You can also insert new BTree
11911 ** entries or retrieve the key or data from the entry that the cursor
11912 ** is currently pointing to.
11913 ** 
11914 ** Every cursor that the virtual machine has open is represented by an
11915 ** instance of the following structure.
11916 **
11917 ** If the VdbeCursor.isTriggerRow flag is set it means that this cursor is
11918 ** really a single row that represents the NEW or OLD pseudo-table of
11919 ** a row trigger.  The data for the row is stored in VdbeCursor.pData and
11920 ** the rowid is in VdbeCursor.iKey.
11921 */
11922 struct VdbeCursor {
11923   BtCursor *pCursor;    /* The cursor structure of the backend */
11924   int iDb;              /* Index of cursor database in db->aDb[] (or -1) */
11925   i64 lastRowid;        /* Last rowid from a Next or NextIdx operation */
11926   Bool zeroed;          /* True if zeroed out and ready for reuse */
11927   Bool rowidIsValid;    /* True if lastRowid is valid */
11928   Bool atFirst;         /* True if pointing to first entry */
11929   Bool useRandomRowid;  /* Generate new record numbers semi-randomly */
11930   Bool nullRow;         /* True if pointing to a row with no data */
11931   Bool deferredMoveto;  /* A call to sqlite3BtreeMoveto() is needed */
11932   Bool isTable;         /* True if a table requiring integer keys */
11933   Bool isIndex;         /* True if an index containing keys only - no data */
11934   Bool isOrdered;       /* True if the underlying table is BTREE_UNORDERED */
11935   i64 movetoTarget;     /* Argument to the deferred sqlite3BtreeMoveto() */
11936   Btree *pBt;           /* Separate file holding temporary table */
11937   int pseudoTableReg;   /* Register holding pseudotable content. */
11938   KeyInfo *pKeyInfo;    /* Info about index keys needed by index cursors */
11939   int nField;           /* Number of fields in the header */
11940   i64 seqCount;         /* Sequence counter */
11941   sqlite3_vtab_cursor *pVtabCursor;  /* The cursor for a virtual table */
11942   const sqlite3_module *pModule;     /* Module for cursor pVtabCursor */
11943
11944   /* Result of last sqlite3BtreeMoveto() done by an OP_NotExists or 
11945   ** OP_IsUnique opcode on this cursor. */
11946   int seekResult;
11947
11948   /* Cached information about the header for the data record that the
11949   ** cursor is currently pointing to.  Only valid if cacheStatus matches
11950   ** Vdbe.cacheCtr.  Vdbe.cacheCtr will never take on the value of
11951   ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
11952   ** the cache is out of date.
11953   **
11954   ** aRow might point to (ephemeral) data for the current row, or it might
11955   ** be NULL.
11956   */
11957   u32 cacheStatus;      /* Cache is valid if this matches Vdbe.cacheCtr */
11958   int payloadSize;      /* Total number of bytes in the record */
11959   u32 *aType;           /* Type values for all entries in the record */
11960   u32 *aOffset;         /* Cached offsets to the start of each columns data */
11961   u8 *aRow;             /* Data for the current row, if all on one page */
11962 };
11963 typedef struct VdbeCursor VdbeCursor;
11964
11965 /*
11966 ** When a sub-program is executed (OP_Program), a structure of this type
11967 ** is allocated to store the current value of the program counter, as
11968 ** well as the current memory cell array and various other frame specific
11969 ** values stored in the Vdbe struct. When the sub-program is finished, 
11970 ** these values are copied back to the Vdbe from the VdbeFrame structure,
11971 ** restoring the state of the VM to as it was before the sub-program
11972 ** began executing.
11973 **
11974 ** Frames are stored in a linked list headed at Vdbe.pParent. Vdbe.pParent
11975 ** is the parent of the current frame, or zero if the current frame
11976 ** is the main Vdbe program.
11977 */
11978 typedef struct VdbeFrame VdbeFrame;
11979 struct VdbeFrame {
11980   Vdbe *v;                /* VM this frame belongs to */
11981   int pc;                 /* Program Counter */
11982   Op *aOp;                /* Program instructions */
11983   int nOp;                /* Size of aOp array */
11984   Mem *aMem;              /* Array of memory cells */
11985   int nMem;               /* Number of entries in aMem */
11986   VdbeCursor **apCsr;     /* Element of Vdbe cursors */
11987   u16 nCursor;            /* Number of entries in apCsr */
11988   void *token;            /* Copy of SubProgram.token */
11989   int nChildMem;          /* Number of memory cells for child frame */
11990   int nChildCsr;          /* Number of cursors for child frame */
11991   i64 lastRowid;          /* Last insert rowid (sqlite3.lastRowid) */
11992   int nChange;            /* Statement changes (Vdbe.nChanges)     */
11993   VdbeFrame *pParent;     /* Parent of this frame */
11994 };
11995
11996 #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
11997
11998 /*
11999 ** A value for VdbeCursor.cacheValid that means the cache is always invalid.
12000 */
12001 #define CACHE_STALE 0
12002
12003 /*
12004 ** Internally, the vdbe manipulates nearly all SQL values as Mem
12005 ** structures. Each Mem struct may cache multiple representations (string,
12006 ** integer etc.) of the same value.  A value (and therefore Mem structure)
12007 ** has the following properties:
12008 **
12009 ** Each value has a manifest type. The manifest type of the value stored
12010 ** in a Mem struct is returned by the MemType(Mem*) macro. The type is
12011 ** one of SQLITE_NULL, SQLITE_INTEGER, SQLITE_REAL, SQLITE_TEXT or
12012 ** SQLITE_BLOB.
12013 */
12014 struct Mem {
12015   union {
12016     i64 i;              /* Integer value. */
12017     int nZero;          /* Used when bit MEM_Zero is set in flags */
12018     FuncDef *pDef;      /* Used only when flags==MEM_Agg */
12019     RowSet *pRowSet;    /* Used only when flags==MEM_RowSet */
12020     VdbeFrame *pFrame;  /* Used when flags==MEM_Frame */
12021   } u;
12022   double r;           /* Real value */
12023   sqlite3 *db;        /* The associated database connection */
12024   char *z;            /* String or BLOB value */
12025   int n;              /* Number of characters in string value, excluding '\0' */
12026   u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
12027   u8  type;           /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
12028   u8  enc;            /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
12029 #ifdef SQLITE_DEBUG
12030   Mem *pScopyFrom;    /* This Mem is a shallow copy of pScopyFrom */
12031   void *pFiller;      /* So that sizeof(Mem) is a multiple of 8 */
12032 #endif
12033   void (*xDel)(void *);  /* If not null, call this function to delete Mem.z */
12034   char *zMalloc;      /* Dynamic buffer allocated by sqlite3_malloc() */
12035 };
12036
12037 /* One or more of the following flags are set to indicate the validOK
12038 ** representations of the value stored in the Mem struct.
12039 **
12040 ** If the MEM_Null flag is set, then the value is an SQL NULL value.
12041 ** No other flags may be set in this case.
12042 **
12043 ** If the MEM_Str flag is set then Mem.z points at a string representation.
12044 ** Usually this is encoded in the same unicode encoding as the main
12045 ** database (see below for exceptions). If the MEM_Term flag is also
12046 ** set, then the string is nul terminated. The MEM_Int and MEM_Real 
12047 ** flags may coexist with the MEM_Str flag.
12048 **
12049 ** Multiple of these values can appear in Mem.flags.  But only one
12050 ** at a time can appear in Mem.type.
12051 */
12052 #define MEM_Null      0x0001   /* Value is NULL */
12053 #define MEM_Str       0x0002   /* Value is a string */
12054 #define MEM_Int       0x0004   /* Value is an integer */
12055 #define MEM_Real      0x0008   /* Value is a real number */
12056 #define MEM_Blob      0x0010   /* Value is a BLOB */
12057 #define MEM_RowSet    0x0020   /* Value is a RowSet object */
12058 #define MEM_Frame     0x0040   /* Value is a VdbeFrame object */
12059 #define MEM_Invalid   0x0080   /* Value is undefined */
12060 #define MEM_TypeMask  0x00ff   /* Mask of type bits */
12061
12062 /* Whenever Mem contains a valid string or blob representation, one of
12063 ** the following flags must be set to determine the memory management
12064 ** policy for Mem.z.  The MEM_Term flag tells us whether or not the
12065 ** string is \000 or \u0000 terminated
12066 */
12067 #define MEM_Term      0x0200   /* String rep is nul terminated */
12068 #define MEM_Dyn       0x0400   /* Need to call sqliteFree() on Mem.z */
12069 #define MEM_Static    0x0800   /* Mem.z points to a static string */
12070 #define MEM_Ephem     0x1000   /* Mem.z points to an ephemeral string */
12071 #define MEM_Agg       0x2000   /* Mem.z points to an agg function context */
12072 #define MEM_Zero      0x4000   /* Mem.i contains count of 0s appended to blob */
12073 #ifdef SQLITE_OMIT_INCRBLOB
12074   #undef MEM_Zero
12075   #define MEM_Zero 0x0000
12076 #endif
12077
12078 /*
12079 ** Clear any existing type flags from a Mem and replace them with f
12080 */
12081 #define MemSetTypeFlag(p, f) \
12082    ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
12083
12084 /*
12085 ** Return true if a memory cell is not marked as invalid.  This macro
12086 ** is for use inside assert() statements only.
12087 */
12088 #ifdef SQLITE_DEBUG
12089 #define memIsValid(M)  ((M)->flags & MEM_Invalid)==0
12090 #endif
12091
12092
12093 /* A VdbeFunc is just a FuncDef (defined in sqliteInt.h) that contains
12094 ** additional information about auxiliary information bound to arguments
12095 ** of the function.  This is used to implement the sqlite3_get_auxdata()
12096 ** and sqlite3_set_auxdata() APIs.  The "auxdata" is some auxiliary data
12097 ** that can be associated with a constant argument to a function.  This
12098 ** allows functions such as "regexp" to compile their constant regular
12099 ** expression argument once and reused the compiled code for multiple
12100 ** invocations.
12101 */
12102 struct VdbeFunc {
12103   FuncDef *pFunc;               /* The definition of the function */
12104   int nAux;                     /* Number of entries allocated for apAux[] */
12105   struct AuxData {
12106     void *pAux;                   /* Aux data for the i-th argument */
12107     void (*xDelete)(void *);      /* Destructor for the aux data */
12108   } apAux[1];                   /* One slot for each function argument */
12109 };
12110
12111 /*
12112 ** The "context" argument for a installable function.  A pointer to an
12113 ** instance of this structure is the first argument to the routines used
12114 ** implement the SQL functions.
12115 **
12116 ** There is a typedef for this structure in sqlite.h.  So all routines,
12117 ** even the public interface to SQLite, can use a pointer to this structure.
12118 ** But this file is the only place where the internal details of this
12119 ** structure are known.
12120 **
12121 ** This structure is defined inside of vdbeInt.h because it uses substructures
12122 ** (Mem) which are only defined there.
12123 */
12124 struct sqlite3_context {
12125   FuncDef *pFunc;       /* Pointer to function information.  MUST BE FIRST */
12126   VdbeFunc *pVdbeFunc;  /* Auxilary data, if created. */
12127   Mem s;                /* The return value is stored here */
12128   Mem *pMem;            /* Memory cell used to store aggregate context */
12129   int isError;          /* Error code returned by the function. */
12130   CollSeq *pColl;       /* Collating sequence */
12131 };
12132
12133 /*
12134 ** A Set structure is used for quick testing to see if a value
12135 ** is part of a small set.  Sets are used to implement code like
12136 ** this:
12137 **            x.y IN ('hi','hoo','hum')
12138 */
12139 typedef struct Set Set;
12140 struct Set {
12141   Hash hash;             /* A set is just a hash table */
12142   HashElem *prev;        /* Previously accessed hash elemen */
12143 };
12144
12145 /*
12146 ** An instance of the virtual machine.  This structure contains the complete
12147 ** state of the virtual machine.
12148 **
12149 ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_compile()
12150 ** is really a pointer to an instance of this structure.
12151 **
12152 ** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
12153 ** any virtual table method invocations made by the vdbe program. It is
12154 ** set to 2 for xDestroy method calls and 1 for all other methods. This
12155 ** variable is used for two purposes: to allow xDestroy methods to execute
12156 ** "DROP TABLE" statements and to prevent some nasty side effects of
12157 ** malloc failure when SQLite is invoked recursively by a virtual table 
12158 ** method function.
12159 */
12160 struct Vdbe {
12161   sqlite3 *db;            /* The database connection that owns this statement */
12162   Vdbe *pPrev,*pNext;     /* Linked list of VDBEs with the same Vdbe.db */
12163   int nOp;                /* Number of instructions in the program */
12164   int nOpAlloc;           /* Number of slots allocated for aOp[] */
12165   Op *aOp;                /* Space to hold the virtual machine's program */
12166   int nLabel;             /* Number of labels used */
12167   int nLabelAlloc;        /* Number of slots allocated in aLabel[] */
12168   int *aLabel;            /* Space to hold the labels */
12169   Mem **apArg;            /* Arguments to currently executing user function */
12170   Mem *aColName;          /* Column names to return */
12171   Mem *pResultSet;        /* Pointer to an array of results */
12172   u16 nResColumn;         /* Number of columns in one row of the result set */
12173   u16 nCursor;            /* Number of slots in apCsr[] */
12174   VdbeCursor **apCsr;     /* One element of this array for each open cursor */
12175   u8 errorAction;         /* Recovery action to do in case of an error */
12176   u8 okVar;               /* True if azVar[] has been initialized */
12177   ynVar nVar;             /* Number of entries in aVar[] */
12178   Mem *aVar;              /* Values for the OP_Variable opcode. */
12179   char **azVar;           /* Name of variables */
12180   u32 magic;              /* Magic number for sanity checking */
12181   int nMem;               /* Number of memory locations currently allocated */
12182   Mem *aMem;              /* The memory locations */
12183   u32 cacheCtr;           /* VdbeCursor row cache generation counter */
12184   int pc;                 /* The program counter */
12185   int rc;                 /* Value to return */
12186   char *zErrMsg;          /* Error message written here */
12187   u8 explain;             /* True if EXPLAIN present on SQL command */
12188   u8 changeCntOn;         /* True to update the change-counter */
12189   u8 expired;             /* True if the VM needs to be recompiled */
12190   u8 runOnlyOnce;         /* Automatically expire on reset */
12191   u8 minWriteFileFormat;  /* Minimum file format for writable database files */
12192   u8 inVtabMethod;        /* See comments above */
12193   u8 usesStmtJournal;     /* True if uses a statement journal */
12194   u8 readOnly;            /* True for read-only statements */
12195   u8 isPrepareV2;         /* True if prepared with prepare_v2() */
12196   int nChange;            /* Number of db changes made since last reset */
12197   int btreeMask;          /* Bitmask of db->aDb[] entries referenced */
12198   i64 startTime;          /* Time when query started - used for profiling */
12199   BtreeMutexArray aMutex; /* An array of Btree used here and needing locks */
12200   int aCounter[3];        /* Counters used by sqlite3_stmt_status() */
12201   char *zSql;             /* Text of the SQL statement that generated this */
12202   void *pFree;            /* Free this when deleting the vdbe */
12203   i64 nFkConstraint;      /* Number of imm. FK constraints this VM */
12204   i64 nStmtDefCons;       /* Number of def. constraints when stmt started */
12205   int iStatement;         /* Statement number (or 0 if has not opened stmt) */
12206 #ifdef SQLITE_DEBUG
12207   FILE *trace;            /* Write an execution trace here, if not NULL */
12208 #endif
12209   VdbeFrame *pFrame;      /* Parent frame */
12210   int nFrame;             /* Number of frames in pFrame list */
12211   u32 expmask;            /* Binding to these vars invalidates VM */
12212   SubProgram *pProgram;   /* Linked list of all sub-programs used by VM */
12213 };
12214
12215 /*
12216 ** The following are allowed values for Vdbe.magic
12217 */
12218 #define VDBE_MAGIC_INIT     0x26bceaa5    /* Building a VDBE program */
12219 #define VDBE_MAGIC_RUN      0xbdf20da3    /* VDBE is ready to execute */
12220 #define VDBE_MAGIC_HALT     0x519c2973    /* VDBE has completed execution */
12221 #define VDBE_MAGIC_DEAD     0xb606c3c8    /* The VDBE has been deallocated */
12222
12223 /*
12224 ** Function prototypes
12225 */
12226 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
12227 void sqliteVdbePopStack(Vdbe*,int);
12228 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
12229 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
12230 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
12231 #endif
12232 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
12233 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
12234 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int);
12235 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
12236 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc*, int);
12237
12238 int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
12239 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int*);
12240 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor *, i64 *);
12241 SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
12242 SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
12243 SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
12244 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
12245 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
12246 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
12247 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
12248 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
12249 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
12250 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
12251 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
12252 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
12253 #ifdef SQLITE_OMIT_FLOATING_POINT
12254 # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
12255 #else
12256 SQLITE_PRIVATE   void sqlite3VdbeMemSetDouble(Mem*, double);
12257 #endif
12258 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
12259 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
12260 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
12261 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
12262 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, int);
12263 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
12264 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
12265 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
12266 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
12267 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
12268 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
12269 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*);
12270 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
12271 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p);
12272 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
12273 SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
12274 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
12275 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
12276 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
12277 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
12278 SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem);
12279
12280 #ifdef SQLITE_DEBUG
12281 SQLITE_PRIVATE void sqlite3VdbeMemPrepareToChange(Vdbe*,Mem*);
12282 #endif
12283
12284 #ifndef SQLITE_OMIT_FOREIGN_KEY
12285 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
12286 #else
12287 # define sqlite3VdbeCheckFk(p,i) 0
12288 #endif
12289
12290 #ifndef SQLITE_OMIT_SHARED_CACHE
12291 SQLITE_PRIVATE void sqlite3VdbeMutexArrayEnter(Vdbe *p);
12292 #else
12293 # define sqlite3VdbeMutexArrayEnter(p)
12294 #endif
12295
12296 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
12297 #ifdef SQLITE_DEBUG
12298 SQLITE_PRIVATE   void sqlite3VdbePrintSql(Vdbe*);
12299 SQLITE_PRIVATE   void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
12300 #endif
12301 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
12302
12303 #ifndef SQLITE_OMIT_INCRBLOB
12304 SQLITE_PRIVATE   int sqlite3VdbeMemExpandBlob(Mem *);
12305 #else
12306   #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
12307 #endif
12308
12309 #endif /* !defined(_VDBEINT_H_) */
12310
12311 /************** End of vdbeInt.h *********************************************/
12312 /************** Continuing where we left off in status.c *********************/
12313
12314 /*
12315 ** Variables in which to record status information.
12316 */
12317 typedef struct sqlite3StatType sqlite3StatType;
12318 static SQLITE_WSD struct sqlite3StatType {
12319   int nowValue[10];         /* Current value */
12320   int mxValue[10];          /* Maximum value */
12321 } sqlite3Stat = { {0,}, {0,} };
12322
12323
12324 /* The "wsdStat" macro will resolve to the status information
12325 ** state vector.  If writable static data is unsupported on the target,
12326 ** we have to locate the state vector at run-time.  In the more common
12327 ** case where writable static data is supported, wsdStat can refer directly
12328 ** to the "sqlite3Stat" state vector declared above.
12329 */
12330 #ifdef SQLITE_OMIT_WSD
12331 # define wsdStatInit  sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
12332 # define wsdStat x[0]
12333 #else
12334 # define wsdStatInit
12335 # define wsdStat sqlite3Stat
12336 #endif
12337
12338 /*
12339 ** Return the current value of a status parameter.
12340 */
12341 SQLITE_PRIVATE int sqlite3StatusValue(int op){
12342   wsdStatInit;
12343   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
12344   return wsdStat.nowValue[op];
12345 }
12346
12347 /*
12348 ** Add N to the value of a status record.  It is assumed that the
12349 ** caller holds appropriate locks.
12350 */
12351 SQLITE_PRIVATE void sqlite3StatusAdd(int op, int N){
12352   wsdStatInit;
12353   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
12354   wsdStat.nowValue[op] += N;
12355   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
12356     wsdStat.mxValue[op] = wsdStat.nowValue[op];
12357   }
12358 }
12359
12360 /*
12361 ** Set the value of a status to X.
12362 */
12363 SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
12364   wsdStatInit;
12365   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
12366   wsdStat.nowValue[op] = X;
12367   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
12368     wsdStat.mxValue[op] = wsdStat.nowValue[op];
12369   }
12370 }
12371
12372 /*
12373 ** Query status information.
12374 **
12375 ** This implementation assumes that reading or writing an aligned
12376 ** 32-bit integer is an atomic operation.  If that assumption is not true,
12377 ** then this routine is not threadsafe.
12378 */
12379 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
12380   wsdStatInit;
12381   if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
12382     return SQLITE_MISUSE_BKPT;
12383   }
12384   *pCurrent = wsdStat.nowValue[op];
12385   *pHighwater = wsdStat.mxValue[op];
12386   if( resetFlag ){
12387     wsdStat.mxValue[op] = wsdStat.nowValue[op];
12388   }
12389   return SQLITE_OK;
12390 }
12391
12392 /*
12393 ** Query status information for a single database connection
12394 */
12395 SQLITE_API int sqlite3_db_status(
12396   sqlite3 *db,          /* The database connection whose status is desired */
12397   int op,               /* Status verb */
12398   int *pCurrent,        /* Write current value here */
12399   int *pHighwater,      /* Write high-water mark here */
12400   int resetFlag         /* Reset high-water mark if true */
12401 ){
12402   int rc = SQLITE_OK;   /* Return code */
12403   sqlite3_mutex_enter(db->mutex);
12404   switch( op ){
12405     case SQLITE_DBSTATUS_LOOKASIDE_USED: {
12406       *pCurrent = db->lookaside.nOut;
12407       *pHighwater = db->lookaside.mxOut;
12408       if( resetFlag ){
12409         db->lookaside.mxOut = db->lookaside.nOut;
12410       }
12411       break;
12412     }
12413
12414     /* 
12415     ** Return an approximation for the amount of memory currently used
12416     ** by all pagers associated with the given database connection.  The
12417     ** highwater mark is meaningless and is returned as zero.
12418     */
12419     case SQLITE_DBSTATUS_CACHE_USED: {
12420       int totalUsed = 0;
12421       int i;
12422       sqlite3BtreeEnterAll(db);
12423       for(i=0; i<db->nDb; i++){
12424         Btree *pBt = db->aDb[i].pBt;
12425         if( pBt ){
12426           Pager *pPager = sqlite3BtreePager(pBt);
12427           totalUsed += sqlite3PagerMemUsed(pPager);
12428         }
12429       }
12430       sqlite3BtreeLeaveAll(db);
12431       *pCurrent = totalUsed;
12432       *pHighwater = 0;
12433       break;
12434     }
12435
12436     /*
12437     ** *pCurrent gets an accurate estimate of the amount of memory used
12438     ** to store the schema for all databases (main, temp, and any ATTACHed
12439     ** databases.  *pHighwater is set to zero.
12440     */
12441     case SQLITE_DBSTATUS_SCHEMA_USED: {
12442       int i;                      /* Used to iterate through schemas */
12443       int nByte = 0;              /* Used to accumulate return value */
12444
12445       db->pnBytesFreed = &nByte;
12446       for(i=0; i<db->nDb; i++){
12447         Schema *pSchema = db->aDb[i].pSchema;
12448         if( ALWAYS(pSchema!=0) ){
12449           HashElem *p;
12450
12451           nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
12452               pSchema->tblHash.count 
12453             + pSchema->trigHash.count
12454             + pSchema->idxHash.count
12455             + pSchema->fkeyHash.count
12456           );
12457           nByte += sqlite3MallocSize(pSchema->tblHash.ht);
12458           nByte += sqlite3MallocSize(pSchema->trigHash.ht);
12459           nByte += sqlite3MallocSize(pSchema->idxHash.ht);
12460           nByte += sqlite3MallocSize(pSchema->fkeyHash.ht);
12461
12462           for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
12463             sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
12464           }
12465           for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
12466             sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
12467           }
12468         }
12469       }
12470       db->pnBytesFreed = 0;
12471
12472       *pHighwater = 0;
12473       *pCurrent = nByte;
12474       break;
12475     }
12476
12477     /*
12478     ** *pCurrent gets an accurate estimate of the amount of memory used
12479     ** to store all prepared statements.
12480     ** *pHighwater is set to zero.
12481     */
12482     case SQLITE_DBSTATUS_STMT_USED: {
12483       struct Vdbe *pVdbe;         /* Used to iterate through VMs */
12484       int nByte = 0;              /* Used to accumulate return value */
12485
12486       db->pnBytesFreed = &nByte;
12487       for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
12488         sqlite3VdbeDeleteObject(db, pVdbe);
12489       }
12490       db->pnBytesFreed = 0;
12491
12492       *pHighwater = 0;
12493       *pCurrent = nByte;
12494
12495       break;
12496     }
12497
12498     default: {
12499       rc = SQLITE_ERROR;
12500     }
12501   }
12502   sqlite3_mutex_leave(db->mutex);
12503   return rc;
12504 }
12505
12506 /************** End of status.c **********************************************/
12507 /************** Begin file date.c ********************************************/
12508 /*
12509 ** 2003 October 31
12510 **
12511 ** The author disclaims copyright to this source code.  In place of
12512 ** a legal notice, here is a blessing:
12513 **
12514 **    May you do good and not evil.
12515 **    May you find forgiveness for yourself and forgive others.
12516 **    May you share freely, never taking more than you give.
12517 **
12518 *************************************************************************
12519 ** This file contains the C functions that implement date and time
12520 ** functions for SQLite.  
12521 **
12522 ** There is only one exported symbol in this file - the function
12523 ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
12524 ** All other code has file scope.
12525 **
12526 ** SQLite processes all times and dates as Julian Day numbers.  The
12527 ** dates and times are stored as the number of days since noon
12528 ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
12529 ** calendar system. 
12530 **
12531 ** 1970-01-01 00:00:00 is JD 2440587.5
12532 ** 2000-01-01 00:00:00 is JD 2451544.5
12533 **
12534 ** This implemention requires years to be expressed as a 4-digit number
12535 ** which means that only dates between 0000-01-01 and 9999-12-31 can
12536 ** be represented, even though julian day numbers allow a much wider
12537 ** range of dates.
12538 **
12539 ** The Gregorian calendar system is used for all dates and times,
12540 ** even those that predate the Gregorian calendar.  Historians usually
12541 ** use the Julian calendar for dates prior to 1582-10-15 and for some
12542 ** dates afterwards, depending on locale.  Beware of this difference.
12543 **
12544 ** The conversion algorithms are implemented based on descriptions
12545 ** in the following text:
12546 **
12547 **      Jean Meeus
12548 **      Astronomical Algorithms, 2nd Edition, 1998
12549 **      ISBM 0-943396-61-1
12550 **      Willmann-Bell, Inc
12551 **      Richmond, Virginia (USA)
12552 */
12553 #include <time.h>
12554
12555 #ifndef SQLITE_OMIT_DATETIME_FUNCS
12556
12557 /*
12558 ** On recent Windows platforms, the localtime_s() function is available
12559 ** as part of the "Secure CRT". It is essentially equivalent to 
12560 ** localtime_r() available under most POSIX platforms, except that the 
12561 ** order of the parameters is reversed.
12562 **
12563 ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
12564 **
12565 ** If the user has not indicated to use localtime_r() or localtime_s()
12566 ** already, check for an MSVC build environment that provides 
12567 ** localtime_s().
12568 */
12569 #if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
12570      defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
12571 #define HAVE_LOCALTIME_S 1
12572 #endif
12573
12574 /*
12575 ** A structure for holding a single date and time.
12576 */
12577 typedef struct DateTime DateTime;
12578 struct DateTime {
12579   sqlite3_int64 iJD; /* The julian day number times 86400000 */
12580   int Y, M, D;       /* Year, month, and day */
12581   int h, m;          /* Hour and minutes */
12582   int tz;            /* Timezone offset in minutes */
12583   double s;          /* Seconds */
12584   char validYMD;     /* True (1) if Y,M,D are valid */
12585   char validHMS;     /* True (1) if h,m,s are valid */
12586   char validJD;      /* True (1) if iJD is valid */
12587   char validTZ;      /* True (1) if tz is valid */
12588 };
12589
12590
12591 /*
12592 ** Convert zDate into one or more integers.  Additional arguments
12593 ** come in groups of 5 as follows:
12594 **
12595 **       N       number of digits in the integer
12596 **       min     minimum allowed value of the integer
12597 **       max     maximum allowed value of the integer
12598 **       nextC   first character after the integer
12599 **       pVal    where to write the integers value.
12600 **
12601 ** Conversions continue until one with nextC==0 is encountered.
12602 ** The function returns the number of successful conversions.
12603 */
12604 static int getDigits(const char *zDate, ...){
12605   va_list ap;
12606   int val;
12607   int N;
12608   int min;
12609   int max;
12610   int nextC;
12611   int *pVal;
12612   int cnt = 0;
12613   va_start(ap, zDate);
12614   do{
12615     N = va_arg(ap, int);
12616     min = va_arg(ap, int);
12617     max = va_arg(ap, int);
12618     nextC = va_arg(ap, int);
12619     pVal = va_arg(ap, int*);
12620     val = 0;
12621     while( N-- ){
12622       if( !sqlite3Isdigit(*zDate) ){
12623         goto end_getDigits;
12624       }
12625       val = val*10 + *zDate - '0';
12626       zDate++;
12627     }
12628     if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
12629       goto end_getDigits;
12630     }
12631     *pVal = val;
12632     zDate++;
12633     cnt++;
12634   }while( nextC );
12635 end_getDigits:
12636   va_end(ap);
12637   return cnt;
12638 }
12639
12640 /*
12641 ** Parse a timezone extension on the end of a date-time.
12642 ** The extension is of the form:
12643 **
12644 **        (+/-)HH:MM
12645 **
12646 ** Or the "zulu" notation:
12647 **
12648 **        Z
12649 **
12650 ** If the parse is successful, write the number of minutes
12651 ** of change in p->tz and return 0.  If a parser error occurs,
12652 ** return non-zero.
12653 **
12654 ** A missing specifier is not considered an error.
12655 */
12656 static int parseTimezone(const char *zDate, DateTime *p){
12657   int sgn = 0;
12658   int nHr, nMn;
12659   int c;
12660   while( sqlite3Isspace(*zDate) ){ zDate++; }
12661   p->tz = 0;
12662   c = *zDate;
12663   if( c=='-' ){
12664     sgn = -1;
12665   }else if( c=='+' ){
12666     sgn = +1;
12667   }else if( c=='Z' || c=='z' ){
12668     zDate++;
12669     goto zulu_time;
12670   }else{
12671     return c!=0;
12672   }
12673   zDate++;
12674   if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
12675     return 1;
12676   }
12677   zDate += 5;
12678   p->tz = sgn*(nMn + nHr*60);
12679 zulu_time:
12680   while( sqlite3Isspace(*zDate) ){ zDate++; }
12681   return *zDate!=0;
12682 }
12683
12684 /*
12685 ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
12686 ** The HH, MM, and SS must each be exactly 2 digits.  The
12687 ** fractional seconds FFFF can be one or more digits.
12688 **
12689 ** Return 1 if there is a parsing error and 0 on success.
12690 */
12691 static int parseHhMmSs(const char *zDate, DateTime *p){
12692   int h, m, s;
12693   double ms = 0.0;
12694   if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
12695     return 1;
12696   }
12697   zDate += 5;
12698   if( *zDate==':' ){
12699     zDate++;
12700     if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
12701       return 1;
12702     }
12703     zDate += 2;
12704     if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
12705       double rScale = 1.0;
12706       zDate++;
12707       while( sqlite3Isdigit(*zDate) ){
12708         ms = ms*10.0 + *zDate - '0';
12709         rScale *= 10.0;
12710         zDate++;
12711       }
12712       ms /= rScale;
12713     }
12714   }else{
12715     s = 0;
12716   }
12717   p->validJD = 0;
12718   p->validHMS = 1;
12719   p->h = h;
12720   p->m = m;
12721   p->s = s + ms;
12722   if( parseTimezone(zDate, p) ) return 1;
12723   p->validTZ = (p->tz!=0)?1:0;
12724   return 0;
12725 }
12726
12727 /*
12728 ** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
12729 ** that the YYYY-MM-DD is according to the Gregorian calendar.
12730 **
12731 ** Reference:  Meeus page 61
12732 */
12733 static void computeJD(DateTime *p){
12734   int Y, M, D, A, B, X1, X2;
12735
12736   if( p->validJD ) return;
12737   if( p->validYMD ){
12738     Y = p->Y;
12739     M = p->M;
12740     D = p->D;
12741   }else{
12742     Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
12743     M = 1;
12744     D = 1;
12745   }
12746   if( M<=2 ){
12747     Y--;
12748     M += 12;
12749   }
12750   A = Y/100;
12751   B = 2 - A + (A/4);
12752   X1 = 36525*(Y+4716)/100;
12753   X2 = 306001*(M+1)/10000;
12754   p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
12755   p->validJD = 1;
12756   if( p->validHMS ){
12757     p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
12758     if( p->validTZ ){
12759       p->iJD -= p->tz*60000;
12760       p->validYMD = 0;
12761       p->validHMS = 0;
12762       p->validTZ = 0;
12763     }
12764   }
12765 }
12766
12767 /*
12768 ** Parse dates of the form
12769 **
12770 **     YYYY-MM-DD HH:MM:SS.FFF
12771 **     YYYY-MM-DD HH:MM:SS
12772 **     YYYY-MM-DD HH:MM
12773 **     YYYY-MM-DD
12774 **
12775 ** Write the result into the DateTime structure and return 0
12776 ** on success and 1 if the input string is not a well-formed
12777 ** date.
12778 */
12779 static int parseYyyyMmDd(const char *zDate, DateTime *p){
12780   int Y, M, D, neg;
12781
12782   if( zDate[0]=='-' ){
12783     zDate++;
12784     neg = 1;
12785   }else{
12786     neg = 0;
12787   }
12788   if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
12789     return 1;
12790   }
12791   zDate += 10;
12792   while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
12793   if( parseHhMmSs(zDate, p)==0 ){
12794     /* We got the time */
12795   }else if( *zDate==0 ){
12796     p->validHMS = 0;
12797   }else{
12798     return 1;
12799   }
12800   p->validJD = 0;
12801   p->validYMD = 1;
12802   p->Y = neg ? -Y : Y;
12803   p->M = M;
12804   p->D = D;
12805   if( p->validTZ ){
12806     computeJD(p);
12807   }
12808   return 0;
12809 }
12810
12811 /*
12812 ** Set the time to the current time reported by the VFS
12813 */
12814 static void setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
12815   sqlite3 *db = sqlite3_context_db_handle(context);
12816   sqlite3OsCurrentTimeInt64(db->pVfs, &p->iJD);
12817   p->validJD = 1;
12818 }
12819
12820 /*
12821 ** Attempt to parse the given string into a Julian Day Number.  Return
12822 ** the number of errors.
12823 **
12824 ** The following are acceptable forms for the input string:
12825 **
12826 **      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
12827 **      DDDD.DD 
12828 **      now
12829 **
12830 ** In the first form, the +/-HH:MM is always optional.  The fractional
12831 ** seconds extension (the ".FFF") is optional.  The seconds portion
12832 ** (":SS.FFF") is option.  The year and date can be omitted as long
12833 ** as there is a time string.  The time string can be omitted as long
12834 ** as there is a year and date.
12835 */
12836 static int parseDateOrTime(
12837   sqlite3_context *context, 
12838   const char *zDate, 
12839   DateTime *p
12840 ){
12841   double r;
12842   if( parseYyyyMmDd(zDate,p)==0 ){
12843     return 0;
12844   }else if( parseHhMmSs(zDate, p)==0 ){
12845     return 0;
12846   }else if( sqlite3StrICmp(zDate,"now")==0){
12847     setDateTimeToCurrent(context, p);
12848     return 0;
12849   }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
12850     p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
12851     p->validJD = 1;
12852     return 0;
12853   }
12854   return 1;
12855 }
12856
12857 /*
12858 ** Compute the Year, Month, and Day from the julian day number.
12859 */
12860 static void computeYMD(DateTime *p){
12861   int Z, A, B, C, D, E, X1;
12862   if( p->validYMD ) return;
12863   if( !p->validJD ){
12864     p->Y = 2000;
12865     p->M = 1;
12866     p->D = 1;
12867   }else{
12868     Z = (int)((p->iJD + 43200000)/86400000);
12869     A = (int)((Z - 1867216.25)/36524.25);
12870     A = Z + 1 + A - (A/4);
12871     B = A + 1524;
12872     C = (int)((B - 122.1)/365.25);
12873     D = (36525*C)/100;
12874     E = (int)((B-D)/30.6001);
12875     X1 = (int)(30.6001*E);
12876     p->D = B - D - X1;
12877     p->M = E<14 ? E-1 : E-13;
12878     p->Y = p->M>2 ? C - 4716 : C - 4715;
12879   }
12880   p->validYMD = 1;
12881 }
12882
12883 /*
12884 ** Compute the Hour, Minute, and Seconds from the julian day number.
12885 */
12886 static void computeHMS(DateTime *p){
12887   int s;
12888   if( p->validHMS ) return;
12889   computeJD(p);
12890   s = (int)((p->iJD + 43200000) % 86400000);
12891   p->s = s/1000.0;
12892   s = (int)p->s;
12893   p->s -= s;
12894   p->h = s/3600;
12895   s -= p->h*3600;
12896   p->m = s/60;
12897   p->s += s - p->m*60;
12898   p->validHMS = 1;
12899 }
12900
12901 /*
12902 ** Compute both YMD and HMS
12903 */
12904 static void computeYMD_HMS(DateTime *p){
12905   computeYMD(p);
12906   computeHMS(p);
12907 }
12908
12909 /*
12910 ** Clear the YMD and HMS and the TZ
12911 */
12912 static void clearYMD_HMS_TZ(DateTime *p){
12913   p->validYMD = 0;
12914   p->validHMS = 0;
12915   p->validTZ = 0;
12916 }
12917
12918 #ifndef SQLITE_OMIT_LOCALTIME
12919 /*
12920 ** Compute the difference (in milliseconds)
12921 ** between localtime and UTC (a.k.a. GMT)
12922 ** for the time value p where p is in UTC.
12923 */
12924 static sqlite3_int64 localtimeOffset(DateTime *p){
12925   DateTime x, y;
12926   time_t t;
12927   x = *p;
12928   computeYMD_HMS(&x);
12929   if( x.Y<1971 || x.Y>=2038 ){
12930     x.Y = 2000;
12931     x.M = 1;
12932     x.D = 1;
12933     x.h = 0;
12934     x.m = 0;
12935     x.s = 0.0;
12936   } else {
12937     int s = (int)(x.s + 0.5);
12938     x.s = s;
12939   }
12940   x.tz = 0;
12941   x.validJD = 0;
12942   computeJD(&x);
12943   t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
12944 #ifdef HAVE_LOCALTIME_R
12945   {
12946     struct tm sLocal;
12947     localtime_r(&t, &sLocal);
12948     y.Y = sLocal.tm_year + 1900;
12949     y.M = sLocal.tm_mon + 1;
12950     y.D = sLocal.tm_mday;
12951     y.h = sLocal.tm_hour;
12952     y.m = sLocal.tm_min;
12953     y.s = sLocal.tm_sec;
12954   }
12955 #elif defined(HAVE_LOCALTIME_S) && HAVE_LOCALTIME_S
12956   {
12957     struct tm sLocal;
12958     localtime_s(&sLocal, &t);
12959     y.Y = sLocal.tm_year + 1900;
12960     y.M = sLocal.tm_mon + 1;
12961     y.D = sLocal.tm_mday;
12962     y.h = sLocal.tm_hour;
12963     y.m = sLocal.tm_min;
12964     y.s = sLocal.tm_sec;
12965   }
12966 #else
12967   {
12968     struct tm *pTm;
12969     sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
12970     pTm = localtime(&t);
12971     y.Y = pTm->tm_year + 1900;
12972     y.M = pTm->tm_mon + 1;
12973     y.D = pTm->tm_mday;
12974     y.h = pTm->tm_hour;
12975     y.m = pTm->tm_min;
12976     y.s = pTm->tm_sec;
12977     sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
12978   }
12979 #endif
12980   y.validYMD = 1;
12981   y.validHMS = 1;
12982   y.validJD = 0;
12983   y.validTZ = 0;
12984   computeJD(&y);
12985   return y.iJD - x.iJD;
12986 }
12987 #endif /* SQLITE_OMIT_LOCALTIME */
12988
12989 /*
12990 ** Process a modifier to a date-time stamp.  The modifiers are
12991 ** as follows:
12992 **
12993 **     NNN days
12994 **     NNN hours
12995 **     NNN minutes
12996 **     NNN.NNNN seconds
12997 **     NNN months
12998 **     NNN years
12999 **     start of month
13000 **     start of year
13001 **     start of week
13002 **     start of day
13003 **     weekday N
13004 **     unixepoch
13005 **     localtime
13006 **     utc
13007 **
13008 ** Return 0 on success and 1 if there is any kind of error.
13009 */
13010 static int parseModifier(const char *zMod, DateTime *p){
13011   int rc = 1;
13012   int n;
13013   double r;
13014   char *z, zBuf[30];
13015   z = zBuf;
13016   for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
13017     z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
13018   }
13019   z[n] = 0;
13020   switch( z[0] ){
13021 #ifndef SQLITE_OMIT_LOCALTIME
13022     case 'l': {
13023       /*    localtime
13024       **
13025       ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
13026       ** show local time.
13027       */
13028       if( strcmp(z, "localtime")==0 ){
13029         computeJD(p);
13030         p->iJD += localtimeOffset(p);
13031         clearYMD_HMS_TZ(p);
13032         rc = 0;
13033       }
13034       break;
13035     }
13036 #endif
13037     case 'u': {
13038       /*
13039       **    unixepoch
13040       **
13041       ** Treat the current value of p->iJD as the number of
13042       ** seconds since 1970.  Convert to a real julian day number.
13043       */
13044       if( strcmp(z, "unixepoch")==0 && p->validJD ){
13045         p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
13046         clearYMD_HMS_TZ(p);
13047         rc = 0;
13048       }
13049 #ifndef SQLITE_OMIT_LOCALTIME
13050       else if( strcmp(z, "utc")==0 ){
13051         sqlite3_int64 c1;
13052         computeJD(p);
13053         c1 = localtimeOffset(p);
13054         p->iJD -= c1;
13055         clearYMD_HMS_TZ(p);
13056         p->iJD += c1 - localtimeOffset(p);
13057         rc = 0;
13058       }
13059 #endif
13060       break;
13061     }
13062     case 'w': {
13063       /*
13064       **    weekday N
13065       **
13066       ** Move the date to the same time on the next occurrence of
13067       ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
13068       ** date is already on the appropriate weekday, this is a no-op.
13069       */
13070       if( strncmp(z, "weekday ", 8)==0
13071                && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
13072                && (n=(int)r)==r && n>=0 && r<7 ){
13073         sqlite3_int64 Z;
13074         computeYMD_HMS(p);
13075         p->validTZ = 0;
13076         p->validJD = 0;
13077         computeJD(p);
13078         Z = ((p->iJD + 129600000)/86400000) % 7;
13079         if( Z>n ) Z -= 7;
13080         p->iJD += (n - Z)*86400000;
13081         clearYMD_HMS_TZ(p);
13082         rc = 0;
13083       }
13084       break;
13085     }
13086     case 's': {
13087       /*
13088       **    start of TTTTT
13089       **
13090       ** Move the date backwards to the beginning of the current day,
13091       ** or month or year.
13092       */
13093       if( strncmp(z, "start of ", 9)!=0 ) break;
13094       z += 9;
13095       computeYMD(p);
13096       p->validHMS = 1;
13097       p->h = p->m = 0;
13098       p->s = 0.0;
13099       p->validTZ = 0;
13100       p->validJD = 0;
13101       if( strcmp(z,"month")==0 ){
13102         p->D = 1;
13103         rc = 0;
13104       }else if( strcmp(z,"year")==0 ){
13105         computeYMD(p);
13106         p->M = 1;
13107         p->D = 1;
13108         rc = 0;
13109       }else if( strcmp(z,"day")==0 ){
13110         rc = 0;
13111       }
13112       break;
13113     }
13114     case '+':
13115     case '-':
13116     case '0':
13117     case '1':
13118     case '2':
13119     case '3':
13120     case '4':
13121     case '5':
13122     case '6':
13123     case '7':
13124     case '8':
13125     case '9': {
13126       double rRounder;
13127       for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
13128       if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
13129         rc = 1;
13130         break;
13131       }
13132       if( z[n]==':' ){
13133         /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
13134         ** specified number of hours, minutes, seconds, and fractional seconds
13135         ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
13136         ** omitted.
13137         */
13138         const char *z2 = z;
13139         DateTime tx;
13140         sqlite3_int64 day;
13141         if( !sqlite3Isdigit(*z2) ) z2++;
13142         memset(&tx, 0, sizeof(tx));
13143         if( parseHhMmSs(z2, &tx) ) break;
13144         computeJD(&tx);
13145         tx.iJD -= 43200000;
13146         day = tx.iJD/86400000;
13147         tx.iJD -= day*86400000;
13148         if( z[0]=='-' ) tx.iJD = -tx.iJD;
13149         computeJD(p);
13150         clearYMD_HMS_TZ(p);
13151         p->iJD += tx.iJD;
13152         rc = 0;
13153         break;
13154       }
13155       z += n;
13156       while( sqlite3Isspace(*z) ) z++;
13157       n = sqlite3Strlen30(z);
13158       if( n>10 || n<3 ) break;
13159       if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
13160       computeJD(p);
13161       rc = 0;
13162       rRounder = r<0 ? -0.5 : +0.5;
13163       if( n==3 && strcmp(z,"day")==0 ){
13164         p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
13165       }else if( n==4 && strcmp(z,"hour")==0 ){
13166         p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
13167       }else if( n==6 && strcmp(z,"minute")==0 ){
13168         p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
13169       }else if( n==6 && strcmp(z,"second")==0 ){
13170         p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
13171       }else if( n==5 && strcmp(z,"month")==0 ){
13172         int x, y;
13173         computeYMD_HMS(p);
13174         p->M += (int)r;
13175         x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
13176         p->Y += x;
13177         p->M -= x*12;
13178         p->validJD = 0;
13179         computeJD(p);
13180         y = (int)r;
13181         if( y!=r ){
13182           p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
13183         }
13184       }else if( n==4 && strcmp(z,"year")==0 ){
13185         int y = (int)r;
13186         computeYMD_HMS(p);
13187         p->Y += y;
13188         p->validJD = 0;
13189         computeJD(p);
13190         if( y!=r ){
13191           p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
13192         }
13193       }else{
13194         rc = 1;
13195       }
13196       clearYMD_HMS_TZ(p);
13197       break;
13198     }
13199     default: {
13200       break;
13201     }
13202   }
13203   return rc;
13204 }
13205
13206 /*
13207 ** Process time function arguments.  argv[0] is a date-time stamp.
13208 ** argv[1] and following are modifiers.  Parse them all and write
13209 ** the resulting time into the DateTime structure p.  Return 0
13210 ** on success and 1 if there are any errors.
13211 **
13212 ** If there are zero parameters (if even argv[0] is undefined)
13213 ** then assume a default value of "now" for argv[0].
13214 */
13215 static int isDate(
13216   sqlite3_context *context, 
13217   int argc, 
13218   sqlite3_value **argv, 
13219   DateTime *p
13220 ){
13221   int i;
13222   const unsigned char *z;
13223   int eType;
13224   memset(p, 0, sizeof(*p));
13225   if( argc==0 ){
13226     setDateTimeToCurrent(context, p);
13227   }else if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
13228                    || eType==SQLITE_INTEGER ){
13229     p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
13230     p->validJD = 1;
13231   }else{
13232     z = sqlite3_value_text(argv[0]);
13233     if( !z || parseDateOrTime(context, (char*)z, p) ){
13234       return 1;
13235     }
13236   }
13237   for(i=1; i<argc; i++){
13238     if( (z = sqlite3_value_text(argv[i]))==0 || parseModifier((char*)z, p) ){
13239       return 1;
13240     }
13241   }
13242   return 0;
13243 }
13244
13245
13246 /*
13247 ** The following routines implement the various date and time functions
13248 ** of SQLite.
13249 */
13250
13251 /*
13252 **    julianday( TIMESTRING, MOD, MOD, ...)
13253 **
13254 ** Return the julian day number of the date specified in the arguments
13255 */
13256 static void juliandayFunc(
13257   sqlite3_context *context,
13258   int argc,
13259   sqlite3_value **argv
13260 ){
13261   DateTime x;
13262   if( isDate(context, argc, argv, &x)==0 ){
13263     computeJD(&x);
13264     sqlite3_result_double(context, x.iJD/86400000.0);
13265   }
13266 }
13267
13268 /*
13269 **    datetime( TIMESTRING, MOD, MOD, ...)
13270 **
13271 ** Return YYYY-MM-DD HH:MM:SS
13272 */
13273 static void datetimeFunc(
13274   sqlite3_context *context,
13275   int argc,
13276   sqlite3_value **argv
13277 ){
13278   DateTime x;
13279   if( isDate(context, argc, argv, &x)==0 ){
13280     char zBuf[100];
13281     computeYMD_HMS(&x);
13282     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
13283                      x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
13284     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
13285   }
13286 }
13287
13288 /*
13289 **    time( TIMESTRING, MOD, MOD, ...)
13290 **
13291 ** Return HH:MM:SS
13292 */
13293 static void timeFunc(
13294   sqlite3_context *context,
13295   int argc,
13296   sqlite3_value **argv
13297 ){
13298   DateTime x;
13299   if( isDate(context, argc, argv, &x)==0 ){
13300     char zBuf[100];
13301     computeHMS(&x);
13302     sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
13303     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
13304   }
13305 }
13306
13307 /*
13308 **    date( TIMESTRING, MOD, MOD, ...)
13309 **
13310 ** Return YYYY-MM-DD
13311 */
13312 static void dateFunc(
13313   sqlite3_context *context,
13314   int argc,
13315   sqlite3_value **argv
13316 ){
13317   DateTime x;
13318   if( isDate(context, argc, argv, &x)==0 ){
13319     char zBuf[100];
13320     computeYMD(&x);
13321     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
13322     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
13323   }
13324 }
13325
13326 /*
13327 **    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
13328 **
13329 ** Return a string described by FORMAT.  Conversions as follows:
13330 **
13331 **   %d  day of month
13332 **   %f  ** fractional seconds  SS.SSS
13333 **   %H  hour 00-24
13334 **   %j  day of year 000-366
13335 **   %J  ** Julian day number
13336 **   %m  month 01-12
13337 **   %M  minute 00-59
13338 **   %s  seconds since 1970-01-01
13339 **   %S  seconds 00-59
13340 **   %w  day of week 0-6  sunday==0
13341 **   %W  week of year 00-53
13342 **   %Y  year 0000-9999
13343 **   %%  %
13344 */
13345 static void strftimeFunc(
13346   sqlite3_context *context,
13347   int argc,
13348   sqlite3_value **argv
13349 ){
13350   DateTime x;
13351   u64 n;
13352   size_t i,j;
13353   char *z;
13354   sqlite3 *db;
13355   const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
13356   char zBuf[100];
13357   if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
13358   db = sqlite3_context_db_handle(context);
13359   for(i=0, n=1; zFmt[i]; i++, n++){
13360     if( zFmt[i]=='%' ){
13361       switch( zFmt[i+1] ){
13362         case 'd':
13363         case 'H':
13364         case 'm':
13365         case 'M':
13366         case 'S':
13367         case 'W':
13368           n++;
13369           /* fall thru */
13370         case 'w':
13371         case '%':
13372           break;
13373         case 'f':
13374           n += 8;
13375           break;
13376         case 'j':
13377           n += 3;
13378           break;
13379         case 'Y':
13380           n += 8;
13381           break;
13382         case 's':
13383         case 'J':
13384           n += 50;
13385           break;
13386         default:
13387           return;  /* ERROR.  return a NULL */
13388       }
13389       i++;
13390     }
13391   }
13392   testcase( n==sizeof(zBuf)-1 );
13393   testcase( n==sizeof(zBuf) );
13394   testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
13395   testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
13396   if( n<sizeof(zBuf) ){
13397     z = zBuf;
13398   }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
13399     sqlite3_result_error_toobig(context);
13400     return;
13401   }else{
13402     z = sqlite3DbMallocRaw(db, (int)n);
13403     if( z==0 ){
13404       sqlite3_result_error_nomem(context);
13405       return;
13406     }
13407   }
13408   computeJD(&x);
13409   computeYMD_HMS(&x);
13410   for(i=j=0; zFmt[i]; i++){
13411     if( zFmt[i]!='%' ){
13412       z[j++] = zFmt[i];
13413     }else{
13414       i++;
13415       switch( zFmt[i] ){
13416         case 'd':  sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
13417         case 'f': {
13418           double s = x.s;
13419           if( s>59.999 ) s = 59.999;
13420           sqlite3_snprintf(7, &z[j],"%06.3f", s);
13421           j += sqlite3Strlen30(&z[j]);
13422           break;
13423         }
13424         case 'H':  sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
13425         case 'W': /* Fall thru */
13426         case 'j': {
13427           int nDay;             /* Number of days since 1st day of year */
13428           DateTime y = x;
13429           y.validJD = 0;
13430           y.M = 1;
13431           y.D = 1;
13432           computeJD(&y);
13433           nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
13434           if( zFmt[i]=='W' ){
13435             int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
13436             wd = (int)(((x.iJD+43200000)/86400000)%7);
13437             sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
13438             j += 2;
13439           }else{
13440             sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
13441             j += 3;
13442           }
13443           break;
13444         }
13445         case 'J': {
13446           sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
13447           j+=sqlite3Strlen30(&z[j]);
13448           break;
13449         }
13450         case 'm':  sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
13451         case 'M':  sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
13452         case 's': {
13453           sqlite3_snprintf(30,&z[j],"%lld",
13454                            (i64)(x.iJD/1000 - 21086676*(i64)10000));
13455           j += sqlite3Strlen30(&z[j]);
13456           break;
13457         }
13458         case 'S':  sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
13459         case 'w': {
13460           z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
13461           break;
13462         }
13463         case 'Y': {
13464           sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
13465           break;
13466         }
13467         default:   z[j++] = '%'; break;
13468       }
13469     }
13470   }
13471   z[j] = 0;
13472   sqlite3_result_text(context, z, -1,
13473                       z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
13474 }
13475
13476 /*
13477 ** current_time()
13478 **
13479 ** This function returns the same value as time('now').
13480 */
13481 static void ctimeFunc(
13482   sqlite3_context *context,
13483   int NotUsed,
13484   sqlite3_value **NotUsed2
13485 ){
13486   UNUSED_PARAMETER2(NotUsed, NotUsed2);
13487   timeFunc(context, 0, 0);
13488 }
13489
13490 /*
13491 ** current_date()
13492 **
13493 ** This function returns the same value as date('now').
13494 */
13495 static void cdateFunc(
13496   sqlite3_context *context,
13497   int NotUsed,
13498   sqlite3_value **NotUsed2
13499 ){
13500   UNUSED_PARAMETER2(NotUsed, NotUsed2);
13501   dateFunc(context, 0, 0);
13502 }
13503
13504 /*
13505 ** current_timestamp()
13506 **
13507 ** This function returns the same value as datetime('now').
13508 */
13509 static void ctimestampFunc(
13510   sqlite3_context *context,
13511   int NotUsed,
13512   sqlite3_value **NotUsed2
13513 ){
13514   UNUSED_PARAMETER2(NotUsed, NotUsed2);
13515   datetimeFunc(context, 0, 0);
13516 }
13517 #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
13518
13519 #ifdef SQLITE_OMIT_DATETIME_FUNCS
13520 /*
13521 ** If the library is compiled to omit the full-scale date and time
13522 ** handling (to get a smaller binary), the following minimal version
13523 ** of the functions current_time(), current_date() and current_timestamp()
13524 ** are included instead. This is to support column declarations that
13525 ** include "DEFAULT CURRENT_TIME" etc.
13526 **
13527 ** This function uses the C-library functions time(), gmtime()
13528 ** and strftime(). The format string to pass to strftime() is supplied
13529 ** as the user-data for the function.
13530 */
13531 static void currentTimeFunc(
13532   sqlite3_context *context,
13533   int argc,
13534   sqlite3_value **argv
13535 ){
13536   time_t t;
13537   char *zFormat = (char *)sqlite3_user_data(context);
13538   sqlite3 *db;
13539   sqlite3_int64 iT;
13540   char zBuf[20];
13541
13542   UNUSED_PARAMETER(argc);
13543   UNUSED_PARAMETER(argv);
13544
13545   db = sqlite3_context_db_handle(context);
13546   sqlite3OsCurrentTimeInt64(db->pVfs, &iT);
13547   t = iT/1000 - 10000*(sqlite3_int64)21086676;
13548 #ifdef HAVE_GMTIME_R
13549   {
13550     struct tm sNow;
13551     gmtime_r(&t, &sNow);
13552     strftime(zBuf, 20, zFormat, &sNow);
13553   }
13554 #else
13555   {
13556     struct tm *pTm;
13557     sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
13558     pTm = gmtime(&t);
13559     strftime(zBuf, 20, zFormat, pTm);
13560     sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
13561   }
13562 #endif
13563
13564   sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
13565 }
13566 #endif
13567
13568 /*
13569 ** This function registered all of the above C functions as SQL
13570 ** functions.  This should be the only routine in this file with
13571 ** external linkage.
13572 */
13573 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
13574   static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
13575 #ifndef SQLITE_OMIT_DATETIME_FUNCS
13576     FUNCTION(julianday,        -1, 0, 0, juliandayFunc ),
13577     FUNCTION(date,             -1, 0, 0, dateFunc      ),
13578     FUNCTION(time,             -1, 0, 0, timeFunc      ),
13579     FUNCTION(datetime,         -1, 0, 0, datetimeFunc  ),
13580     FUNCTION(strftime,         -1, 0, 0, strftimeFunc  ),
13581     FUNCTION(current_time,      0, 0, 0, ctimeFunc     ),
13582     FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
13583     FUNCTION(current_date,      0, 0, 0, cdateFunc     ),
13584 #else
13585     STR_FUNCTION(current_time,      0, "%H:%M:%S",          0, currentTimeFunc),
13586     STR_FUNCTION(current_date,      0, "%Y-%m-%d",          0, currentTimeFunc),
13587     STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
13588 #endif
13589   };
13590   int i;
13591   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
13592   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
13593
13594   for(i=0; i<ArraySize(aDateTimeFuncs); i++){
13595     sqlite3FuncDefInsert(pHash, &aFunc[i]);
13596   }
13597 }
13598
13599 /************** End of date.c ************************************************/
13600 /************** Begin file os.c **********************************************/
13601 /*
13602 ** 2005 November 29
13603 **
13604 ** The author disclaims copyright to this source code.  In place of
13605 ** a legal notice, here is a blessing:
13606 **
13607 **    May you do good and not evil.
13608 **    May you find forgiveness for yourself and forgive others.
13609 **    May you share freely, never taking more than you give.
13610 **
13611 ******************************************************************************
13612 **
13613 ** This file contains OS interface code that is common to all
13614 ** architectures.
13615 */
13616 #define _SQLITE_OS_C_ 1
13617 #undef _SQLITE_OS_C_
13618
13619 /*
13620 ** The default SQLite sqlite3_vfs implementations do not allocate
13621 ** memory (actually, os_unix.c allocates a small amount of memory
13622 ** from within OsOpen()), but some third-party implementations may.
13623 ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
13624 ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
13625 **
13626 ** The following functions are instrumented for malloc() failure 
13627 ** testing:
13628 **
13629 **     sqlite3OsOpen()
13630 **     sqlite3OsRead()
13631 **     sqlite3OsWrite()
13632 **     sqlite3OsSync()
13633 **     sqlite3OsLock()
13634 **
13635 */
13636 #if defined(SQLITE_TEST)
13637 SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
13638   #define DO_OS_MALLOC_TEST(x)                                       \
13639   if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3IsMemJournal(x))) {  \
13640     void *pTstAlloc = sqlite3Malloc(10);                             \
13641     if (!pTstAlloc) return SQLITE_IOERR_NOMEM;                       \
13642     sqlite3_free(pTstAlloc);                                         \
13643   }
13644 #else
13645   #define DO_OS_MALLOC_TEST(x)
13646 #endif
13647
13648 /*
13649 ** The following routines are convenience wrappers around methods
13650 ** of the sqlite3_file object.  This is mostly just syntactic sugar. All
13651 ** of this would be completely automatic if SQLite were coded using
13652 ** C++ instead of plain old C.
13653 */
13654 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
13655   int rc = SQLITE_OK;
13656   if( pId->pMethods ){
13657     rc = pId->pMethods->xClose(pId);
13658     pId->pMethods = 0;
13659   }
13660   return rc;
13661 }
13662 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
13663   DO_OS_MALLOC_TEST(id);
13664   return id->pMethods->xRead(id, pBuf, amt, offset);
13665 }
13666 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
13667   DO_OS_MALLOC_TEST(id);
13668   return id->pMethods->xWrite(id, pBuf, amt, offset);
13669 }
13670 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
13671   return id->pMethods->xTruncate(id, size);
13672 }
13673 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
13674   DO_OS_MALLOC_TEST(id);
13675   return id->pMethods->xSync(id, flags);
13676 }
13677 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
13678   DO_OS_MALLOC_TEST(id);
13679   return id->pMethods->xFileSize(id, pSize);
13680 }
13681 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
13682   DO_OS_MALLOC_TEST(id);
13683   return id->pMethods->xLock(id, lockType);
13684 }
13685 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
13686   return id->pMethods->xUnlock(id, lockType);
13687 }
13688 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
13689   DO_OS_MALLOC_TEST(id);
13690   return id->pMethods->xCheckReservedLock(id, pResOut);
13691 }
13692 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
13693   return id->pMethods->xFileControl(id, op, pArg);
13694 }
13695 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
13696   int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
13697   return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
13698 }
13699 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
13700   return id->pMethods->xDeviceCharacteristics(id);
13701 }
13702 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
13703   return id->pMethods->xShmLock(id, offset, n, flags);
13704 }
13705 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
13706   id->pMethods->xShmBarrier(id);
13707 }
13708 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
13709   return id->pMethods->xShmUnmap(id, deleteFlag);
13710 }
13711 SQLITE_PRIVATE int sqlite3OsShmMap(
13712   sqlite3_file *id,               /* Database file handle */
13713   int iPage,
13714   int pgsz,
13715   int bExtend,                    /* True to extend file if necessary */
13716   void volatile **pp              /* OUT: Pointer to mapping */
13717 ){
13718   return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
13719 }
13720
13721 /*
13722 ** The next group of routines are convenience wrappers around the
13723 ** VFS methods.
13724 */
13725 SQLITE_PRIVATE int sqlite3OsOpen(
13726   sqlite3_vfs *pVfs, 
13727   const char *zPath, 
13728   sqlite3_file *pFile, 
13729   int flags, 
13730   int *pFlagsOut
13731 ){
13732   int rc;
13733   DO_OS_MALLOC_TEST(0);
13734   /* 0x87f3f is a mask of SQLITE_OPEN_ flags that are valid to be passed
13735   ** down into the VFS layer.  Some SQLITE_OPEN_ flags (for example,
13736   ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
13737   ** reaching the VFS. */
13738   rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f3f, pFlagsOut);
13739   assert( rc==SQLITE_OK || pFile->pMethods==0 );
13740   return rc;
13741 }
13742 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
13743   return pVfs->xDelete(pVfs, zPath, dirSync);
13744 }
13745 SQLITE_PRIVATE int sqlite3OsAccess(
13746   sqlite3_vfs *pVfs, 
13747   const char *zPath, 
13748   int flags, 
13749   int *pResOut
13750 ){
13751   DO_OS_MALLOC_TEST(0);
13752   return pVfs->xAccess(pVfs, zPath, flags, pResOut);
13753 }
13754 SQLITE_PRIVATE int sqlite3OsFullPathname(
13755   sqlite3_vfs *pVfs, 
13756   const char *zPath, 
13757   int nPathOut, 
13758   char *zPathOut
13759 ){
13760   zPathOut[0] = 0;
13761   return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
13762 }
13763 #ifndef SQLITE_OMIT_LOAD_EXTENSION
13764 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
13765   return pVfs->xDlOpen(pVfs, zPath);
13766 }
13767 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
13768   pVfs->xDlError(pVfs, nByte, zBufOut);
13769 }
13770 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
13771   return pVfs->xDlSym(pVfs, pHdle, zSym);
13772 }
13773 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
13774   pVfs->xDlClose(pVfs, pHandle);
13775 }
13776 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
13777 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
13778   return pVfs->xRandomness(pVfs, nByte, zBufOut);
13779 }
13780 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
13781   return pVfs->xSleep(pVfs, nMicro);
13782 }
13783 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
13784   int rc;
13785   /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
13786   ** method to get the current date and time if that method is available
13787   ** (if iVersion is 2 or greater and the function pointer is not NULL) and
13788   ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
13789   ** unavailable.
13790   */
13791   if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
13792     rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
13793   }else{
13794     double r;
13795     rc = pVfs->xCurrentTime(pVfs, &r);
13796     *pTimeOut = (sqlite3_int64)(r*86400000.0);
13797   }
13798   return rc;
13799 }
13800
13801 SQLITE_PRIVATE int sqlite3OsOpenMalloc(
13802   sqlite3_vfs *pVfs, 
13803   const char *zFile, 
13804   sqlite3_file **ppFile, 
13805   int flags,
13806   int *pOutFlags
13807 ){
13808   int rc = SQLITE_NOMEM;
13809   sqlite3_file *pFile;
13810   pFile = (sqlite3_file *)sqlite3Malloc(pVfs->szOsFile);
13811   if( pFile ){
13812     rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
13813     if( rc!=SQLITE_OK ){
13814       sqlite3_free(pFile);
13815     }else{
13816       *ppFile = pFile;
13817     }
13818   }
13819   return rc;
13820 }
13821 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
13822   int rc = SQLITE_OK;
13823   assert( pFile );
13824   rc = sqlite3OsClose(pFile);
13825   sqlite3_free(pFile);
13826   return rc;
13827 }
13828
13829 /*
13830 ** This function is a wrapper around the OS specific implementation of
13831 ** sqlite3_os_init(). The purpose of the wrapper is to provide the
13832 ** ability to simulate a malloc failure, so that the handling of an
13833 ** error in sqlite3_os_init() by the upper layers can be tested.
13834 */
13835 SQLITE_PRIVATE int sqlite3OsInit(void){
13836   void *p = sqlite3_malloc(10);
13837   if( p==0 ) return SQLITE_NOMEM;
13838   sqlite3_free(p);
13839   return sqlite3_os_init();
13840 }
13841
13842 /*
13843 ** The list of all registered VFS implementations.
13844 */
13845 static sqlite3_vfs * SQLITE_WSD vfsList = 0;
13846 #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
13847
13848 /*
13849 ** Locate a VFS by name.  If no name is given, simply return the
13850 ** first VFS on the list.
13851 */
13852 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
13853   sqlite3_vfs *pVfs = 0;
13854 #if SQLITE_THREADSAFE
13855   sqlite3_mutex *mutex;
13856 #endif
13857 #ifndef SQLITE_OMIT_AUTOINIT
13858   int rc = sqlite3_initialize();
13859   if( rc ) return 0;
13860 #endif
13861 #if SQLITE_THREADSAFE
13862   mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
13863 #endif
13864   sqlite3_mutex_enter(mutex);
13865   for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
13866     if( zVfs==0 ) break;
13867     if( strcmp(zVfs, pVfs->zName)==0 ) break;
13868   }
13869   sqlite3_mutex_leave(mutex);
13870   return pVfs;
13871 }
13872
13873 /*
13874 ** Unlink a VFS from the linked list
13875 */
13876 static void vfsUnlink(sqlite3_vfs *pVfs){
13877   assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
13878   if( pVfs==0 ){
13879     /* No-op */
13880   }else if( vfsList==pVfs ){
13881     vfsList = pVfs->pNext;
13882   }else if( vfsList ){
13883     sqlite3_vfs *p = vfsList;
13884     while( p->pNext && p->pNext!=pVfs ){
13885       p = p->pNext;
13886     }
13887     if( p->pNext==pVfs ){
13888       p->pNext = pVfs->pNext;
13889     }
13890   }
13891 }
13892
13893 /*
13894 ** Register a VFS with the system.  It is harmless to register the same
13895 ** VFS multiple times.  The new VFS becomes the default if makeDflt is
13896 ** true.
13897 */
13898 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
13899   sqlite3_mutex *mutex = 0;
13900 #ifndef SQLITE_OMIT_AUTOINIT
13901   int rc = sqlite3_initialize();
13902   if( rc ) return rc;
13903 #endif
13904   mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
13905   sqlite3_mutex_enter(mutex);
13906   vfsUnlink(pVfs);
13907   if( makeDflt || vfsList==0 ){
13908     pVfs->pNext = vfsList;
13909     vfsList = pVfs;
13910   }else{
13911     pVfs->pNext = vfsList->pNext;
13912     vfsList->pNext = pVfs;
13913   }
13914   assert(vfsList);
13915   sqlite3_mutex_leave(mutex);
13916   return SQLITE_OK;
13917 }
13918
13919 /*
13920 ** Unregister a VFS so that it is no longer accessible.
13921 */
13922 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
13923 #if SQLITE_THREADSAFE
13924   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
13925 #endif
13926   sqlite3_mutex_enter(mutex);
13927   vfsUnlink(pVfs);
13928   sqlite3_mutex_leave(mutex);
13929   return SQLITE_OK;
13930 }
13931
13932 /************** End of os.c **************************************************/
13933 /************** Begin file fault.c *******************************************/
13934 /*
13935 ** 2008 Jan 22
13936 **
13937 ** The author disclaims copyright to this source code.  In place of
13938 ** a legal notice, here is a blessing:
13939 **
13940 **    May you do good and not evil.
13941 **    May you find forgiveness for yourself and forgive others.
13942 **    May you share freely, never taking more than you give.
13943 **
13944 *************************************************************************
13945 **
13946 ** This file contains code to support the concept of "benign" 
13947 ** malloc failures (when the xMalloc() or xRealloc() method of the
13948 ** sqlite3_mem_methods structure fails to allocate a block of memory
13949 ** and returns 0). 
13950 **
13951 ** Most malloc failures are non-benign. After they occur, SQLite
13952 ** abandons the current operation and returns an error code (usually
13953 ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
13954 ** fatal. For example, if a malloc fails while resizing a hash table, this 
13955 ** is completely recoverable simply by not carrying out the resize. The 
13956 ** hash table will continue to function normally.  So a malloc failure 
13957 ** during a hash table resize is a benign fault.
13958 */
13959
13960
13961 #ifndef SQLITE_OMIT_BUILTIN_TEST
13962
13963 /*
13964 ** Global variables.
13965 */
13966 typedef struct BenignMallocHooks BenignMallocHooks;
13967 static SQLITE_WSD struct BenignMallocHooks {
13968   void (*xBenignBegin)(void);
13969   void (*xBenignEnd)(void);
13970 } sqlite3Hooks = { 0, 0 };
13971
13972 /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
13973 ** structure.  If writable static data is unsupported on the target,
13974 ** we have to locate the state vector at run-time.  In the more common
13975 ** case where writable static data is supported, wsdHooks can refer directly
13976 ** to the "sqlite3Hooks" state vector declared above.
13977 */
13978 #ifdef SQLITE_OMIT_WSD
13979 # define wsdHooksInit \
13980   BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
13981 # define wsdHooks x[0]
13982 #else
13983 # define wsdHooksInit
13984 # define wsdHooks sqlite3Hooks
13985 #endif
13986
13987
13988 /*
13989 ** Register hooks to call when sqlite3BeginBenignMalloc() and
13990 ** sqlite3EndBenignMalloc() are called, respectively.
13991 */
13992 SQLITE_PRIVATE void sqlite3BenignMallocHooks(
13993   void (*xBenignBegin)(void),
13994   void (*xBenignEnd)(void)
13995 ){
13996   wsdHooksInit;
13997   wsdHooks.xBenignBegin = xBenignBegin;
13998   wsdHooks.xBenignEnd = xBenignEnd;
13999 }
14000
14001 /*
14002 ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
14003 ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
14004 ** indicates that subsequent malloc failures are non-benign.
14005 */
14006 SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
14007   wsdHooksInit;
14008   if( wsdHooks.xBenignBegin ){
14009     wsdHooks.xBenignBegin();
14010   }
14011 }
14012 SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
14013   wsdHooksInit;
14014   if( wsdHooks.xBenignEnd ){
14015     wsdHooks.xBenignEnd();
14016   }
14017 }
14018
14019 #endif   /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
14020
14021 /************** End of fault.c ***********************************************/
14022 /************** Begin file mem0.c ********************************************/
14023 /*
14024 ** 2008 October 28
14025 **
14026 ** The author disclaims copyright to this source code.  In place of
14027 ** a legal notice, here is a blessing:
14028 **
14029 **    May you do good and not evil.
14030 **    May you find forgiveness for yourself and forgive others.
14031 **    May you share freely, never taking more than you give.
14032 **
14033 *************************************************************************
14034 **
14035 ** This file contains a no-op memory allocation drivers for use when
14036 ** SQLITE_ZERO_MALLOC is defined.  The allocation drivers implemented
14037 ** here always fail.  SQLite will not operate with these drivers.  These
14038 ** are merely placeholders.  Real drivers must be substituted using
14039 ** sqlite3_config() before SQLite will operate.
14040 */
14041
14042 /*
14043 ** This version of the memory allocator is the default.  It is
14044 ** used when no other memory allocator is specified using compile-time
14045 ** macros.
14046 */
14047 #ifdef SQLITE_ZERO_MALLOC
14048
14049 /*
14050 ** No-op versions of all memory allocation routines
14051 */
14052 static void *sqlite3MemMalloc(int nByte){ return 0; }
14053 static void sqlite3MemFree(void *pPrior){ return; }
14054 static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
14055 static int sqlite3MemSize(void *pPrior){ return 0; }
14056 static int sqlite3MemRoundup(int n){ return n; }
14057 static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
14058 static void sqlite3MemShutdown(void *NotUsed){ return; }
14059
14060 /*
14061 ** This routine is the only routine in this file with external linkage.
14062 **
14063 ** Populate the low-level memory allocation function pointers in
14064 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
14065 */
14066 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
14067   static const sqlite3_mem_methods defaultMethods = {
14068      sqlite3MemMalloc,
14069      sqlite3MemFree,
14070      sqlite3MemRealloc,
14071      sqlite3MemSize,
14072      sqlite3MemRoundup,
14073      sqlite3MemInit,
14074      sqlite3MemShutdown,
14075      0
14076   };
14077   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
14078 }
14079
14080 #endif /* SQLITE_ZERO_MALLOC */
14081
14082 /************** End of mem0.c ************************************************/
14083 /************** Begin file mem1.c ********************************************/
14084 /*
14085 ** 2007 August 14
14086 **
14087 ** The author disclaims copyright to this source code.  In place of
14088 ** a legal notice, here is a blessing:
14089 **
14090 **    May you do good and not evil.
14091 **    May you find forgiveness for yourself and forgive others.
14092 **    May you share freely, never taking more than you give.
14093 **
14094 *************************************************************************
14095 **
14096 ** This file contains low-level memory allocation drivers for when
14097 ** SQLite will use the standard C-library malloc/realloc/free interface
14098 ** to obtain the memory it needs.
14099 **
14100 ** This file contains implementations of the low-level memory allocation
14101 ** routines specified in the sqlite3_mem_methods object.
14102 */
14103
14104 /*
14105 ** This version of the memory allocator is the default.  It is
14106 ** used when no other memory allocator is specified using compile-time
14107 ** macros.
14108 */
14109 #ifdef SQLITE_SYSTEM_MALLOC
14110
14111 /*
14112 ** Like malloc(), but remember the size of the allocation
14113 ** so that we can find it later using sqlite3MemSize().
14114 **
14115 ** For this low-level routine, we are guaranteed that nByte>0 because
14116 ** cases of nByte<=0 will be intercepted and dealt with by higher level
14117 ** routines.
14118 */
14119 static void *sqlite3MemMalloc(int nByte){
14120   sqlite3_int64 *p;
14121   assert( nByte>0 );
14122   nByte = ROUND8(nByte);
14123   p = malloc( nByte+8 );
14124   if( p ){
14125     p[0] = nByte;
14126     p++;
14127   }else{
14128     testcase( sqlite3GlobalConfig.xLog!=0 );
14129     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
14130   }
14131   return (void *)p;
14132 }
14133
14134 /*
14135 ** Like free() but works for allocations obtained from sqlite3MemMalloc()
14136 ** or sqlite3MemRealloc().
14137 **
14138 ** For this low-level routine, we already know that pPrior!=0 since
14139 ** cases where pPrior==0 will have been intecepted and dealt with
14140 ** by higher-level routines.
14141 */
14142 static void sqlite3MemFree(void *pPrior){
14143   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
14144   assert( pPrior!=0 );
14145   p--;
14146   free(p);
14147 }
14148
14149 /*
14150 ** Report the allocated size of a prior return from xMalloc()
14151 ** or xRealloc().
14152 */
14153 static int sqlite3MemSize(void *pPrior){
14154   sqlite3_int64 *p;
14155   if( pPrior==0 ) return 0;
14156   p = (sqlite3_int64*)pPrior;
14157   p--;
14158   return (int)p[0];
14159 }
14160
14161 /*
14162 ** Like realloc().  Resize an allocation previously obtained from
14163 ** sqlite3MemMalloc().
14164 **
14165 ** For this low-level interface, we know that pPrior!=0.  Cases where
14166 ** pPrior==0 while have been intercepted by higher-level routine and
14167 ** redirected to xMalloc.  Similarly, we know that nByte>0 becauses
14168 ** cases where nByte<=0 will have been intercepted by higher-level
14169 ** routines and redirected to xFree.
14170 */
14171 static void *sqlite3MemRealloc(void *pPrior, int nByte){
14172   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
14173   assert( pPrior!=0 && nByte>0 );
14174   assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
14175   p--;
14176   p = realloc(p, nByte+8 );
14177   if( p ){
14178     p[0] = nByte;
14179     p++;
14180   }else{
14181     testcase( sqlite3GlobalConfig.xLog!=0 );
14182     sqlite3_log(SQLITE_NOMEM,
14183       "failed memory resize %u to %u bytes",
14184       sqlite3MemSize(pPrior), nByte);
14185   }
14186   return (void*)p;
14187 }
14188
14189 /*
14190 ** Round up a request size to the next valid allocation size.
14191 */
14192 static int sqlite3MemRoundup(int n){
14193   return ROUND8(n);
14194 }
14195
14196 /*
14197 ** Initialize this module.
14198 */
14199 static int sqlite3MemInit(void *NotUsed){
14200   UNUSED_PARAMETER(NotUsed);
14201   return SQLITE_OK;
14202 }
14203
14204 /*
14205 ** Deinitialize this module.
14206 */
14207 static void sqlite3MemShutdown(void *NotUsed){
14208   UNUSED_PARAMETER(NotUsed);
14209   return;
14210 }
14211
14212 /*
14213 ** This routine is the only routine in this file with external linkage.
14214 **
14215 ** Populate the low-level memory allocation function pointers in
14216 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
14217 */
14218 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
14219   static const sqlite3_mem_methods defaultMethods = {
14220      sqlite3MemMalloc,
14221      sqlite3MemFree,
14222      sqlite3MemRealloc,
14223      sqlite3MemSize,
14224      sqlite3MemRoundup,
14225      sqlite3MemInit,
14226      sqlite3MemShutdown,
14227      0
14228   };
14229   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
14230 }
14231
14232 #endif /* SQLITE_SYSTEM_MALLOC */
14233
14234 /************** End of mem1.c ************************************************/
14235 /************** Begin file mem2.c ********************************************/
14236 /*
14237 ** 2007 August 15
14238 **
14239 ** The author disclaims copyright to this source code.  In place of
14240 ** a legal notice, here is a blessing:
14241 **
14242 **    May you do good and not evil.
14243 **    May you find forgiveness for yourself and forgive others.
14244 **    May you share freely, never taking more than you give.
14245 **
14246 *************************************************************************
14247 **
14248 ** This file contains low-level memory allocation drivers for when
14249 ** SQLite will use the standard C-library malloc/realloc/free interface
14250 ** to obtain the memory it needs while adding lots of additional debugging
14251 ** information to each allocation in order to help detect and fix memory
14252 ** leaks and memory usage errors.
14253 **
14254 ** This file contains implementations of the low-level memory allocation
14255 ** routines specified in the sqlite3_mem_methods object.
14256 */
14257
14258 /*
14259 ** This version of the memory allocator is used only if the
14260 ** SQLITE_MEMDEBUG macro is defined
14261 */
14262 #ifdef SQLITE_MEMDEBUG
14263
14264 /*
14265 ** The backtrace functionality is only available with GLIBC
14266 */
14267 #ifdef __GLIBC__
14268   extern int backtrace(void**,int);
14269   extern void backtrace_symbols_fd(void*const*,int,int);
14270 #else
14271 # define backtrace(A,B) 1
14272 # define backtrace_symbols_fd(A,B,C)
14273 #endif
14274
14275 /*
14276 ** Each memory allocation looks like this:
14277 **
14278 **  ------------------------------------------------------------------------
14279 **  | Title |  backtrace pointers |  MemBlockHdr |  allocation |  EndGuard |
14280 **  ------------------------------------------------------------------------
14281 **
14282 ** The application code sees only a pointer to the allocation.  We have
14283 ** to back up from the allocation pointer to find the MemBlockHdr.  The
14284 ** MemBlockHdr tells us the size of the allocation and the number of
14285 ** backtrace pointers.  There is also a guard word at the end of the
14286 ** MemBlockHdr.
14287 */
14288 struct MemBlockHdr {
14289   i64 iSize;                          /* Size of this allocation */
14290   struct MemBlockHdr *pNext, *pPrev;  /* Linked list of all unfreed memory */
14291   char nBacktrace;                    /* Number of backtraces on this alloc */
14292   char nBacktraceSlots;               /* Available backtrace slots */
14293   u8 nTitle;                          /* Bytes of title; includes '\0' */
14294   u8 eType;                           /* Allocation type code */
14295   int iForeGuard;                     /* Guard word for sanity */
14296 };
14297
14298 /*
14299 ** Guard words
14300 */
14301 #define FOREGUARD 0x80F5E153
14302 #define REARGUARD 0xE4676B53
14303
14304 /*
14305 ** Number of malloc size increments to track.
14306 */
14307 #define NCSIZE  1000
14308
14309 /*
14310 ** All of the static variables used by this module are collected
14311 ** into a single structure named "mem".  This is to keep the
14312 ** static variables organized and to reduce namespace pollution
14313 ** when this module is combined with other in the amalgamation.
14314 */
14315 static struct {
14316   
14317   /*
14318   ** Mutex to control access to the memory allocation subsystem.
14319   */
14320   sqlite3_mutex *mutex;
14321
14322   /*
14323   ** Head and tail of a linked list of all outstanding allocations
14324   */
14325   struct MemBlockHdr *pFirst;
14326   struct MemBlockHdr *pLast;
14327   
14328   /*
14329   ** The number of levels of backtrace to save in new allocations.
14330   */
14331   int nBacktrace;
14332   void (*xBacktrace)(int, int, void **);
14333
14334   /*
14335   ** Title text to insert in front of each block
14336   */
14337   int nTitle;        /* Bytes of zTitle to save.  Includes '\0' and padding */
14338   char zTitle[100];  /* The title text */
14339
14340   /* 
14341   ** sqlite3MallocDisallow() increments the following counter.
14342   ** sqlite3MallocAllow() decrements it.
14343   */
14344   int disallow; /* Do not allow memory allocation */
14345
14346   /*
14347   ** Gather statistics on the sizes of memory allocations.
14348   ** nAlloc[i] is the number of allocation attempts of i*8
14349   ** bytes.  i==NCSIZE is the number of allocation attempts for
14350   ** sizes more than NCSIZE*8 bytes.
14351   */
14352   int nAlloc[NCSIZE];      /* Total number of allocations */
14353   int nCurrent[NCSIZE];    /* Current number of allocations */
14354   int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */
14355
14356 } mem;
14357
14358
14359 /*
14360 ** Adjust memory usage statistics
14361 */
14362 static void adjustStats(int iSize, int increment){
14363   int i = ROUND8(iSize)/8;
14364   if( i>NCSIZE-1 ){
14365     i = NCSIZE - 1;
14366   }
14367   if( increment>0 ){
14368     mem.nAlloc[i]++;
14369     mem.nCurrent[i]++;
14370     if( mem.nCurrent[i]>mem.mxCurrent[i] ){
14371       mem.mxCurrent[i] = mem.nCurrent[i];
14372     }
14373   }else{
14374     mem.nCurrent[i]--;
14375     assert( mem.nCurrent[i]>=0 );
14376   }
14377 }
14378
14379 /*
14380 ** Given an allocation, find the MemBlockHdr for that allocation.
14381 **
14382 ** This routine checks the guards at either end of the allocation and
14383 ** if they are incorrect it asserts.
14384 */
14385 static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
14386   struct MemBlockHdr *p;
14387   int *pInt;
14388   u8 *pU8;
14389   int nReserve;
14390
14391   p = (struct MemBlockHdr*)pAllocation;
14392   p--;
14393   assert( p->iForeGuard==(int)FOREGUARD );
14394   nReserve = ROUND8(p->iSize);
14395   pInt = (int*)pAllocation;
14396   pU8 = (u8*)pAllocation;
14397   assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
14398   /* This checks any of the "extra" bytes allocated due
14399   ** to rounding up to an 8 byte boundary to ensure 
14400   ** they haven't been overwritten.
14401   */
14402   while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
14403   return p;
14404 }
14405
14406 /*
14407 ** Return the number of bytes currently allocated at address p.
14408 */
14409 static int sqlite3MemSize(void *p){
14410   struct MemBlockHdr *pHdr;
14411   if( !p ){
14412     return 0;
14413   }
14414   pHdr = sqlite3MemsysGetHeader(p);
14415   return pHdr->iSize;
14416 }
14417
14418 /*
14419 ** Initialize the memory allocation subsystem.
14420 */
14421 static int sqlite3MemInit(void *NotUsed){
14422   UNUSED_PARAMETER(NotUsed);
14423   assert( (sizeof(struct MemBlockHdr)&7) == 0 );
14424   if( !sqlite3GlobalConfig.bMemstat ){
14425     /* If memory status is enabled, then the malloc.c wrapper will already
14426     ** hold the STATIC_MEM mutex when the routines here are invoked. */
14427     mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
14428   }
14429   return SQLITE_OK;
14430 }
14431
14432 /*
14433 ** Deinitialize the memory allocation subsystem.
14434 */
14435 static void sqlite3MemShutdown(void *NotUsed){
14436   UNUSED_PARAMETER(NotUsed);
14437   mem.mutex = 0;
14438 }
14439
14440 /*
14441 ** Round up a request size to the next valid allocation size.
14442 */
14443 static int sqlite3MemRoundup(int n){
14444   return ROUND8(n);
14445 }
14446
14447 /*
14448 ** Fill a buffer with pseudo-random bytes.  This is used to preset
14449 ** the content of a new memory allocation to unpredictable values and
14450 ** to clear the content of a freed allocation to unpredictable values.
14451 */
14452 static void randomFill(char *pBuf, int nByte){
14453   unsigned int x, y, r;
14454   x = SQLITE_PTR_TO_INT(pBuf);
14455   y = nByte | 1;
14456   while( nByte >= 4 ){
14457     x = (x>>1) ^ (-(x&1) & 0xd0000001);
14458     y = y*1103515245 + 12345;
14459     r = x ^ y;
14460     *(int*)pBuf = r;
14461     pBuf += 4;
14462     nByte -= 4;
14463   }
14464   while( nByte-- > 0 ){
14465     x = (x>>1) ^ (-(x&1) & 0xd0000001);
14466     y = y*1103515245 + 12345;
14467     r = x ^ y;
14468     *(pBuf++) = r & 0xff;
14469   }
14470 }
14471
14472 /*
14473 ** Allocate nByte bytes of memory.
14474 */
14475 static void *sqlite3MemMalloc(int nByte){
14476   struct MemBlockHdr *pHdr;
14477   void **pBt;
14478   char *z;
14479   int *pInt;
14480   void *p = 0;
14481   int totalSize;
14482   int nReserve;
14483   sqlite3_mutex_enter(mem.mutex);
14484   assert( mem.disallow==0 );
14485   nReserve = ROUND8(nByte);
14486   totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
14487                mem.nBacktrace*sizeof(void*) + mem.nTitle;
14488   p = malloc(totalSize);
14489   if( p ){
14490     z = p;
14491     pBt = (void**)&z[mem.nTitle];
14492     pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
14493     pHdr->pNext = 0;
14494     pHdr->pPrev = mem.pLast;
14495     if( mem.pLast ){
14496       mem.pLast->pNext = pHdr;
14497     }else{
14498       mem.pFirst = pHdr;
14499     }
14500     mem.pLast = pHdr;
14501     pHdr->iForeGuard = FOREGUARD;
14502     pHdr->eType = MEMTYPE_HEAP;
14503     pHdr->nBacktraceSlots = mem.nBacktrace;
14504     pHdr->nTitle = mem.nTitle;
14505     if( mem.nBacktrace ){
14506       void *aAddr[40];
14507       pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
14508       memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
14509       assert(pBt[0]);
14510       if( mem.xBacktrace ){
14511         mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
14512       }
14513     }else{
14514       pHdr->nBacktrace = 0;
14515     }
14516     if( mem.nTitle ){
14517       memcpy(z, mem.zTitle, mem.nTitle);
14518     }
14519     pHdr->iSize = nByte;
14520     adjustStats(nByte, +1);
14521     pInt = (int*)&pHdr[1];
14522     pInt[nReserve/sizeof(int)] = REARGUARD;
14523     randomFill((char*)pInt, nByte);
14524     memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
14525     p = (void*)pInt;
14526   }
14527   sqlite3_mutex_leave(mem.mutex);
14528   return p; 
14529 }
14530
14531 /*
14532 ** Free memory.
14533 */
14534 static void sqlite3MemFree(void *pPrior){
14535   struct MemBlockHdr *pHdr;
14536   void **pBt;
14537   char *z;
14538   assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0 
14539        || mem.mutex!=0 );
14540   pHdr = sqlite3MemsysGetHeader(pPrior);
14541   pBt = (void**)pHdr;
14542   pBt -= pHdr->nBacktraceSlots;
14543   sqlite3_mutex_enter(mem.mutex);
14544   if( pHdr->pPrev ){
14545     assert( pHdr->pPrev->pNext==pHdr );
14546     pHdr->pPrev->pNext = pHdr->pNext;
14547   }else{
14548     assert( mem.pFirst==pHdr );
14549     mem.pFirst = pHdr->pNext;
14550   }
14551   if( pHdr->pNext ){
14552     assert( pHdr->pNext->pPrev==pHdr );
14553     pHdr->pNext->pPrev = pHdr->pPrev;
14554   }else{
14555     assert( mem.pLast==pHdr );
14556     mem.pLast = pHdr->pPrev;
14557   }
14558   z = (char*)pBt;
14559   z -= pHdr->nTitle;
14560   adjustStats(pHdr->iSize, -1);
14561   randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
14562                 pHdr->iSize + sizeof(int) + pHdr->nTitle);
14563   free(z);
14564   sqlite3_mutex_leave(mem.mutex);  
14565 }
14566
14567 /*
14568 ** Change the size of an existing memory allocation.
14569 **
14570 ** For this debugging implementation, we *always* make a copy of the
14571 ** allocation into a new place in memory.  In this way, if the 
14572 ** higher level code is using pointer to the old allocation, it is 
14573 ** much more likely to break and we are much more liking to find
14574 ** the error.
14575 */
14576 static void *sqlite3MemRealloc(void *pPrior, int nByte){
14577   struct MemBlockHdr *pOldHdr;
14578   void *pNew;
14579   assert( mem.disallow==0 );
14580   assert( (nByte & 7)==0 );     /* EV: R-46199-30249 */
14581   pOldHdr = sqlite3MemsysGetHeader(pPrior);
14582   pNew = sqlite3MemMalloc(nByte);
14583   if( pNew ){
14584     memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
14585     if( nByte>pOldHdr->iSize ){
14586       randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - pOldHdr->iSize);
14587     }
14588     sqlite3MemFree(pPrior);
14589   }
14590   return pNew;
14591 }
14592
14593 /*
14594 ** Populate the low-level memory allocation function pointers in
14595 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
14596 */
14597 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
14598   static const sqlite3_mem_methods defaultMethods = {
14599      sqlite3MemMalloc,
14600      sqlite3MemFree,
14601      sqlite3MemRealloc,
14602      sqlite3MemSize,
14603      sqlite3MemRoundup,
14604      sqlite3MemInit,
14605      sqlite3MemShutdown,
14606      0
14607   };
14608   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
14609 }
14610
14611 /*
14612 ** Set the "type" of an allocation.
14613 */
14614 SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
14615   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
14616     struct MemBlockHdr *pHdr;
14617     pHdr = sqlite3MemsysGetHeader(p);
14618     assert( pHdr->iForeGuard==FOREGUARD );
14619     pHdr->eType = eType;
14620   }
14621 }
14622
14623 /*
14624 ** Return TRUE if the mask of type in eType matches the type of the
14625 ** allocation p.  Also return true if p==NULL.
14626 **
14627 ** This routine is designed for use within an assert() statement, to
14628 ** verify the type of an allocation.  For example:
14629 **
14630 **     assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
14631 */
14632 SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
14633   int rc = 1;
14634   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
14635     struct MemBlockHdr *pHdr;
14636     pHdr = sqlite3MemsysGetHeader(p);
14637     assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
14638     if( (pHdr->eType&eType)==0 ){
14639       rc = 0;
14640     }
14641   }
14642   return rc;
14643 }
14644
14645 /*
14646 ** Return TRUE if the mask of type in eType matches no bits of the type of the
14647 ** allocation p.  Also return true if p==NULL.
14648 **
14649 ** This routine is designed for use within an assert() statement, to
14650 ** verify the type of an allocation.  For example:
14651 **
14652 **     assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
14653 */
14654 SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
14655   int rc = 1;
14656   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
14657     struct MemBlockHdr *pHdr;
14658     pHdr = sqlite3MemsysGetHeader(p);
14659     assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
14660     if( (pHdr->eType&eType)!=0 ){
14661       rc = 0;
14662     }
14663   }
14664   return rc;
14665 }
14666
14667 /*
14668 ** Set the number of backtrace levels kept for each allocation.
14669 ** A value of zero turns off backtracing.  The number is always rounded
14670 ** up to a multiple of 2.
14671 */
14672 SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
14673   if( depth<0 ){ depth = 0; }
14674   if( depth>20 ){ depth = 20; }
14675   depth = (depth+1)&0xfe;
14676   mem.nBacktrace = depth;
14677 }
14678
14679 SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
14680   mem.xBacktrace = xBacktrace;
14681 }
14682
14683 /*
14684 ** Set the title string for subsequent allocations.
14685 */
14686 SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
14687   unsigned int n = sqlite3Strlen30(zTitle) + 1;
14688   sqlite3_mutex_enter(mem.mutex);
14689   if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
14690   memcpy(mem.zTitle, zTitle, n);
14691   mem.zTitle[n] = 0;
14692   mem.nTitle = ROUND8(n);
14693   sqlite3_mutex_leave(mem.mutex);
14694 }
14695
14696 SQLITE_PRIVATE void sqlite3MemdebugSync(){
14697   struct MemBlockHdr *pHdr;
14698   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
14699     void **pBt = (void**)pHdr;
14700     pBt -= pHdr->nBacktraceSlots;
14701     mem.xBacktrace(pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
14702   }
14703 }
14704
14705 /*
14706 ** Open the file indicated and write a log of all unfreed memory 
14707 ** allocations into that log.
14708 */
14709 SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
14710   FILE *out;
14711   struct MemBlockHdr *pHdr;
14712   void **pBt;
14713   int i;
14714   out = fopen(zFilename, "w");
14715   if( out==0 ){
14716     fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
14717                     zFilename);
14718     return;
14719   }
14720   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
14721     char *z = (char*)pHdr;
14722     z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
14723     fprintf(out, "**** %lld bytes at %p from %s ****\n", 
14724             pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
14725     if( pHdr->nBacktrace ){
14726       fflush(out);
14727       pBt = (void**)pHdr;
14728       pBt -= pHdr->nBacktraceSlots;
14729       backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
14730       fprintf(out, "\n");
14731     }
14732   }
14733   fprintf(out, "COUNTS:\n");
14734   for(i=0; i<NCSIZE-1; i++){
14735     if( mem.nAlloc[i] ){
14736       fprintf(out, "   %5d: %10d %10d %10d\n", 
14737             i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
14738     }
14739   }
14740   if( mem.nAlloc[NCSIZE-1] ){
14741     fprintf(out, "   %5d: %10d %10d %10d\n",
14742              NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
14743              mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
14744   }
14745   fclose(out);
14746 }
14747
14748 /*
14749 ** Return the number of times sqlite3MemMalloc() has been called.
14750 */
14751 SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
14752   int i;
14753   int nTotal = 0;
14754   for(i=0; i<NCSIZE; i++){
14755     nTotal += mem.nAlloc[i];
14756   }
14757   return nTotal;
14758 }
14759
14760
14761 #endif /* SQLITE_MEMDEBUG */
14762
14763 /************** End of mem2.c ************************************************/
14764 /************** Begin file mem3.c ********************************************/
14765 /*
14766 ** 2007 October 14
14767 **
14768 ** The author disclaims copyright to this source code.  In place of
14769 ** a legal notice, here is a blessing:
14770 **
14771 **    May you do good and not evil.
14772 **    May you find forgiveness for yourself and forgive others.
14773 **    May you share freely, never taking more than you give.
14774 **
14775 *************************************************************************
14776 ** This file contains the C functions that implement a memory
14777 ** allocation subsystem for use by SQLite. 
14778 **
14779 ** This version of the memory allocation subsystem omits all
14780 ** use of malloc(). The SQLite user supplies a block of memory
14781 ** before calling sqlite3_initialize() from which allocations
14782 ** are made and returned by the xMalloc() and xRealloc() 
14783 ** implementations. Once sqlite3_initialize() has been called,
14784 ** the amount of memory available to SQLite is fixed and cannot
14785 ** be changed.
14786 **
14787 ** This version of the memory allocation subsystem is included
14788 ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
14789 */
14790
14791 /*
14792 ** This version of the memory allocator is only built into the library
14793 ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
14794 ** mean that the library will use a memory-pool by default, just that
14795 ** it is available. The mempool allocator is activated by calling
14796 ** sqlite3_config().
14797 */
14798 #ifdef SQLITE_ENABLE_MEMSYS3
14799
14800 /*
14801 ** Maximum size (in Mem3Blocks) of a "small" chunk.
14802 */
14803 #define MX_SMALL 10
14804
14805
14806 /*
14807 ** Number of freelist hash slots
14808 */
14809 #define N_HASH  61
14810
14811 /*
14812 ** A memory allocation (also called a "chunk") consists of two or 
14813 ** more blocks where each block is 8 bytes.  The first 8 bytes are 
14814 ** a header that is not returned to the user.
14815 **
14816 ** A chunk is two or more blocks that is either checked out or
14817 ** free.  The first block has format u.hdr.  u.hdr.size4x is 4 times the
14818 ** size of the allocation in blocks if the allocation is free.
14819 ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
14820 ** false if the chunk is on the freelist.  The u.hdr.size4x&2 bit
14821 ** is true if the previous chunk is checked out and false if the
14822 ** previous chunk is free.  The u.hdr.prevSize field is the size of
14823 ** the previous chunk in blocks if the previous chunk is on the
14824 ** freelist. If the previous chunk is checked out, then
14825 ** u.hdr.prevSize can be part of the data for that chunk and should
14826 ** not be read or written.
14827 **
14828 ** We often identify a chunk by its index in mem3.aPool[].  When
14829 ** this is done, the chunk index refers to the second block of
14830 ** the chunk.  In this way, the first chunk has an index of 1.
14831 ** A chunk index of 0 means "no such chunk" and is the equivalent
14832 ** of a NULL pointer.
14833 **
14834 ** The second block of free chunks is of the form u.list.  The
14835 ** two fields form a double-linked list of chunks of related sizes.
14836 ** Pointers to the head of the list are stored in mem3.aiSmall[] 
14837 ** for smaller chunks and mem3.aiHash[] for larger chunks.
14838 **
14839 ** The second block of a chunk is user data if the chunk is checked 
14840 ** out.  If a chunk is checked out, the user data may extend into
14841 ** the u.hdr.prevSize value of the following chunk.
14842 */
14843 typedef struct Mem3Block Mem3Block;
14844 struct Mem3Block {
14845   union {
14846     struct {
14847       u32 prevSize;   /* Size of previous chunk in Mem3Block elements */
14848       u32 size4x;     /* 4x the size of current chunk in Mem3Block elements */
14849     } hdr;
14850     struct {
14851       u32 next;       /* Index in mem3.aPool[] of next free chunk */
14852       u32 prev;       /* Index in mem3.aPool[] of previous free chunk */
14853     } list;
14854   } u;
14855 };
14856
14857 /*
14858 ** All of the static variables used by this module are collected
14859 ** into a single structure named "mem3".  This is to keep the
14860 ** static variables organized and to reduce namespace pollution
14861 ** when this module is combined with other in the amalgamation.
14862 */
14863 static SQLITE_WSD struct Mem3Global {
14864   /*
14865   ** Memory available for allocation. nPool is the size of the array
14866   ** (in Mem3Blocks) pointed to by aPool less 2.
14867   */
14868   u32 nPool;
14869   Mem3Block *aPool;
14870
14871   /*
14872   ** True if we are evaluating an out-of-memory callback.
14873   */
14874   int alarmBusy;
14875   
14876   /*
14877   ** Mutex to control access to the memory allocation subsystem.
14878   */
14879   sqlite3_mutex *mutex;
14880   
14881   /*
14882   ** The minimum amount of free space that we have seen.
14883   */
14884   u32 mnMaster;
14885
14886   /*
14887   ** iMaster is the index of the master chunk.  Most new allocations
14888   ** occur off of this chunk.  szMaster is the size (in Mem3Blocks)
14889   ** of the current master.  iMaster is 0 if there is not master chunk.
14890   ** The master chunk is not in either the aiHash[] or aiSmall[].
14891   */
14892   u32 iMaster;
14893   u32 szMaster;
14894
14895   /*
14896   ** Array of lists of free blocks according to the block size 
14897   ** for smaller chunks, or a hash on the block size for larger
14898   ** chunks.
14899   */
14900   u32 aiSmall[MX_SMALL-1];   /* For sizes 2 through MX_SMALL, inclusive */
14901   u32 aiHash[N_HASH];        /* For sizes MX_SMALL+1 and larger */
14902 } mem3 = { 97535575 };
14903
14904 #define mem3 GLOBAL(struct Mem3Global, mem3)
14905
14906 /*
14907 ** Unlink the chunk at mem3.aPool[i] from list it is currently
14908 ** on.  *pRoot is the list that i is a member of.
14909 */
14910 static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
14911   u32 next = mem3.aPool[i].u.list.next;
14912   u32 prev = mem3.aPool[i].u.list.prev;
14913   assert( sqlite3_mutex_held(mem3.mutex) );
14914   if( prev==0 ){
14915     *pRoot = next;
14916   }else{
14917     mem3.aPool[prev].u.list.next = next;
14918   }
14919   if( next ){
14920     mem3.aPool[next].u.list.prev = prev;
14921   }
14922   mem3.aPool[i].u.list.next = 0;
14923   mem3.aPool[i].u.list.prev = 0;
14924 }
14925
14926 /*
14927 ** Unlink the chunk at index i from 
14928 ** whatever list is currently a member of.
14929 */
14930 static void memsys3Unlink(u32 i){
14931   u32 size, hash;
14932   assert( sqlite3_mutex_held(mem3.mutex) );
14933   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
14934   assert( i>=1 );
14935   size = mem3.aPool[i-1].u.hdr.size4x/4;
14936   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
14937   assert( size>=2 );
14938   if( size <= MX_SMALL ){
14939     memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
14940   }else{
14941     hash = size % N_HASH;
14942     memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
14943   }
14944 }
14945
14946 /*
14947 ** Link the chunk at mem3.aPool[i] so that is on the list rooted
14948 ** at *pRoot.
14949 */
14950 static void memsys3LinkIntoList(u32 i, u32 *pRoot){
14951   assert( sqlite3_mutex_held(mem3.mutex) );
14952   mem3.aPool[i].u.list.next = *pRoot;
14953   mem3.aPool[i].u.list.prev = 0;
14954   if( *pRoot ){
14955     mem3.aPool[*pRoot].u.list.prev = i;
14956   }
14957   *pRoot = i;
14958 }
14959
14960 /*
14961 ** Link the chunk at index i into either the appropriate
14962 ** small chunk list, or into the large chunk hash table.
14963 */
14964 static void memsys3Link(u32 i){
14965   u32 size, hash;
14966   assert( sqlite3_mutex_held(mem3.mutex) );
14967   assert( i>=1 );
14968   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
14969   size = mem3.aPool[i-1].u.hdr.size4x/4;
14970   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
14971   assert( size>=2 );
14972   if( size <= MX_SMALL ){
14973     memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
14974   }else{
14975     hash = size % N_HASH;
14976     memsys3LinkIntoList(i, &mem3.aiHash[hash]);
14977   }
14978 }
14979
14980 /*
14981 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
14982 ** will already be held (obtained by code in malloc.c) if
14983 ** sqlite3GlobalConfig.bMemStat is true.
14984 */
14985 static void memsys3Enter(void){
14986   if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
14987     mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
14988   }
14989   sqlite3_mutex_enter(mem3.mutex);
14990 }
14991 static void memsys3Leave(void){
14992   sqlite3_mutex_leave(mem3.mutex);
14993 }
14994
14995 /*
14996 ** Called when we are unable to satisfy an allocation of nBytes.
14997 */
14998 static void memsys3OutOfMemory(int nByte){
14999   if( !mem3.alarmBusy ){
15000     mem3.alarmBusy = 1;
15001     assert( sqlite3_mutex_held(mem3.mutex) );
15002     sqlite3_mutex_leave(mem3.mutex);
15003     sqlite3_release_memory(nByte);
15004     sqlite3_mutex_enter(mem3.mutex);
15005     mem3.alarmBusy = 0;
15006   }
15007 }
15008
15009
15010 /*
15011 ** Chunk i is a free chunk that has been unlinked.  Adjust its 
15012 ** size parameters for check-out and return a pointer to the 
15013 ** user portion of the chunk.
15014 */
15015 static void *memsys3Checkout(u32 i, u32 nBlock){
15016   u32 x;
15017   assert( sqlite3_mutex_held(mem3.mutex) );
15018   assert( i>=1 );
15019   assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
15020   assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
15021   x = mem3.aPool[i-1].u.hdr.size4x;
15022   mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
15023   mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
15024   mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
15025   return &mem3.aPool[i];
15026 }
15027
15028 /*
15029 ** Carve a piece off of the end of the mem3.iMaster free chunk.
15030 ** Return a pointer to the new allocation.  Or, if the master chunk
15031 ** is not large enough, return 0.
15032 */
15033 static void *memsys3FromMaster(u32 nBlock){
15034   assert( sqlite3_mutex_held(mem3.mutex) );
15035   assert( mem3.szMaster>=nBlock );
15036   if( nBlock>=mem3.szMaster-1 ){
15037     /* Use the entire master */
15038     void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
15039     mem3.iMaster = 0;
15040     mem3.szMaster = 0;
15041     mem3.mnMaster = 0;
15042     return p;
15043   }else{
15044     /* Split the master block.  Return the tail. */
15045     u32 newi, x;
15046     newi = mem3.iMaster + mem3.szMaster - nBlock;
15047     assert( newi > mem3.iMaster+1 );
15048     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
15049     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
15050     mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
15051     mem3.szMaster -= nBlock;
15052     mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
15053     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
15054     mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
15055     if( mem3.szMaster < mem3.mnMaster ){
15056       mem3.mnMaster = mem3.szMaster;
15057     }
15058     return (void*)&mem3.aPool[newi];
15059   }
15060 }
15061
15062 /*
15063 ** *pRoot is the head of a list of free chunks of the same size
15064 ** or same size hash.  In other words, *pRoot is an entry in either
15065 ** mem3.aiSmall[] or mem3.aiHash[].  
15066 **
15067 ** This routine examines all entries on the given list and tries
15068 ** to coalesce each entries with adjacent free chunks.  
15069 **
15070 ** If it sees a chunk that is larger than mem3.iMaster, it replaces 
15071 ** the current mem3.iMaster with the new larger chunk.  In order for
15072 ** this mem3.iMaster replacement to work, the master chunk must be
15073 ** linked into the hash tables.  That is not the normal state of
15074 ** affairs, of course.  The calling routine must link the master
15075 ** chunk before invoking this routine, then must unlink the (possibly
15076 ** changed) master chunk once this routine has finished.
15077 */
15078 static void memsys3Merge(u32 *pRoot){
15079   u32 iNext, prev, size, i, x;
15080
15081   assert( sqlite3_mutex_held(mem3.mutex) );
15082   for(i=*pRoot; i>0; i=iNext){
15083     iNext = mem3.aPool[i].u.list.next;
15084     size = mem3.aPool[i-1].u.hdr.size4x;
15085     assert( (size&1)==0 );
15086     if( (size&2)==0 ){
15087       memsys3UnlinkFromList(i, pRoot);
15088       assert( i > mem3.aPool[i-1].u.hdr.prevSize );
15089       prev = i - mem3.aPool[i-1].u.hdr.prevSize;
15090       if( prev==iNext ){
15091         iNext = mem3.aPool[prev].u.list.next;
15092       }
15093       memsys3Unlink(prev);
15094       size = i + size/4 - prev;
15095       x = mem3.aPool[prev-1].u.hdr.size4x & 2;
15096       mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
15097       mem3.aPool[prev+size-1].u.hdr.prevSize = size;
15098       memsys3Link(prev);
15099       i = prev;
15100     }else{
15101       size /= 4;
15102     }
15103     if( size>mem3.szMaster ){
15104       mem3.iMaster = i;
15105       mem3.szMaster = size;
15106     }
15107   }
15108 }
15109
15110 /*
15111 ** Return a block of memory of at least nBytes in size.
15112 ** Return NULL if unable.
15113 **
15114 ** This function assumes that the necessary mutexes, if any, are
15115 ** already held by the caller. Hence "Unsafe".
15116 */
15117 static void *memsys3MallocUnsafe(int nByte){
15118   u32 i;
15119   u32 nBlock;
15120   u32 toFree;
15121
15122   assert( sqlite3_mutex_held(mem3.mutex) );
15123   assert( sizeof(Mem3Block)==8 );
15124   if( nByte<=12 ){
15125     nBlock = 2;
15126   }else{
15127     nBlock = (nByte + 11)/8;
15128   }
15129   assert( nBlock>=2 );
15130
15131   /* STEP 1:
15132   ** Look for an entry of the correct size in either the small
15133   ** chunk table or in the large chunk hash table.  This is
15134   ** successful most of the time (about 9 times out of 10).
15135   */
15136   if( nBlock <= MX_SMALL ){
15137     i = mem3.aiSmall[nBlock-2];
15138     if( i>0 ){
15139       memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
15140       return memsys3Checkout(i, nBlock);
15141     }
15142   }else{
15143     int hash = nBlock % N_HASH;
15144     for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
15145       if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
15146         memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
15147         return memsys3Checkout(i, nBlock);
15148       }
15149     }
15150   }
15151
15152   /* STEP 2:
15153   ** Try to satisfy the allocation by carving a piece off of the end
15154   ** of the master chunk.  This step usually works if step 1 fails.
15155   */
15156   if( mem3.szMaster>=nBlock ){
15157     return memsys3FromMaster(nBlock);
15158   }
15159
15160
15161   /* STEP 3:  
15162   ** Loop through the entire memory pool.  Coalesce adjacent free
15163   ** chunks.  Recompute the master chunk as the largest free chunk.
15164   ** Then try again to satisfy the allocation by carving a piece off
15165   ** of the end of the master chunk.  This step happens very
15166   ** rarely (we hope!)
15167   */
15168   for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
15169     memsys3OutOfMemory(toFree);
15170     if( mem3.iMaster ){
15171       memsys3Link(mem3.iMaster);
15172       mem3.iMaster = 0;
15173       mem3.szMaster = 0;
15174     }
15175     for(i=0; i<N_HASH; i++){
15176       memsys3Merge(&mem3.aiHash[i]);
15177     }
15178     for(i=0; i<MX_SMALL-1; i++){
15179       memsys3Merge(&mem3.aiSmall[i]);
15180     }
15181     if( mem3.szMaster ){
15182       memsys3Unlink(mem3.iMaster);
15183       if( mem3.szMaster>=nBlock ){
15184         return memsys3FromMaster(nBlock);
15185       }
15186     }
15187   }
15188
15189   /* If none of the above worked, then we fail. */
15190   return 0;
15191 }
15192
15193 /*
15194 ** Free an outstanding memory allocation.
15195 **
15196 ** This function assumes that the necessary mutexes, if any, are
15197 ** already held by the caller. Hence "Unsafe".
15198 */
15199 void memsys3FreeUnsafe(void *pOld){
15200   Mem3Block *p = (Mem3Block*)pOld;
15201   int i;
15202   u32 size, x;
15203   assert( sqlite3_mutex_held(mem3.mutex) );
15204   assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
15205   i = p - mem3.aPool;
15206   assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
15207   size = mem3.aPool[i-1].u.hdr.size4x/4;
15208   assert( i+size<=mem3.nPool+1 );
15209   mem3.aPool[i-1].u.hdr.size4x &= ~1;
15210   mem3.aPool[i+size-1].u.hdr.prevSize = size;
15211   mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
15212   memsys3Link(i);
15213
15214   /* Try to expand the master using the newly freed chunk */
15215   if( mem3.iMaster ){
15216     while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
15217       size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
15218       mem3.iMaster -= size;
15219       mem3.szMaster += size;
15220       memsys3Unlink(mem3.iMaster);
15221       x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
15222       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
15223       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
15224     }
15225     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
15226     while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
15227       memsys3Unlink(mem3.iMaster+mem3.szMaster);
15228       mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
15229       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
15230       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
15231     }
15232   }
15233 }
15234
15235 /*
15236 ** Return the size of an outstanding allocation, in bytes.  The
15237 ** size returned omits the 8-byte header overhead.  This only
15238 ** works for chunks that are currently checked out.
15239 */
15240 static int memsys3Size(void *p){
15241   Mem3Block *pBlock;
15242   if( p==0 ) return 0;
15243   pBlock = (Mem3Block*)p;
15244   assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
15245   return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
15246 }
15247
15248 /*
15249 ** Round up a request size to the next valid allocation size.
15250 */
15251 static int memsys3Roundup(int n){
15252   if( n<=12 ){
15253     return 12;
15254   }else{
15255     return ((n+11)&~7) - 4;
15256   }
15257 }
15258
15259 /*
15260 ** Allocate nBytes of memory.
15261 */
15262 static void *memsys3Malloc(int nBytes){
15263   sqlite3_int64 *p;
15264   assert( nBytes>0 );          /* malloc.c filters out 0 byte requests */
15265   memsys3Enter();
15266   p = memsys3MallocUnsafe(nBytes);
15267   memsys3Leave();
15268   return (void*)p; 
15269 }
15270
15271 /*
15272 ** Free memory.
15273 */
15274 void memsys3Free(void *pPrior){
15275   assert( pPrior );
15276   memsys3Enter();
15277   memsys3FreeUnsafe(pPrior);
15278   memsys3Leave();
15279 }
15280
15281 /*
15282 ** Change the size of an existing memory allocation
15283 */
15284 void *memsys3Realloc(void *pPrior, int nBytes){
15285   int nOld;
15286   void *p;
15287   if( pPrior==0 ){
15288     return sqlite3_malloc(nBytes);
15289   }
15290   if( nBytes<=0 ){
15291     sqlite3_free(pPrior);
15292     return 0;
15293   }
15294   nOld = memsys3Size(pPrior);
15295   if( nBytes<=nOld && nBytes>=nOld-128 ){
15296     return pPrior;
15297   }
15298   memsys3Enter();
15299   p = memsys3MallocUnsafe(nBytes);
15300   if( p ){
15301     if( nOld<nBytes ){
15302       memcpy(p, pPrior, nOld);
15303     }else{
15304       memcpy(p, pPrior, nBytes);
15305     }
15306     memsys3FreeUnsafe(pPrior);
15307   }
15308   memsys3Leave();
15309   return p;
15310 }
15311
15312 /*
15313 ** Initialize this module.
15314 */
15315 static int memsys3Init(void *NotUsed){
15316   UNUSED_PARAMETER(NotUsed);
15317   if( !sqlite3GlobalConfig.pHeap ){
15318     return SQLITE_ERROR;
15319   }
15320
15321   /* Store a pointer to the memory block in global structure mem3. */
15322   assert( sizeof(Mem3Block)==8 );
15323   mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
15324   mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
15325
15326   /* Initialize the master block. */
15327   mem3.szMaster = mem3.nPool;
15328   mem3.mnMaster = mem3.szMaster;
15329   mem3.iMaster = 1;
15330   mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
15331   mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
15332   mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
15333
15334   return SQLITE_OK;
15335 }
15336
15337 /*
15338 ** Deinitialize this module.
15339 */
15340 static void memsys3Shutdown(void *NotUsed){
15341   UNUSED_PARAMETER(NotUsed);
15342   mem3.mutex = 0;
15343   return;
15344 }
15345
15346
15347
15348 /*
15349 ** Open the file indicated and write a log of all unfreed memory 
15350 ** allocations into that log.
15351 */
15352 SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
15353 #ifdef SQLITE_DEBUG
15354   FILE *out;
15355   u32 i, j;
15356   u32 size;
15357   if( zFilename==0 || zFilename[0]==0 ){
15358     out = stdout;
15359   }else{
15360     out = fopen(zFilename, "w");
15361     if( out==0 ){
15362       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
15363                       zFilename);
15364       return;
15365     }
15366   }
15367   memsys3Enter();
15368   fprintf(out, "CHUNKS:\n");
15369   for(i=1; i<=mem3.nPool; i+=size/4){
15370     size = mem3.aPool[i-1].u.hdr.size4x;
15371     if( size/4<=1 ){
15372       fprintf(out, "%p size error\n", &mem3.aPool[i]);
15373       assert( 0 );
15374       break;
15375     }
15376     if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
15377       fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
15378       assert( 0 );
15379       break;
15380     }
15381     if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
15382       fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
15383       assert( 0 );
15384       break;
15385     }
15386     if( size&1 ){
15387       fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
15388     }else{
15389       fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
15390                   i==mem3.iMaster ? " **master**" : "");
15391     }
15392   }
15393   for(i=0; i<MX_SMALL-1; i++){
15394     if( mem3.aiSmall[i]==0 ) continue;
15395     fprintf(out, "small(%2d):", i);
15396     for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
15397       fprintf(out, " %p(%d)", &mem3.aPool[j],
15398               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
15399     }
15400     fprintf(out, "\n"); 
15401   }
15402   for(i=0; i<N_HASH; i++){
15403     if( mem3.aiHash[i]==0 ) continue;
15404     fprintf(out, "hash(%2d):", i);
15405     for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
15406       fprintf(out, " %p(%d)", &mem3.aPool[j],
15407               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
15408     }
15409     fprintf(out, "\n"); 
15410   }
15411   fprintf(out, "master=%d\n", mem3.iMaster);
15412   fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
15413   fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
15414   sqlite3_mutex_leave(mem3.mutex);
15415   if( out==stdout ){
15416     fflush(stdout);
15417   }else{
15418     fclose(out);
15419   }
15420 #else
15421   UNUSED_PARAMETER(zFilename);
15422 #endif
15423 }
15424
15425 /*
15426 ** This routine is the only routine in this file with external 
15427 ** linkage.
15428 **
15429 ** Populate the low-level memory allocation function pointers in
15430 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
15431 ** arguments specify the block of memory to manage.
15432 **
15433 ** This routine is only called by sqlite3_config(), and therefore
15434 ** is not required to be threadsafe (it is not).
15435 */
15436 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
15437   static const sqlite3_mem_methods mempoolMethods = {
15438      memsys3Malloc,
15439      memsys3Free,
15440      memsys3Realloc,
15441      memsys3Size,
15442      memsys3Roundup,
15443      memsys3Init,
15444      memsys3Shutdown,
15445      0
15446   };
15447   return &mempoolMethods;
15448 }
15449
15450 #endif /* SQLITE_ENABLE_MEMSYS3 */
15451
15452 /************** End of mem3.c ************************************************/
15453 /************** Begin file mem5.c ********************************************/
15454 /*
15455 ** 2007 October 14
15456 **
15457 ** The author disclaims copyright to this source code.  In place of
15458 ** a legal notice, here is a blessing:
15459 **
15460 **    May you do good and not evil.
15461 **    May you find forgiveness for yourself and forgive others.
15462 **    May you share freely, never taking more than you give.
15463 **
15464 *************************************************************************
15465 ** This file contains the C functions that implement a memory
15466 ** allocation subsystem for use by SQLite. 
15467 **
15468 ** This version of the memory allocation subsystem omits all
15469 ** use of malloc(). The application gives SQLite a block of memory
15470 ** before calling sqlite3_initialize() from which allocations
15471 ** are made and returned by the xMalloc() and xRealloc() 
15472 ** implementations. Once sqlite3_initialize() has been called,
15473 ** the amount of memory available to SQLite is fixed and cannot
15474 ** be changed.
15475 **
15476 ** This version of the memory allocation subsystem is included
15477 ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
15478 **
15479 ** This memory allocator uses the following algorithm:
15480 **
15481 **   1.  All memory allocations sizes are rounded up to a power of 2.
15482 **
15483 **   2.  If two adjacent free blocks are the halves of a larger block,
15484 **       then the two blocks are coalesed into the single larger block.
15485 **
15486 **   3.  New memory is allocated from the first available free block.
15487 **
15488 ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
15489 ** Concerning Dynamic Storage Allocation". Journal of the Association for
15490 ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
15491 ** 
15492 ** Let n be the size of the largest allocation divided by the minimum
15493 ** allocation size (after rounding all sizes up to a power of 2.)  Let M
15494 ** be the maximum amount of memory ever outstanding at one time.  Let
15495 ** N be the total amount of memory available for allocation.  Robson
15496 ** proved that this memory allocator will never breakdown due to 
15497 ** fragmentation as long as the following constraint holds:
15498 **
15499 **      N >=  M*(1 + log2(n)/2) - n + 1
15500 **
15501 ** The sqlite3_status() logic tracks the maximum values of n and M so
15502 ** that an application can, at any time, verify this constraint.
15503 */
15504
15505 /*
15506 ** This version of the memory allocator is used only when 
15507 ** SQLITE_ENABLE_MEMSYS5 is defined.
15508 */
15509 #ifdef SQLITE_ENABLE_MEMSYS5
15510
15511 /*
15512 ** A minimum allocation is an instance of the following structure.
15513 ** Larger allocations are an array of these structures where the
15514 ** size of the array is a power of 2.
15515 **
15516 ** The size of this object must be a power of two.  That fact is
15517 ** verified in memsys5Init().
15518 */
15519 typedef struct Mem5Link Mem5Link;
15520 struct Mem5Link {
15521   int next;       /* Index of next free chunk */
15522   int prev;       /* Index of previous free chunk */
15523 };
15524
15525 /*
15526 ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
15527 ** mem5.szAtom is always at least 8 and 32-bit integers are used,
15528 ** it is not actually possible to reach this limit.
15529 */
15530 #define LOGMAX 30
15531
15532 /*
15533 ** Masks used for mem5.aCtrl[] elements.
15534 */
15535 #define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block */
15536 #define CTRL_FREE     0x20    /* True if not checked out */
15537
15538 /*
15539 ** All of the static variables used by this module are collected
15540 ** into a single structure named "mem5".  This is to keep the
15541 ** static variables organized and to reduce namespace pollution
15542 ** when this module is combined with other in the amalgamation.
15543 */
15544 static SQLITE_WSD struct Mem5Global {
15545   /*
15546   ** Memory available for allocation
15547   */
15548   int szAtom;      /* Smallest possible allocation in bytes */
15549   int nBlock;      /* Number of szAtom sized blocks in zPool */
15550   u8 *zPool;       /* Memory available to be allocated */
15551   
15552   /*
15553   ** Mutex to control access to the memory allocation subsystem.
15554   */
15555   sqlite3_mutex *mutex;
15556
15557   /*
15558   ** Performance statistics
15559   */
15560   u64 nAlloc;         /* Total number of calls to malloc */
15561   u64 totalAlloc;     /* Total of all malloc calls - includes internal frag */
15562   u64 totalExcess;    /* Total internal fragmentation */
15563   u32 currentOut;     /* Current checkout, including internal fragmentation */
15564   u32 currentCount;   /* Current number of distinct checkouts */
15565   u32 maxOut;         /* Maximum instantaneous currentOut */
15566   u32 maxCount;       /* Maximum instantaneous currentCount */
15567   u32 maxRequest;     /* Largest allocation (exclusive of internal frag) */
15568   
15569   /*
15570   ** Lists of free blocks.  aiFreelist[0] is a list of free blocks of
15571   ** size mem5.szAtom.  aiFreelist[1] holds blocks of size szAtom*2.
15572   ** and so forth.
15573   */
15574   int aiFreelist[LOGMAX+1];
15575
15576   /*
15577   ** Space for tracking which blocks are checked out and the size
15578   ** of each block.  One byte per block.
15579   */
15580   u8 *aCtrl;
15581
15582 } mem5 = { 0 };
15583
15584 /*
15585 ** Access the static variable through a macro for SQLITE_OMIT_WSD
15586 */
15587 #define mem5 GLOBAL(struct Mem5Global, mem5)
15588
15589 /*
15590 ** Assuming mem5.zPool is divided up into an array of Mem5Link
15591 ** structures, return a pointer to the idx-th such lik.
15592 */
15593 #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
15594
15595 /*
15596 ** Unlink the chunk at mem5.aPool[i] from list it is currently
15597 ** on.  It should be found on mem5.aiFreelist[iLogsize].
15598 */
15599 static void memsys5Unlink(int i, int iLogsize){
15600   int next, prev;
15601   assert( i>=0 && i<mem5.nBlock );
15602   assert( iLogsize>=0 && iLogsize<=LOGMAX );
15603   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
15604
15605   next = MEM5LINK(i)->next;
15606   prev = MEM5LINK(i)->prev;
15607   if( prev<0 ){
15608     mem5.aiFreelist[iLogsize] = next;
15609   }else{
15610     MEM5LINK(prev)->next = next;
15611   }
15612   if( next>=0 ){
15613     MEM5LINK(next)->prev = prev;
15614   }
15615 }
15616
15617 /*
15618 ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
15619 ** free list.
15620 */
15621 static void memsys5Link(int i, int iLogsize){
15622   int x;
15623   assert( sqlite3_mutex_held(mem5.mutex) );
15624   assert( i>=0 && i<mem5.nBlock );
15625   assert( iLogsize>=0 && iLogsize<=LOGMAX );
15626   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
15627
15628   x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
15629   MEM5LINK(i)->prev = -1;
15630   if( x>=0 ){
15631     assert( x<mem5.nBlock );
15632     MEM5LINK(x)->prev = i;
15633   }
15634   mem5.aiFreelist[iLogsize] = i;
15635 }
15636
15637 /*
15638 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
15639 ** will already be held (obtained by code in malloc.c) if
15640 ** sqlite3GlobalConfig.bMemStat is true.
15641 */
15642 static void memsys5Enter(void){
15643   sqlite3_mutex_enter(mem5.mutex);
15644 }
15645 static void memsys5Leave(void){
15646   sqlite3_mutex_leave(mem5.mutex);
15647 }
15648
15649 /*
15650 ** Return the size of an outstanding allocation, in bytes.  The
15651 ** size returned omits the 8-byte header overhead.  This only
15652 ** works for chunks that are currently checked out.
15653 */
15654 static int memsys5Size(void *p){
15655   int iSize = 0;
15656   if( p ){
15657     int i = ((u8 *)p-mem5.zPool)/mem5.szAtom;
15658     assert( i>=0 && i<mem5.nBlock );
15659     iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
15660   }
15661   return iSize;
15662 }
15663
15664 /*
15665 ** Find the first entry on the freelist iLogsize.  Unlink that
15666 ** entry and return its index. 
15667 */
15668 static int memsys5UnlinkFirst(int iLogsize){
15669   int i;
15670   int iFirst;
15671
15672   assert( iLogsize>=0 && iLogsize<=LOGMAX );
15673   i = iFirst = mem5.aiFreelist[iLogsize];
15674   assert( iFirst>=0 );
15675   while( i>0 ){
15676     if( i<iFirst ) iFirst = i;
15677     i = MEM5LINK(i)->next;
15678   }
15679   memsys5Unlink(iFirst, iLogsize);
15680   return iFirst;
15681 }
15682
15683 /*
15684 ** Return a block of memory of at least nBytes in size.
15685 ** Return NULL if unable.  Return NULL if nBytes==0.
15686 **
15687 ** The caller guarantees that nByte positive.
15688 **
15689 ** The caller has obtained a mutex prior to invoking this
15690 ** routine so there is never any chance that two or more
15691 ** threads can be in this routine at the same time.
15692 */
15693 static void *memsys5MallocUnsafe(int nByte){
15694   int i;           /* Index of a mem5.aPool[] slot */
15695   int iBin;        /* Index into mem5.aiFreelist[] */
15696   int iFullSz;     /* Size of allocation rounded up to power of 2 */
15697   int iLogsize;    /* Log2 of iFullSz/POW2_MIN */
15698
15699   /* nByte must be a positive */
15700   assert( nByte>0 );
15701
15702   /* Keep track of the maximum allocation request.  Even unfulfilled
15703   ** requests are counted */
15704   if( (u32)nByte>mem5.maxRequest ){
15705     mem5.maxRequest = nByte;
15706   }
15707
15708   /* Abort if the requested allocation size is larger than the largest
15709   ** power of two that we can represent using 32-bit signed integers.
15710   */
15711   if( nByte > 0x40000000 ){
15712     return 0;
15713   }
15714
15715   /* Round nByte up to the next valid power of two */
15716   for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
15717
15718   /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
15719   ** block.  If not, then split a block of the next larger power of
15720   ** two in order to create a new free block of size iLogsize.
15721   */
15722   for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){}
15723   if( iBin>LOGMAX ){
15724     testcase( sqlite3GlobalConfig.xLog!=0 );
15725     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
15726     return 0;
15727   }
15728   i = memsys5UnlinkFirst(iBin);
15729   while( iBin>iLogsize ){
15730     int newSize;
15731
15732     iBin--;
15733     newSize = 1 << iBin;
15734     mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
15735     memsys5Link(i+newSize, iBin);
15736   }
15737   mem5.aCtrl[i] = iLogsize;
15738
15739   /* Update allocator performance statistics. */
15740   mem5.nAlloc++;
15741   mem5.totalAlloc += iFullSz;
15742   mem5.totalExcess += iFullSz - nByte;
15743   mem5.currentCount++;
15744   mem5.currentOut += iFullSz;
15745   if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
15746   if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
15747
15748   /* Return a pointer to the allocated memory. */
15749   return (void*)&mem5.zPool[i*mem5.szAtom];
15750 }
15751
15752 /*
15753 ** Free an outstanding memory allocation.
15754 */
15755 static void memsys5FreeUnsafe(void *pOld){
15756   u32 size, iLogsize;
15757   int iBlock;
15758
15759   /* Set iBlock to the index of the block pointed to by pOld in 
15760   ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
15761   */
15762   iBlock = ((u8 *)pOld-mem5.zPool)/mem5.szAtom;
15763
15764   /* Check that the pointer pOld points to a valid, non-free block. */
15765   assert( iBlock>=0 && iBlock<mem5.nBlock );
15766   assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
15767   assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
15768
15769   iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
15770   size = 1<<iLogsize;
15771   assert( iBlock+size-1<(u32)mem5.nBlock );
15772
15773   mem5.aCtrl[iBlock] |= CTRL_FREE;
15774   mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
15775   assert( mem5.currentCount>0 );
15776   assert( mem5.currentOut>=(size*mem5.szAtom) );
15777   mem5.currentCount--;
15778   mem5.currentOut -= size*mem5.szAtom;
15779   assert( mem5.currentOut>0 || mem5.currentCount==0 );
15780   assert( mem5.currentCount>0 || mem5.currentOut==0 );
15781
15782   mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
15783   while( ALWAYS(iLogsize<LOGMAX) ){
15784     int iBuddy;
15785     if( (iBlock>>iLogsize) & 1 ){
15786       iBuddy = iBlock - size;
15787     }else{
15788       iBuddy = iBlock + size;
15789     }
15790     assert( iBuddy>=0 );
15791     if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
15792     if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
15793     memsys5Unlink(iBuddy, iLogsize);
15794     iLogsize++;
15795     if( iBuddy<iBlock ){
15796       mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
15797       mem5.aCtrl[iBlock] = 0;
15798       iBlock = iBuddy;
15799     }else{
15800       mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
15801       mem5.aCtrl[iBuddy] = 0;
15802     }
15803     size *= 2;
15804   }
15805   memsys5Link(iBlock, iLogsize);
15806 }
15807
15808 /*
15809 ** Allocate nBytes of memory
15810 */
15811 static void *memsys5Malloc(int nBytes){
15812   sqlite3_int64 *p = 0;
15813   if( nBytes>0 ){
15814     memsys5Enter();
15815     p = memsys5MallocUnsafe(nBytes);
15816     memsys5Leave();
15817   }
15818   return (void*)p; 
15819 }
15820
15821 /*
15822 ** Free memory.
15823 **
15824 ** The outer layer memory allocator prevents this routine from
15825 ** being called with pPrior==0.
15826 */
15827 static void memsys5Free(void *pPrior){
15828   assert( pPrior!=0 );
15829   memsys5Enter();
15830   memsys5FreeUnsafe(pPrior);
15831   memsys5Leave();  
15832 }
15833
15834 /*
15835 ** Change the size of an existing memory allocation.
15836 **
15837 ** The outer layer memory allocator prevents this routine from
15838 ** being called with pPrior==0.  
15839 **
15840 ** nBytes is always a value obtained from a prior call to
15841 ** memsys5Round().  Hence nBytes is always a non-negative power
15842 ** of two.  If nBytes==0 that means that an oversize allocation
15843 ** (an allocation larger than 0x40000000) was requested and this
15844 ** routine should return 0 without freeing pPrior.
15845 */
15846 static void *memsys5Realloc(void *pPrior, int nBytes){
15847   int nOld;
15848   void *p;
15849   assert( pPrior!=0 );
15850   assert( (nBytes&(nBytes-1))==0 );  /* EV: R-46199-30249 */
15851   assert( nBytes>=0 );
15852   if( nBytes==0 ){
15853     return 0;
15854   }
15855   nOld = memsys5Size(pPrior);
15856   if( nBytes<=nOld ){
15857     return pPrior;
15858   }
15859   memsys5Enter();
15860   p = memsys5MallocUnsafe(nBytes);
15861   if( p ){
15862     memcpy(p, pPrior, nOld);
15863     memsys5FreeUnsafe(pPrior);
15864   }
15865   memsys5Leave();
15866   return p;
15867 }
15868
15869 /*
15870 ** Round up a request size to the next valid allocation size.  If
15871 ** the allocation is too large to be handled by this allocation system,
15872 ** return 0.
15873 **
15874 ** All allocations must be a power of two and must be expressed by a
15875 ** 32-bit signed integer.  Hence the largest allocation is 0x40000000
15876 ** or 1073741824 bytes.
15877 */
15878 static int memsys5Roundup(int n){
15879   int iFullSz;
15880   if( n > 0x40000000 ) return 0;
15881   for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
15882   return iFullSz;
15883 }
15884
15885 /*
15886 ** Return the ceiling of the logarithm base 2 of iValue.
15887 **
15888 ** Examples:   memsys5Log(1) -> 0
15889 **             memsys5Log(2) -> 1
15890 **             memsys5Log(4) -> 2
15891 **             memsys5Log(5) -> 3
15892 **             memsys5Log(8) -> 3
15893 **             memsys5Log(9) -> 4
15894 */
15895 static int memsys5Log(int iValue){
15896   int iLog;
15897   for(iLog=0; (1<<iLog)<iValue; iLog++);
15898   return iLog;
15899 }
15900
15901 /*
15902 ** Initialize the memory allocator.
15903 **
15904 ** This routine is not threadsafe.  The caller must be holding a mutex
15905 ** to prevent multiple threads from entering at the same time.
15906 */
15907 static int memsys5Init(void *NotUsed){
15908   int ii;            /* Loop counter */
15909   int nByte;         /* Number of bytes of memory available to this allocator */
15910   u8 *zByte;         /* Memory usable by this allocator */
15911   int nMinLog;       /* Log base 2 of minimum allocation size in bytes */
15912   int iOffset;       /* An offset into mem5.aCtrl[] */
15913
15914   UNUSED_PARAMETER(NotUsed);
15915
15916   /* For the purposes of this routine, disable the mutex */
15917   mem5.mutex = 0;
15918
15919   /* The size of a Mem5Link object must be a power of two.  Verify that
15920   ** this is case.
15921   */
15922   assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
15923
15924   nByte = sqlite3GlobalConfig.nHeap;
15925   zByte = (u8*)sqlite3GlobalConfig.pHeap;
15926   assert( zByte!=0 );  /* sqlite3_config() does not allow otherwise */
15927
15928   nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
15929   mem5.szAtom = (1<<nMinLog);
15930   while( (int)sizeof(Mem5Link)>mem5.szAtom ){
15931     mem5.szAtom = mem5.szAtom << 1;
15932   }
15933
15934   mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
15935   mem5.zPool = zByte;
15936   mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
15937
15938   for(ii=0; ii<=LOGMAX; ii++){
15939     mem5.aiFreelist[ii] = -1;
15940   }
15941
15942   iOffset = 0;
15943   for(ii=LOGMAX; ii>=0; ii--){
15944     int nAlloc = (1<<ii);
15945     if( (iOffset+nAlloc)<=mem5.nBlock ){
15946       mem5.aCtrl[iOffset] = ii | CTRL_FREE;
15947       memsys5Link(iOffset, ii);
15948       iOffset += nAlloc;
15949     }
15950     assert((iOffset+nAlloc)>mem5.nBlock);
15951   }
15952
15953   /* If a mutex is required for normal operation, allocate one */
15954   if( sqlite3GlobalConfig.bMemstat==0 ){
15955     mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
15956   }
15957
15958   return SQLITE_OK;
15959 }
15960
15961 /*
15962 ** Deinitialize this module.
15963 */
15964 static void memsys5Shutdown(void *NotUsed){
15965   UNUSED_PARAMETER(NotUsed);
15966   mem5.mutex = 0;
15967   return;
15968 }
15969
15970 #ifdef SQLITE_TEST
15971 /*
15972 ** Open the file indicated and write a log of all unfreed memory 
15973 ** allocations into that log.
15974 */
15975 SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
15976   FILE *out;
15977   int i, j, n;
15978   int nMinLog;
15979
15980   if( zFilename==0 || zFilename[0]==0 ){
15981     out = stdout;
15982   }else{
15983     out = fopen(zFilename, "w");
15984     if( out==0 ){
15985       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
15986                       zFilename);
15987       return;
15988     }
15989   }
15990   memsys5Enter();
15991   nMinLog = memsys5Log(mem5.szAtom);
15992   for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
15993     for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
15994     fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
15995   }
15996   fprintf(out, "mem5.nAlloc       = %llu\n", mem5.nAlloc);
15997   fprintf(out, "mem5.totalAlloc   = %llu\n", mem5.totalAlloc);
15998   fprintf(out, "mem5.totalExcess  = %llu\n", mem5.totalExcess);
15999   fprintf(out, "mem5.currentOut   = %u\n", mem5.currentOut);
16000   fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
16001   fprintf(out, "mem5.maxOut       = %u\n", mem5.maxOut);
16002   fprintf(out, "mem5.maxCount     = %u\n", mem5.maxCount);
16003   fprintf(out, "mem5.maxRequest   = %u\n", mem5.maxRequest);
16004   memsys5Leave();
16005   if( out==stdout ){
16006     fflush(stdout);
16007   }else{
16008     fclose(out);
16009   }
16010 }
16011 #endif
16012
16013 /*
16014 ** This routine is the only routine in this file with external 
16015 ** linkage. It returns a pointer to a static sqlite3_mem_methods
16016 ** struct populated with the memsys5 methods.
16017 */
16018 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
16019   static const sqlite3_mem_methods memsys5Methods = {
16020      memsys5Malloc,
16021      memsys5Free,
16022      memsys5Realloc,
16023      memsys5Size,
16024      memsys5Roundup,
16025      memsys5Init,
16026      memsys5Shutdown,
16027      0
16028   };
16029   return &memsys5Methods;
16030 }
16031
16032 #endif /* SQLITE_ENABLE_MEMSYS5 */
16033
16034 /************** End of mem5.c ************************************************/
16035 /************** Begin file mutex.c *******************************************/
16036 /*
16037 ** 2007 August 14
16038 **
16039 ** The author disclaims copyright to this source code.  In place of
16040 ** a legal notice, here is a blessing:
16041 **
16042 **    May you do good and not evil.
16043 **    May you find forgiveness for yourself and forgive others.
16044 **    May you share freely, never taking more than you give.
16045 **
16046 *************************************************************************
16047 ** This file contains the C functions that implement mutexes.
16048 **
16049 ** This file contains code that is common across all mutex implementations.
16050 */
16051
16052 #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
16053 /*
16054 ** For debugging purposes, record when the mutex subsystem is initialized
16055 ** and uninitialized so that we can assert() if there is an attempt to
16056 ** allocate a mutex while the system is uninitialized.
16057 */
16058 static SQLITE_WSD int mutexIsInit = 0;
16059 #endif /* SQLITE_DEBUG */
16060
16061
16062 #ifndef SQLITE_MUTEX_OMIT
16063 /*
16064 ** Initialize the mutex system.
16065 */
16066 SQLITE_PRIVATE int sqlite3MutexInit(void){ 
16067   int rc = SQLITE_OK;
16068   if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
16069     /* If the xMutexAlloc method has not been set, then the user did not
16070     ** install a mutex implementation via sqlite3_config() prior to 
16071     ** sqlite3_initialize() being called. This block copies pointers to
16072     ** the default implementation into the sqlite3GlobalConfig structure.
16073     */
16074     sqlite3_mutex_methods const *pFrom;
16075     sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
16076
16077     if( sqlite3GlobalConfig.bCoreMutex ){
16078       pFrom = sqlite3DefaultMutex();
16079     }else{
16080       pFrom = sqlite3NoopMutex();
16081     }
16082     memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc));
16083     memcpy(&pTo->xMutexFree, &pFrom->xMutexFree,
16084            sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree));
16085     pTo->xMutexAlloc = pFrom->xMutexAlloc;
16086   }
16087   rc = sqlite3GlobalConfig.mutex.xMutexInit();
16088
16089 #ifdef SQLITE_DEBUG
16090   GLOBAL(int, mutexIsInit) = 1;
16091 #endif
16092
16093   return rc;
16094 }
16095
16096 /*
16097 ** Shutdown the mutex system. This call frees resources allocated by
16098 ** sqlite3MutexInit().
16099 */
16100 SQLITE_PRIVATE int sqlite3MutexEnd(void){
16101   int rc = SQLITE_OK;
16102   if( sqlite3GlobalConfig.mutex.xMutexEnd ){
16103     rc = sqlite3GlobalConfig.mutex.xMutexEnd();
16104   }
16105
16106 #ifdef SQLITE_DEBUG
16107   GLOBAL(int, mutexIsInit) = 0;
16108 #endif
16109
16110   return rc;
16111 }
16112
16113 /*
16114 ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
16115 */
16116 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
16117 #ifndef SQLITE_OMIT_AUTOINIT
16118   if( sqlite3_initialize() ) return 0;
16119 #endif
16120   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
16121 }
16122
16123 SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
16124   if( !sqlite3GlobalConfig.bCoreMutex ){
16125     return 0;
16126   }
16127   assert( GLOBAL(int, mutexIsInit) );
16128   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
16129 }
16130
16131 /*
16132 ** Free a dynamic mutex.
16133 */
16134 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
16135   if( p ){
16136     sqlite3GlobalConfig.mutex.xMutexFree(p);
16137   }
16138 }
16139
16140 /*
16141 ** Obtain the mutex p. If some other thread already has the mutex, block
16142 ** until it can be obtained.
16143 */
16144 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
16145   if( p ){
16146     sqlite3GlobalConfig.mutex.xMutexEnter(p);
16147   }
16148 }
16149
16150 /*
16151 ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
16152 ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
16153 */
16154 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
16155   int rc = SQLITE_OK;
16156   if( p ){
16157     return sqlite3GlobalConfig.mutex.xMutexTry(p);
16158   }
16159   return rc;
16160 }
16161
16162 /*
16163 ** The sqlite3_mutex_leave() routine exits a mutex that was previously
16164 ** entered by the same thread.  The behavior is undefined if the mutex 
16165 ** is not currently entered. If a NULL pointer is passed as an argument
16166 ** this function is a no-op.
16167 */
16168 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
16169   if( p ){
16170     sqlite3GlobalConfig.mutex.xMutexLeave(p);
16171   }
16172 }
16173
16174 #ifndef NDEBUG
16175 /*
16176 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
16177 ** intended for use inside assert() statements.
16178 */
16179 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
16180   return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
16181 }
16182 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
16183   return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
16184 }
16185 #endif
16186
16187 #endif /* SQLITE_MUTEX_OMIT */
16188
16189 /************** End of mutex.c ***********************************************/
16190 /************** Begin file mutex_noop.c **************************************/
16191 /*
16192 ** 2008 October 07
16193 **
16194 ** The author disclaims copyright to this source code.  In place of
16195 ** a legal notice, here is a blessing:
16196 **
16197 **    May you do good and not evil.
16198 **    May you find forgiveness for yourself and forgive others.
16199 **    May you share freely, never taking more than you give.
16200 **
16201 *************************************************************************
16202 ** This file contains the C functions that implement mutexes.
16203 **
16204 ** This implementation in this file does not provide any mutual
16205 ** exclusion and is thus suitable for use only in applications
16206 ** that use SQLite in a single thread.  The routines defined
16207 ** here are place-holders.  Applications can substitute working
16208 ** mutex routines at start-time using the
16209 **
16210 **     sqlite3_config(SQLITE_CONFIG_MUTEX,...)
16211 **
16212 ** interface.
16213 **
16214 ** If compiled with SQLITE_DEBUG, then additional logic is inserted
16215 ** that does error checking on mutexes to make sure they are being
16216 ** called correctly.
16217 */
16218
16219 #ifndef SQLITE_MUTEX_OMIT
16220
16221 #ifndef SQLITE_DEBUG
16222 /*
16223 ** Stub routines for all mutex methods.
16224 **
16225 ** This routines provide no mutual exclusion or error checking.
16226 */
16227 static int noopMutexInit(void){ return SQLITE_OK; }
16228 static int noopMutexEnd(void){ return SQLITE_OK; }
16229 static sqlite3_mutex *noopMutexAlloc(int id){ 
16230   UNUSED_PARAMETER(id);
16231   return (sqlite3_mutex*)8; 
16232 }
16233 static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
16234 static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
16235 static int noopMutexTry(sqlite3_mutex *p){
16236   UNUSED_PARAMETER(p);
16237   return SQLITE_OK;
16238 }
16239 static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
16240
16241 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
16242   static const sqlite3_mutex_methods sMutex = {
16243     noopMutexInit,
16244     noopMutexEnd,
16245     noopMutexAlloc,
16246     noopMutexFree,
16247     noopMutexEnter,
16248     noopMutexTry,
16249     noopMutexLeave,
16250
16251     0,
16252     0,
16253   };
16254
16255   return &sMutex;
16256 }
16257 #endif /* !SQLITE_DEBUG */
16258
16259 #ifdef SQLITE_DEBUG
16260 /*
16261 ** In this implementation, error checking is provided for testing
16262 ** and debugging purposes.  The mutexes still do not provide any
16263 ** mutual exclusion.
16264 */
16265
16266 /*
16267 ** The mutex object
16268 */
16269 typedef struct sqlite3_debug_mutex {
16270   int id;     /* The mutex type */
16271   int cnt;    /* Number of entries without a matching leave */
16272 } sqlite3_debug_mutex;
16273
16274 /*
16275 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
16276 ** intended for use inside assert() statements.
16277 */
16278 static int debugMutexHeld(sqlite3_mutex *pX){
16279   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16280   return p==0 || p->cnt>0;
16281 }
16282 static int debugMutexNotheld(sqlite3_mutex *pX){
16283   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16284   return p==0 || p->cnt==0;
16285 }
16286
16287 /*
16288 ** Initialize and deinitialize the mutex subsystem.
16289 */
16290 static int debugMutexInit(void){ return SQLITE_OK; }
16291 static int debugMutexEnd(void){ return SQLITE_OK; }
16292
16293 /*
16294 ** The sqlite3_mutex_alloc() routine allocates a new
16295 ** mutex and returns a pointer to it.  If it returns NULL
16296 ** that means that a mutex could not be allocated. 
16297 */
16298 static sqlite3_mutex *debugMutexAlloc(int id){
16299   static sqlite3_debug_mutex aStatic[6];
16300   sqlite3_debug_mutex *pNew = 0;
16301   switch( id ){
16302     case SQLITE_MUTEX_FAST:
16303     case SQLITE_MUTEX_RECURSIVE: {
16304       pNew = sqlite3Malloc(sizeof(*pNew));
16305       if( pNew ){
16306         pNew->id = id;
16307         pNew->cnt = 0;
16308       }
16309       break;
16310     }
16311     default: {
16312       assert( id-2 >= 0 );
16313       assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) );
16314       pNew = &aStatic[id-2];
16315       pNew->id = id;
16316       break;
16317     }
16318   }
16319   return (sqlite3_mutex*)pNew;
16320 }
16321
16322 /*
16323 ** This routine deallocates a previously allocated mutex.
16324 */
16325 static void debugMutexFree(sqlite3_mutex *pX){
16326   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16327   assert( p->cnt==0 );
16328   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
16329   sqlite3_free(p);
16330 }
16331
16332 /*
16333 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
16334 ** to enter a mutex.  If another thread is already within the mutex,
16335 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
16336 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
16337 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
16338 ** be entered multiple times by the same thread.  In such cases the,
16339 ** mutex must be exited an equal number of times before another thread
16340 ** can enter.  If the same thread tries to enter any other kind of mutex
16341 ** more than once, the behavior is undefined.
16342 */
16343 static void debugMutexEnter(sqlite3_mutex *pX){
16344   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16345   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
16346   p->cnt++;
16347 }
16348 static int debugMutexTry(sqlite3_mutex *pX){
16349   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16350   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
16351   p->cnt++;
16352   return SQLITE_OK;
16353 }
16354
16355 /*
16356 ** The sqlite3_mutex_leave() routine exits a mutex that was
16357 ** previously entered by the same thread.  The behavior
16358 ** is undefined if the mutex is not currently entered or
16359 ** is not currently allocated.  SQLite will never do either.
16360 */
16361 static void debugMutexLeave(sqlite3_mutex *pX){
16362   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16363   assert( debugMutexHeld(pX) );
16364   p->cnt--;
16365   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
16366 }
16367
16368 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
16369   static const sqlite3_mutex_methods sMutex = {
16370     debugMutexInit,
16371     debugMutexEnd,
16372     debugMutexAlloc,
16373     debugMutexFree,
16374     debugMutexEnter,
16375     debugMutexTry,
16376     debugMutexLeave,
16377
16378     debugMutexHeld,
16379     debugMutexNotheld
16380   };
16381
16382   return &sMutex;
16383 }
16384 #endif /* SQLITE_DEBUG */
16385
16386 /*
16387 ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
16388 ** is used regardless of the run-time threadsafety setting.
16389 */
16390 #ifdef SQLITE_MUTEX_NOOP
16391 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
16392   return sqlite3NoopMutex();
16393 }
16394 #endif /* SQLITE_MUTEX_NOOP */
16395 #endif /* SQLITE_MUTEX_OMIT */
16396
16397 /************** End of mutex_noop.c ******************************************/
16398 /************** Begin file mutex_os2.c ***************************************/
16399 /*
16400 ** 2007 August 28
16401 **
16402 ** The author disclaims copyright to this source code.  In place of
16403 ** a legal notice, here is a blessing:
16404 **
16405 **    May you do good and not evil.
16406 **    May you find forgiveness for yourself and forgive others.
16407 **    May you share freely, never taking more than you give.
16408 **
16409 *************************************************************************
16410 ** This file contains the C functions that implement mutexes for OS/2
16411 */
16412
16413 /*
16414 ** The code in this file is only used if SQLITE_MUTEX_OS2 is defined.
16415 ** See the mutex.h file for details.
16416 */
16417 #ifdef SQLITE_MUTEX_OS2
16418
16419 /********************** OS/2 Mutex Implementation **********************
16420 **
16421 ** This implementation of mutexes is built using the OS/2 API.
16422 */
16423
16424 /*
16425 ** The mutex object
16426 ** Each recursive mutex is an instance of the following structure.
16427 */
16428 struct sqlite3_mutex {
16429   HMTX mutex;       /* Mutex controlling the lock */
16430   int  id;          /* Mutex type */
16431   int  nRef;        /* Number of references */
16432   TID  owner;       /* Thread holding this mutex */
16433 };
16434
16435 #define OS2_MUTEX_INITIALIZER   0,0,0,0
16436
16437 /*
16438 ** Initialize and deinitialize the mutex subsystem.
16439 */
16440 static int os2MutexInit(void){ return SQLITE_OK; }
16441 static int os2MutexEnd(void){ return SQLITE_OK; }
16442
16443 /*
16444 ** The sqlite3_mutex_alloc() routine allocates a new
16445 ** mutex and returns a pointer to it.  If it returns NULL
16446 ** that means that a mutex could not be allocated. 
16447 ** SQLite will unwind its stack and return an error.  The argument
16448 ** to sqlite3_mutex_alloc() is one of these integer constants:
16449 **
16450 ** <ul>
16451 ** <li>  SQLITE_MUTEX_FAST               0
16452 ** <li>  SQLITE_MUTEX_RECURSIVE          1
16453 ** <li>  SQLITE_MUTEX_STATIC_MASTER      2
16454 ** <li>  SQLITE_MUTEX_STATIC_MEM         3
16455 ** <li>  SQLITE_MUTEX_STATIC_PRNG        4
16456 ** </ul>
16457 **
16458 ** The first two constants cause sqlite3_mutex_alloc() to create
16459 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
16460 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
16461 ** The mutex implementation does not need to make a distinction
16462 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
16463 ** not want to.  But SQLite will only request a recursive mutex in
16464 ** cases where it really needs one.  If a faster non-recursive mutex
16465 ** implementation is available on the host platform, the mutex subsystem
16466 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
16467 **
16468 ** The other allowed parameters to sqlite3_mutex_alloc() each return
16469 ** a pointer to a static preexisting mutex.  Three static mutexes are
16470 ** used by the current version of SQLite.  Future versions of SQLite
16471 ** may add additional static mutexes.  Static mutexes are for internal
16472 ** use by SQLite only.  Applications that use SQLite mutexes should
16473 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
16474 ** SQLITE_MUTEX_RECURSIVE.
16475 **
16476 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
16477 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
16478 ** returns a different mutex on every call.  But for the static
16479 ** mutex types, the same mutex is returned on every call that has
16480 ** the same type number.
16481 */
16482 static sqlite3_mutex *os2MutexAlloc(int iType){
16483   sqlite3_mutex *p = NULL;
16484   switch( iType ){
16485     case SQLITE_MUTEX_FAST:
16486     case SQLITE_MUTEX_RECURSIVE: {
16487       p = sqlite3MallocZero( sizeof(*p) );
16488       if( p ){
16489         p->id = iType;
16490         if( DosCreateMutexSem( 0, &p->mutex, 0, FALSE ) != NO_ERROR ){
16491           sqlite3_free( p );
16492           p = NULL;
16493         }
16494       }
16495       break;
16496     }
16497     default: {
16498       static volatile int isInit = 0;
16499       static sqlite3_mutex staticMutexes[] = {
16500         { OS2_MUTEX_INITIALIZER, },
16501         { OS2_MUTEX_INITIALIZER, },
16502         { OS2_MUTEX_INITIALIZER, },
16503         { OS2_MUTEX_INITIALIZER, },
16504         { OS2_MUTEX_INITIALIZER, },
16505         { OS2_MUTEX_INITIALIZER, },
16506       };
16507       if ( !isInit ){
16508         APIRET rc;
16509         PTIB ptib;
16510         PPIB ppib;
16511         HMTX mutex;
16512         char name[32];
16513         DosGetInfoBlocks( &ptib, &ppib );
16514         sqlite3_snprintf( sizeof(name), name, "\\SEM32\\SQLITE%04x",
16515                           ppib->pib_ulpid );
16516         while( !isInit ){
16517           mutex = 0;
16518           rc = DosCreateMutexSem( name, &mutex, 0, FALSE);
16519           if( rc == NO_ERROR ){
16520             unsigned int i;
16521             if( !isInit ){
16522               for( i = 0; i < sizeof(staticMutexes)/sizeof(staticMutexes[0]); i++ ){
16523                 DosCreateMutexSem( 0, &staticMutexes[i].mutex, 0, FALSE );
16524               }
16525               isInit = 1;
16526             }
16527             DosCloseMutexSem( mutex );
16528           }else if( rc == ERROR_DUPLICATE_NAME ){
16529             DosSleep( 1 );
16530           }else{
16531             return p;
16532           }
16533         }
16534       }
16535       assert( iType-2 >= 0 );
16536       assert( iType-2 < sizeof(staticMutexes)/sizeof(staticMutexes[0]) );
16537       p = &staticMutexes[iType-2];
16538       p->id = iType;
16539       break;
16540     }
16541   }
16542   return p;
16543 }
16544
16545
16546 /*
16547 ** This routine deallocates a previously allocated mutex.
16548 ** SQLite is careful to deallocate every mutex that it allocates.
16549 */
16550 static void os2MutexFree(sqlite3_mutex *p){
16551   if( p==0 ) return;
16552   assert( p->nRef==0 );
16553   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
16554   DosCloseMutexSem( p->mutex );
16555   sqlite3_free( p );
16556 }
16557
16558 #ifdef SQLITE_DEBUG
16559 /*
16560 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
16561 ** intended for use inside assert() statements.
16562 */
16563 static int os2MutexHeld(sqlite3_mutex *p){
16564   TID tid;
16565   PID pid;
16566   ULONG ulCount;
16567   PTIB ptib;
16568   if( p!=0 ) {
16569     DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
16570   } else {
16571     DosGetInfoBlocks(&ptib, NULL);
16572     tid = ptib->tib_ptib2->tib2_ultid;
16573   }
16574   return p==0 || (p->nRef!=0 && p->owner==tid);
16575 }
16576 static int os2MutexNotheld(sqlite3_mutex *p){
16577   TID tid;
16578   PID pid;
16579   ULONG ulCount;
16580   PTIB ptib;
16581   if( p!= 0 ) {
16582     DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
16583   } else {
16584     DosGetInfoBlocks(&ptib, NULL);
16585     tid = ptib->tib_ptib2->tib2_ultid;
16586   }
16587   return p==0 || p->nRef==0 || p->owner!=tid;
16588 }
16589 #endif
16590
16591 /*
16592 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
16593 ** to enter a mutex.  If another thread is already within the mutex,
16594 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
16595 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
16596 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
16597 ** be entered multiple times by the same thread.  In such cases the,
16598 ** mutex must be exited an equal number of times before another thread
16599 ** can enter.  If the same thread tries to enter any other kind of mutex
16600 ** more than once, the behavior is undefined.
16601 */
16602 static void os2MutexEnter(sqlite3_mutex *p){
16603   TID tid;
16604   PID holder1;
16605   ULONG holder2;
16606   if( p==0 ) return;
16607   assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
16608   DosRequestMutexSem(p->mutex, SEM_INDEFINITE_WAIT);
16609   DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
16610   p->owner = tid;
16611   p->nRef++;
16612 }
16613 static int os2MutexTry(sqlite3_mutex *p){
16614   int rc;
16615   TID tid;
16616   PID holder1;
16617   ULONG holder2;
16618   if( p==0 ) return SQLITE_OK;
16619   assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
16620   if( DosRequestMutexSem(p->mutex, SEM_IMMEDIATE_RETURN) == NO_ERROR) {
16621     DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
16622     p->owner = tid;
16623     p->nRef++;
16624     rc = SQLITE_OK;
16625   } else {
16626     rc = SQLITE_BUSY;
16627   }
16628
16629   return rc;
16630 }
16631
16632 /*
16633 ** The sqlite3_mutex_leave() routine exits a mutex that was
16634 ** previously entered by the same thread.  The behavior
16635 ** is undefined if the mutex is not currently entered or
16636 ** is not currently allocated.  SQLite will never do either.
16637 */
16638 static void os2MutexLeave(sqlite3_mutex *p){
16639   TID tid;
16640   PID holder1;
16641   ULONG holder2;
16642   if( p==0 ) return;
16643   assert( p->nRef>0 );
16644   DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
16645   assert( p->owner==tid );
16646   p->nRef--;
16647   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
16648   DosReleaseMutexSem(p->mutex);
16649 }
16650
16651 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
16652   static const sqlite3_mutex_methods sMutex = {
16653     os2MutexInit,
16654     os2MutexEnd,
16655     os2MutexAlloc,
16656     os2MutexFree,
16657     os2MutexEnter,
16658     os2MutexTry,
16659     os2MutexLeave,
16660 #ifdef SQLITE_DEBUG
16661     os2MutexHeld,
16662     os2MutexNotheld
16663 #endif
16664   };
16665
16666   return &sMutex;
16667 }
16668 #endif /* SQLITE_MUTEX_OS2 */
16669
16670 /************** End of mutex_os2.c *******************************************/
16671 /************** Begin file mutex_unix.c **************************************/
16672 /*
16673 ** 2007 August 28
16674 **
16675 ** The author disclaims copyright to this source code.  In place of
16676 ** a legal notice, here is a blessing:
16677 **
16678 **    May you do good and not evil.
16679 **    May you find forgiveness for yourself and forgive others.
16680 **    May you share freely, never taking more than you give.
16681 **
16682 *************************************************************************
16683 ** This file contains the C functions that implement mutexes for pthreads
16684 */
16685
16686 /*
16687 ** The code in this file is only used if we are compiling threadsafe
16688 ** under unix with pthreads.
16689 **
16690 ** Note that this implementation requires a version of pthreads that
16691 ** supports recursive mutexes.
16692 */
16693 #ifdef SQLITE_MUTEX_PTHREADS
16694
16695 #include <pthread.h>
16696
16697 /*
16698 ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
16699 ** are necessary under two condidtions:  (1) Debug builds and (2) using
16700 ** home-grown mutexes.  Encapsulate these conditions into a single #define.
16701 */
16702 #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
16703 # define SQLITE_MUTEX_NREF 1
16704 #else
16705 # define SQLITE_MUTEX_NREF 0
16706 #endif
16707
16708 /*
16709 ** Each recursive mutex is an instance of the following structure.
16710 */
16711 struct sqlite3_mutex {
16712   pthread_mutex_t mutex;     /* Mutex controlling the lock */
16713 #if SQLITE_MUTEX_NREF
16714   int id;                    /* Mutex type */
16715   volatile int nRef;         /* Number of entrances */
16716   volatile pthread_t owner;  /* Thread that is within this mutex */
16717   int trace;                 /* True to trace changes */
16718 #endif
16719 };
16720 #if SQLITE_MUTEX_NREF
16721 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
16722 #else
16723 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
16724 #endif
16725
16726 /*
16727 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
16728 ** intended for use only inside assert() statements.  On some platforms,
16729 ** there might be race conditions that can cause these routines to
16730 ** deliver incorrect results.  In particular, if pthread_equal() is
16731 ** not an atomic operation, then these routines might delivery
16732 ** incorrect results.  On most platforms, pthread_equal() is a 
16733 ** comparison of two integers and is therefore atomic.  But we are
16734 ** told that HPUX is not such a platform.  If so, then these routines
16735 ** will not always work correctly on HPUX.
16736 **
16737 ** On those platforms where pthread_equal() is not atomic, SQLite
16738 ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
16739 ** make sure no assert() statements are evaluated and hence these
16740 ** routines are never called.
16741 */
16742 #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
16743 static int pthreadMutexHeld(sqlite3_mutex *p){
16744   return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
16745 }
16746 static int pthreadMutexNotheld(sqlite3_mutex *p){
16747   return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
16748 }
16749 #endif
16750
16751 /*
16752 ** Initialize and deinitialize the mutex subsystem.
16753 */
16754 static int pthreadMutexInit(void){ return SQLITE_OK; }
16755 static int pthreadMutexEnd(void){ return SQLITE_OK; }
16756
16757 /*
16758 ** The sqlite3_mutex_alloc() routine allocates a new
16759 ** mutex and returns a pointer to it.  If it returns NULL
16760 ** that means that a mutex could not be allocated.  SQLite
16761 ** will unwind its stack and return an error.  The argument
16762 ** to sqlite3_mutex_alloc() is one of these integer constants:
16763 **
16764 ** <ul>
16765 ** <li>  SQLITE_MUTEX_FAST
16766 ** <li>  SQLITE_MUTEX_RECURSIVE
16767 ** <li>  SQLITE_MUTEX_STATIC_MASTER
16768 ** <li>  SQLITE_MUTEX_STATIC_MEM
16769 ** <li>  SQLITE_MUTEX_STATIC_MEM2
16770 ** <li>  SQLITE_MUTEX_STATIC_PRNG
16771 ** <li>  SQLITE_MUTEX_STATIC_LRU
16772 ** <li>  SQLITE_MUTEX_STATIC_LRU2
16773 ** </ul>
16774 **
16775 ** The first two constants cause sqlite3_mutex_alloc() to create
16776 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
16777 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
16778 ** The mutex implementation does not need to make a distinction
16779 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
16780 ** not want to.  But SQLite will only request a recursive mutex in
16781 ** cases where it really needs one.  If a faster non-recursive mutex
16782 ** implementation is available on the host platform, the mutex subsystem
16783 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
16784 **
16785 ** The other allowed parameters to sqlite3_mutex_alloc() each return
16786 ** a pointer to a static preexisting mutex.  Six static mutexes are
16787 ** used by the current version of SQLite.  Future versions of SQLite
16788 ** may add additional static mutexes.  Static mutexes are for internal
16789 ** use by SQLite only.  Applications that use SQLite mutexes should
16790 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
16791 ** SQLITE_MUTEX_RECURSIVE.
16792 **
16793 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
16794 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
16795 ** returns a different mutex on every call.  But for the static 
16796 ** mutex types, the same mutex is returned on every call that has
16797 ** the same type number.
16798 */
16799 static sqlite3_mutex *pthreadMutexAlloc(int iType){
16800   static sqlite3_mutex staticMutexes[] = {
16801     SQLITE3_MUTEX_INITIALIZER,
16802     SQLITE3_MUTEX_INITIALIZER,
16803     SQLITE3_MUTEX_INITIALIZER,
16804     SQLITE3_MUTEX_INITIALIZER,
16805     SQLITE3_MUTEX_INITIALIZER,
16806     SQLITE3_MUTEX_INITIALIZER
16807   };
16808   sqlite3_mutex *p;
16809   switch( iType ){
16810     case SQLITE_MUTEX_RECURSIVE: {
16811       p = sqlite3MallocZero( sizeof(*p) );
16812       if( p ){
16813 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
16814         /* If recursive mutexes are not available, we will have to
16815         ** build our own.  See below. */
16816         pthread_mutex_init(&p->mutex, 0);
16817 #else
16818         /* Use a recursive mutex if it is available */
16819         pthread_mutexattr_t recursiveAttr;
16820         pthread_mutexattr_init(&recursiveAttr);
16821         pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
16822         pthread_mutex_init(&p->mutex, &recursiveAttr);
16823         pthread_mutexattr_destroy(&recursiveAttr);
16824 #endif
16825 #if SQLITE_MUTEX_NREF
16826         p->id = iType;
16827 #endif
16828       }
16829       break;
16830     }
16831     case SQLITE_MUTEX_FAST: {
16832       p = sqlite3MallocZero( sizeof(*p) );
16833       if( p ){
16834 #if SQLITE_MUTEX_NREF
16835         p->id = iType;
16836 #endif
16837         pthread_mutex_init(&p->mutex, 0);
16838       }
16839       break;
16840     }
16841     default: {
16842       assert( iType-2 >= 0 );
16843       assert( iType-2 < ArraySize(staticMutexes) );
16844       p = &staticMutexes[iType-2];
16845 #if SQLITE_MUTEX_NREF
16846       p->id = iType;
16847 #endif
16848       break;
16849     }
16850   }
16851   return p;
16852 }
16853
16854
16855 /*
16856 ** This routine deallocates a previously
16857 ** allocated mutex.  SQLite is careful to deallocate every
16858 ** mutex that it allocates.
16859 */
16860 static void pthreadMutexFree(sqlite3_mutex *p){
16861   assert( p->nRef==0 );
16862   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
16863   pthread_mutex_destroy(&p->mutex);
16864   sqlite3_free(p);
16865 }
16866
16867 /*
16868 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
16869 ** to enter a mutex.  If another thread is already within the mutex,
16870 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
16871 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
16872 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
16873 ** be entered multiple times by the same thread.  In such cases the,
16874 ** mutex must be exited an equal number of times before another thread
16875 ** can enter.  If the same thread tries to enter any other kind of mutex
16876 ** more than once, the behavior is undefined.
16877 */
16878 static void pthreadMutexEnter(sqlite3_mutex *p){
16879   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
16880
16881 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
16882   /* If recursive mutexes are not available, then we have to grow
16883   ** our own.  This implementation assumes that pthread_equal()
16884   ** is atomic - that it cannot be deceived into thinking self
16885   ** and p->owner are equal if p->owner changes between two values
16886   ** that are not equal to self while the comparison is taking place.
16887   ** This implementation also assumes a coherent cache - that 
16888   ** separate processes cannot read different values from the same
16889   ** address at the same time.  If either of these two conditions
16890   ** are not met, then the mutexes will fail and problems will result.
16891   */
16892   {
16893     pthread_t self = pthread_self();
16894     if( p->nRef>0 && pthread_equal(p->owner, self) ){
16895       p->nRef++;
16896     }else{
16897       pthread_mutex_lock(&p->mutex);
16898       assert( p->nRef==0 );
16899       p->owner = self;
16900       p->nRef = 1;
16901     }
16902   }
16903 #else
16904   /* Use the built-in recursive mutexes if they are available.
16905   */
16906   pthread_mutex_lock(&p->mutex);
16907 #if SQLITE_MUTEX_NREF
16908   assert( p->nRef>0 || p->owner==0 );
16909   p->owner = pthread_self();
16910   p->nRef++;
16911 #endif
16912 #endif
16913
16914 #ifdef SQLITE_DEBUG
16915   if( p->trace ){
16916     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
16917   }
16918 #endif
16919 }
16920 static int pthreadMutexTry(sqlite3_mutex *p){
16921   int rc;
16922   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
16923
16924 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
16925   /* If recursive mutexes are not available, then we have to grow
16926   ** our own.  This implementation assumes that pthread_equal()
16927   ** is atomic - that it cannot be deceived into thinking self
16928   ** and p->owner are equal if p->owner changes between two values
16929   ** that are not equal to self while the comparison is taking place.
16930   ** This implementation also assumes a coherent cache - that 
16931   ** separate processes cannot read different values from the same
16932   ** address at the same time.  If either of these two conditions
16933   ** are not met, then the mutexes will fail and problems will result.
16934   */
16935   {
16936     pthread_t self = pthread_self();
16937     if( p->nRef>0 && pthread_equal(p->owner, self) ){
16938       p->nRef++;
16939       rc = SQLITE_OK;
16940     }else if( pthread_mutex_trylock(&p->mutex)==0 ){
16941       assert( p->nRef==0 );
16942       p->owner = self;
16943       p->nRef = 1;
16944       rc = SQLITE_OK;
16945     }else{
16946       rc = SQLITE_BUSY;
16947     }
16948   }
16949 #else
16950   /* Use the built-in recursive mutexes if they are available.
16951   */
16952   if( pthread_mutex_trylock(&p->mutex)==0 ){
16953 #if SQLITE_MUTEX_NREF
16954     p->owner = pthread_self();
16955     p->nRef++;
16956 #endif
16957     rc = SQLITE_OK;
16958   }else{
16959     rc = SQLITE_BUSY;
16960   }
16961 #endif
16962
16963 #ifdef SQLITE_DEBUG
16964   if( rc==SQLITE_OK && p->trace ){
16965     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
16966   }
16967 #endif
16968   return rc;
16969 }
16970
16971 /*
16972 ** The sqlite3_mutex_leave() routine exits a mutex that was
16973 ** previously entered by the same thread.  The behavior
16974 ** is undefined if the mutex is not currently entered or
16975 ** is not currently allocated.  SQLite will never do either.
16976 */
16977 static void pthreadMutexLeave(sqlite3_mutex *p){
16978   assert( pthreadMutexHeld(p) );
16979 #if SQLITE_MUTEX_NREF
16980   p->nRef--;
16981   if( p->nRef==0 ) p->owner = 0;
16982 #endif
16983   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
16984
16985 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
16986   if( p->nRef==0 ){
16987     pthread_mutex_unlock(&p->mutex);
16988   }
16989 #else
16990   pthread_mutex_unlock(&p->mutex);
16991 #endif
16992
16993 #ifdef SQLITE_DEBUG
16994   if( p->trace ){
16995     printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
16996   }
16997 #endif
16998 }
16999
17000 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
17001   static const sqlite3_mutex_methods sMutex = {
17002     pthreadMutexInit,
17003     pthreadMutexEnd,
17004     pthreadMutexAlloc,
17005     pthreadMutexFree,
17006     pthreadMutexEnter,
17007     pthreadMutexTry,
17008     pthreadMutexLeave,
17009 #ifdef SQLITE_DEBUG
17010     pthreadMutexHeld,
17011     pthreadMutexNotheld
17012 #else
17013     0,
17014     0
17015 #endif
17016   };
17017
17018   return &sMutex;
17019 }
17020
17021 #endif /* SQLITE_MUTEX_PTHREAD */
17022
17023 /************** End of mutex_unix.c ******************************************/
17024 /************** Begin file mutex_w32.c ***************************************/
17025 /*
17026 ** 2007 August 14
17027 **
17028 ** The author disclaims copyright to this source code.  In place of
17029 ** a legal notice, here is a blessing:
17030 **
17031 **    May you do good and not evil.
17032 **    May you find forgiveness for yourself and forgive others.
17033 **    May you share freely, never taking more than you give.
17034 **
17035 *************************************************************************
17036 ** This file contains the C functions that implement mutexes for win32
17037 */
17038
17039 /*
17040 ** The code in this file is only used if we are compiling multithreaded
17041 ** on a win32 system.
17042 */
17043 #ifdef SQLITE_MUTEX_W32
17044
17045 /*
17046 ** Each recursive mutex is an instance of the following structure.
17047 */
17048 struct sqlite3_mutex {
17049   CRITICAL_SECTION mutex;    /* Mutex controlling the lock */
17050   int id;                    /* Mutex type */
17051 #ifdef SQLITE_DEBUG
17052   volatile int nRef;         /* Number of enterances */
17053   volatile DWORD owner;      /* Thread holding this mutex */
17054   int trace;                 /* True to trace changes */
17055 #endif
17056 };
17057 #define SQLITE_W32_MUTEX_INITIALIZER { 0 }
17058 #ifdef SQLITE_DEBUG
17059 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, 0L, (DWORD)0, 0 }
17060 #else
17061 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
17062 #endif
17063
17064 /*
17065 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
17066 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
17067 **
17068 ** Here is an interesting observation:  Win95, Win98, and WinME lack
17069 ** the LockFileEx() API.  But we can still statically link against that
17070 ** API as long as we don't call it win running Win95/98/ME.  A call to
17071 ** this routine is used to determine if the host is Win95/98/ME or
17072 ** WinNT/2K/XP so that we will know whether or not we can safely call
17073 ** the LockFileEx() API.
17074 **
17075 ** mutexIsNT() is only used for the TryEnterCriticalSection() API call,
17076 ** which is only available if your application was compiled with 
17077 ** _WIN32_WINNT defined to a value >= 0x0400.  Currently, the only
17078 ** call to TryEnterCriticalSection() is #ifdef'ed out, so #ifdef 
17079 ** this out as well.
17080 */
17081 #if 0
17082 #if SQLITE_OS_WINCE
17083 # define mutexIsNT()  (1)
17084 #else
17085   static int mutexIsNT(void){
17086     static int osType = 0;
17087     if( osType==0 ){
17088       OSVERSIONINFO sInfo;
17089       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
17090       GetVersionEx(&sInfo);
17091       osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
17092     }
17093     return osType==2;
17094   }
17095 #endif /* SQLITE_OS_WINCE */
17096 #endif
17097
17098 #ifdef SQLITE_DEBUG
17099 /*
17100 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
17101 ** intended for use only inside assert() statements.
17102 */
17103 static int winMutexHeld(sqlite3_mutex *p){
17104   return p->nRef!=0 && p->owner==GetCurrentThreadId();
17105 }
17106 static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
17107   return p->nRef==0 || p->owner!=tid;
17108 }
17109 static int winMutexNotheld(sqlite3_mutex *p){
17110   DWORD tid = GetCurrentThreadId(); 
17111   return winMutexNotheld2(p, tid);
17112 }
17113 #endif
17114
17115
17116 /*
17117 ** Initialize and deinitialize the mutex subsystem.
17118 */
17119 static sqlite3_mutex winMutex_staticMutexes[6] = {
17120   SQLITE3_MUTEX_INITIALIZER,
17121   SQLITE3_MUTEX_INITIALIZER,
17122   SQLITE3_MUTEX_INITIALIZER,
17123   SQLITE3_MUTEX_INITIALIZER,
17124   SQLITE3_MUTEX_INITIALIZER,
17125   SQLITE3_MUTEX_INITIALIZER
17126 };
17127 static int winMutex_isInit = 0;
17128 /* As winMutexInit() and winMutexEnd() are called as part
17129 ** of the sqlite3_initialize and sqlite3_shutdown()
17130 ** processing, the "interlocked" magic is probably not
17131 ** strictly necessary.
17132 */
17133 static long winMutex_lock = 0;
17134
17135 static int winMutexInit(void){ 
17136   /* The first to increment to 1 does actual initialization */
17137   if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
17138     int i;
17139     for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
17140       InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
17141     }
17142     winMutex_isInit = 1;
17143   }else{
17144     /* Someone else is in the process of initing the static mutexes */
17145     while( !winMutex_isInit ){
17146       Sleep(1);
17147     }
17148   }
17149   return SQLITE_OK; 
17150 }
17151
17152 static int winMutexEnd(void){ 
17153   /* The first to decrement to 0 does actual shutdown 
17154   ** (which should be the last to shutdown.) */
17155   if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
17156     if( winMutex_isInit==1 ){
17157       int i;
17158       for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
17159         DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
17160       }
17161       winMutex_isInit = 0;
17162     }
17163   }
17164   return SQLITE_OK; 
17165 }
17166
17167 /*
17168 ** The sqlite3_mutex_alloc() routine allocates a new
17169 ** mutex and returns a pointer to it.  If it returns NULL
17170 ** that means that a mutex could not be allocated.  SQLite
17171 ** will unwind its stack and return an error.  The argument
17172 ** to sqlite3_mutex_alloc() is one of these integer constants:
17173 **
17174 ** <ul>
17175 ** <li>  SQLITE_MUTEX_FAST
17176 ** <li>  SQLITE_MUTEX_RECURSIVE
17177 ** <li>  SQLITE_MUTEX_STATIC_MASTER
17178 ** <li>  SQLITE_MUTEX_STATIC_MEM
17179 ** <li>  SQLITE_MUTEX_STATIC_MEM2
17180 ** <li>  SQLITE_MUTEX_STATIC_PRNG
17181 ** <li>  SQLITE_MUTEX_STATIC_LRU
17182 ** <li>  SQLITE_MUTEX_STATIC_LRU2
17183 ** </ul>
17184 **
17185 ** The first two constants cause sqlite3_mutex_alloc() to create
17186 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
17187 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
17188 ** The mutex implementation does not need to make a distinction
17189 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
17190 ** not want to.  But SQLite will only request a recursive mutex in
17191 ** cases where it really needs one.  If a faster non-recursive mutex
17192 ** implementation is available on the host platform, the mutex subsystem
17193 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
17194 **
17195 ** The other allowed parameters to sqlite3_mutex_alloc() each return
17196 ** a pointer to a static preexisting mutex.  Six static mutexes are
17197 ** used by the current version of SQLite.  Future versions of SQLite
17198 ** may add additional static mutexes.  Static mutexes are for internal
17199 ** use by SQLite only.  Applications that use SQLite mutexes should
17200 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
17201 ** SQLITE_MUTEX_RECURSIVE.
17202 **
17203 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
17204 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
17205 ** returns a different mutex on every call.  But for the static 
17206 ** mutex types, the same mutex is returned on every call that has
17207 ** the same type number.
17208 */
17209 static sqlite3_mutex *winMutexAlloc(int iType){
17210   sqlite3_mutex *p;
17211
17212   switch( iType ){
17213     case SQLITE_MUTEX_FAST:
17214     case SQLITE_MUTEX_RECURSIVE: {
17215       p = sqlite3MallocZero( sizeof(*p) );
17216       if( p ){  
17217 #ifdef SQLITE_DEBUG
17218         p->id = iType;
17219 #endif
17220         InitializeCriticalSection(&p->mutex);
17221       }
17222       break;
17223     }
17224     default: {
17225       assert( winMutex_isInit==1 );
17226       assert( iType-2 >= 0 );
17227       assert( iType-2 < ArraySize(winMutex_staticMutexes) );
17228       p = &winMutex_staticMutexes[iType-2];
17229 #ifdef SQLITE_DEBUG
17230       p->id = iType;
17231 #endif
17232       break;
17233     }
17234   }
17235   return p;
17236 }
17237
17238
17239 /*
17240 ** This routine deallocates a previously
17241 ** allocated mutex.  SQLite is careful to deallocate every
17242 ** mutex that it allocates.
17243 */
17244 static void winMutexFree(sqlite3_mutex *p){
17245   assert( p );
17246   assert( p->nRef==0 && p->owner==0 );
17247   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
17248   DeleteCriticalSection(&p->mutex);
17249   sqlite3_free(p);
17250 }
17251
17252 /*
17253 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
17254 ** to enter a mutex.  If another thread is already within the mutex,
17255 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
17256 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
17257 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
17258 ** be entered multiple times by the same thread.  In such cases the,
17259 ** mutex must be exited an equal number of times before another thread
17260 ** can enter.  If the same thread tries to enter any other kind of mutex
17261 ** more than once, the behavior is undefined.
17262 */
17263 static void winMutexEnter(sqlite3_mutex *p){
17264 #ifdef SQLITE_DEBUG
17265   DWORD tid = GetCurrentThreadId(); 
17266   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
17267 #endif
17268   EnterCriticalSection(&p->mutex);
17269 #ifdef SQLITE_DEBUG
17270   assert( p->nRef>0 || p->owner==0 );
17271   p->owner = tid; 
17272   p->nRef++;
17273   if( p->trace ){
17274     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
17275   }
17276 #endif
17277 }
17278 static int winMutexTry(sqlite3_mutex *p){
17279 #ifndef NDEBUG
17280   DWORD tid = GetCurrentThreadId(); 
17281 #endif
17282   int rc = SQLITE_BUSY;
17283   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
17284   /*
17285   ** The sqlite3_mutex_try() routine is very rarely used, and when it
17286   ** is used it is merely an optimization.  So it is OK for it to always
17287   ** fail.  
17288   **
17289   ** The TryEnterCriticalSection() interface is only available on WinNT.
17290   ** And some windows compilers complain if you try to use it without
17291   ** first doing some #defines that prevent SQLite from building on Win98.
17292   ** For that reason, we will omit this optimization for now.  See
17293   ** ticket #2685.
17294   */
17295 #if 0
17296   if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){
17297     p->owner = tid;
17298     p->nRef++;
17299     rc = SQLITE_OK;
17300   }
17301 #else
17302   UNUSED_PARAMETER(p);
17303 #endif
17304 #ifdef SQLITE_DEBUG
17305   if( rc==SQLITE_OK && p->trace ){
17306     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
17307   }
17308 #endif
17309   return rc;
17310 }
17311
17312 /*
17313 ** The sqlite3_mutex_leave() routine exits a mutex that was
17314 ** previously entered by the same thread.  The behavior
17315 ** is undefined if the mutex is not currently entered or
17316 ** is not currently allocated.  SQLite will never do either.
17317 */
17318 static void winMutexLeave(sqlite3_mutex *p){
17319 #ifndef NDEBUG
17320   DWORD tid = GetCurrentThreadId();
17321   assert( p->nRef>0 );
17322   assert( p->owner==tid );
17323   p->nRef--;
17324   if( p->nRef==0 ) p->owner = 0;
17325   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
17326 #endif
17327   LeaveCriticalSection(&p->mutex);
17328 #ifdef SQLITE_DEBUG
17329   if( p->trace ){
17330     printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
17331   }
17332 #endif
17333 }
17334
17335 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
17336   static const sqlite3_mutex_methods sMutex = {
17337     winMutexInit,
17338     winMutexEnd,
17339     winMutexAlloc,
17340     winMutexFree,
17341     winMutexEnter,
17342     winMutexTry,
17343     winMutexLeave,
17344 #ifdef SQLITE_DEBUG
17345     winMutexHeld,
17346     winMutexNotheld
17347 #else
17348     0,
17349     0
17350 #endif
17351   };
17352
17353   return &sMutex;
17354 }
17355 #endif /* SQLITE_MUTEX_W32 */
17356
17357 /************** End of mutex_w32.c *******************************************/
17358 /************** Begin file malloc.c ******************************************/
17359 /*
17360 ** 2001 September 15
17361 **
17362 ** The author disclaims copyright to this source code.  In place of
17363 ** a legal notice, here is a blessing:
17364 **
17365 **    May you do good and not evil.
17366 **    May you find forgiveness for yourself and forgive others.
17367 **    May you share freely, never taking more than you give.
17368 **
17369 *************************************************************************
17370 **
17371 ** Memory allocation functions used throughout sqlite.
17372 */
17373
17374 /*
17375 ** Attempt to release up to n bytes of non-essential memory currently
17376 ** held by SQLite. An example of non-essential memory is memory used to
17377 ** cache database pages that are not currently in use.
17378 */
17379 SQLITE_API int sqlite3_release_memory(int n){
17380 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
17381   return sqlite3PcacheReleaseMemory(n);
17382 #else
17383   /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
17384   ** is a no-op returning zero if SQLite is not compiled with
17385   ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
17386   UNUSED_PARAMETER(n);
17387   return 0;
17388 #endif
17389 }
17390
17391 /*
17392 ** An instance of the following object records the location of
17393 ** each unused scratch buffer.
17394 */
17395 typedef struct ScratchFreeslot {
17396   struct ScratchFreeslot *pNext;   /* Next unused scratch buffer */
17397 } ScratchFreeslot;
17398
17399 /*
17400 ** State information local to the memory allocation subsystem.
17401 */
17402 static SQLITE_WSD struct Mem0Global {
17403   sqlite3_mutex *mutex;         /* Mutex to serialize access */
17404
17405   /*
17406   ** The alarm callback and its arguments.  The mem0.mutex lock will
17407   ** be held while the callback is running.  Recursive calls into
17408   ** the memory subsystem are allowed, but no new callbacks will be
17409   ** issued.
17410   */
17411   sqlite3_int64 alarmThreshold;
17412   void (*alarmCallback)(void*, sqlite3_int64,int);
17413   void *alarmArg;
17414
17415   /*
17416   ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
17417   ** (so that a range test can be used to determine if an allocation
17418   ** being freed came from pScratch) and a pointer to the list of
17419   ** unused scratch allocations.
17420   */
17421   void *pScratchEnd;
17422   ScratchFreeslot *pScratchFree;
17423   u32 nScratchFree;
17424
17425   /*
17426   ** True if heap is nearly "full" where "full" is defined by the
17427   ** sqlite3_soft_heap_limit() setting.
17428   */
17429   int nearlyFull;
17430 } mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
17431
17432 #define mem0 GLOBAL(struct Mem0Global, mem0)
17433
17434 /*
17435 ** This routine runs when the memory allocator sees that the
17436 ** total memory allocation is about to exceed the soft heap
17437 ** limit.
17438 */
17439 static void softHeapLimitEnforcer(
17440   void *NotUsed, 
17441   sqlite3_int64 NotUsed2,
17442   int allocSize
17443 ){
17444   UNUSED_PARAMETER2(NotUsed, NotUsed2);
17445   sqlite3_release_memory(allocSize);
17446 }
17447
17448 /*
17449 ** Change the alarm callback
17450 */
17451 static int sqlite3MemoryAlarm(
17452   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
17453   void *pArg,
17454   sqlite3_int64 iThreshold
17455 ){
17456   int nUsed;
17457   sqlite3_mutex_enter(mem0.mutex);
17458   mem0.alarmCallback = xCallback;
17459   mem0.alarmArg = pArg;
17460   mem0.alarmThreshold = iThreshold;
17461   nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
17462   mem0.nearlyFull = (iThreshold>0 && iThreshold<=nUsed);
17463   sqlite3_mutex_leave(mem0.mutex);
17464   return SQLITE_OK;
17465 }
17466
17467 #ifndef SQLITE_OMIT_DEPRECATED
17468 /*
17469 ** Deprecated external interface.  Internal/core SQLite code
17470 ** should call sqlite3MemoryAlarm.
17471 */
17472 SQLITE_API int sqlite3_memory_alarm(
17473   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
17474   void *pArg,
17475   sqlite3_int64 iThreshold
17476 ){
17477   return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
17478 }
17479 #endif
17480
17481 /*
17482 ** Set the soft heap-size limit for the library. Passing a zero or 
17483 ** negative value indicates no limit.
17484 */
17485 SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
17486   sqlite3_int64 priorLimit;
17487   sqlite3_int64 excess;
17488 #ifndef SQLITE_OMIT_AUTOINIT
17489   sqlite3_initialize();
17490 #endif
17491   sqlite3_mutex_enter(mem0.mutex);
17492   priorLimit = mem0.alarmThreshold;
17493   sqlite3_mutex_leave(mem0.mutex);
17494   if( n<0 ) return priorLimit;
17495   if( n>0 ){
17496     sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, n);
17497   }else{
17498     sqlite3MemoryAlarm(0, 0, 0);
17499   }
17500   excess = sqlite3_memory_used() - n;
17501   if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
17502   return priorLimit;
17503 }
17504 SQLITE_API void sqlite3_soft_heap_limit(int n){
17505   if( n<0 ) n = 0;
17506   sqlite3_soft_heap_limit64(n);
17507 }
17508
17509 /*
17510 ** Initialize the memory allocation subsystem.
17511 */
17512 SQLITE_PRIVATE int sqlite3MallocInit(void){
17513   if( sqlite3GlobalConfig.m.xMalloc==0 ){
17514     sqlite3MemSetDefault();
17515   }
17516   memset(&mem0, 0, sizeof(mem0));
17517   if( sqlite3GlobalConfig.bCoreMutex ){
17518     mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
17519   }
17520   if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
17521       && sqlite3GlobalConfig.nScratch>0 ){
17522     int i, n, sz;
17523     ScratchFreeslot *pSlot;
17524     sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
17525     sqlite3GlobalConfig.szScratch = sz;
17526     pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
17527     n = sqlite3GlobalConfig.nScratch;
17528     mem0.pScratchFree = pSlot;
17529     mem0.nScratchFree = n;
17530     for(i=0; i<n-1; i++){
17531       pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
17532       pSlot = pSlot->pNext;
17533     }
17534     pSlot->pNext = 0;
17535     mem0.pScratchEnd = (void*)&pSlot[1];
17536   }else{
17537     mem0.pScratchEnd = 0;
17538     sqlite3GlobalConfig.pScratch = 0;
17539     sqlite3GlobalConfig.szScratch = 0;
17540     sqlite3GlobalConfig.nScratch = 0;
17541   }
17542   if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
17543       || sqlite3GlobalConfig.nPage<1 ){
17544     sqlite3GlobalConfig.pPage = 0;
17545     sqlite3GlobalConfig.szPage = 0;
17546     sqlite3GlobalConfig.nPage = 0;
17547   }
17548   return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
17549 }
17550
17551 /*
17552 ** Return true if the heap is currently under memory pressure - in other
17553 ** words if the amount of heap used is close to the limit set by
17554 ** sqlite3_soft_heap_limit().
17555 */
17556 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
17557   return mem0.nearlyFull;
17558 }
17559
17560 /*
17561 ** Deinitialize the memory allocation subsystem.
17562 */
17563 SQLITE_PRIVATE void sqlite3MallocEnd(void){
17564   if( sqlite3GlobalConfig.m.xShutdown ){
17565     sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
17566   }
17567   memset(&mem0, 0, sizeof(mem0));
17568 }
17569
17570 /*
17571 ** Return the amount of memory currently checked out.
17572 */
17573 SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
17574   int n, mx;
17575   sqlite3_int64 res;
17576   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
17577   res = (sqlite3_int64)n;  /* Work around bug in Borland C. Ticket #3216 */
17578   return res;
17579 }
17580
17581 /*
17582 ** Return the maximum amount of memory that has ever been
17583 ** checked out since either the beginning of this process
17584 ** or since the most recent reset.
17585 */
17586 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
17587   int n, mx;
17588   sqlite3_int64 res;
17589   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
17590   res = (sqlite3_int64)mx;  /* Work around bug in Borland C. Ticket #3216 */
17591   return res;
17592 }
17593
17594 /*
17595 ** Trigger the alarm 
17596 */
17597 static void sqlite3MallocAlarm(int nByte){
17598   void (*xCallback)(void*,sqlite3_int64,int);
17599   sqlite3_int64 nowUsed;
17600   void *pArg;
17601   if( mem0.alarmCallback==0 ) return;
17602   xCallback = mem0.alarmCallback;
17603   nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
17604   pArg = mem0.alarmArg;
17605   mem0.alarmCallback = 0;
17606   sqlite3_mutex_leave(mem0.mutex);
17607   xCallback(pArg, nowUsed, nByte);
17608   sqlite3_mutex_enter(mem0.mutex);
17609   mem0.alarmCallback = xCallback;
17610   mem0.alarmArg = pArg;
17611 }
17612
17613 /*
17614 ** Do a memory allocation with statistics and alarms.  Assume the
17615 ** lock is already held.
17616 */
17617 static int mallocWithAlarm(int n, void **pp){
17618   int nFull;
17619   void *p;
17620   assert( sqlite3_mutex_held(mem0.mutex) );
17621   nFull = sqlite3GlobalConfig.m.xRoundup(n);
17622   sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
17623   if( mem0.alarmCallback!=0 ){
17624     int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
17625     if( nUsed+nFull >= mem0.alarmThreshold ){
17626       mem0.nearlyFull = 1;
17627       sqlite3MallocAlarm(nFull);
17628     }else{
17629       mem0.nearlyFull = 0;
17630     }
17631   }
17632   p = sqlite3GlobalConfig.m.xMalloc(nFull);
17633 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
17634   if( p==0 && mem0.alarmCallback ){
17635     sqlite3MallocAlarm(nFull);
17636     p = sqlite3GlobalConfig.m.xMalloc(nFull);
17637   }
17638 #endif
17639   if( p ){
17640     nFull = sqlite3MallocSize(p);
17641     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
17642     sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, 1);
17643   }
17644   *pp = p;
17645   return nFull;
17646 }
17647
17648 /*
17649 ** Allocate memory.  This routine is like sqlite3_malloc() except that it
17650 ** assumes the memory subsystem has already been initialized.
17651 */
17652 SQLITE_PRIVATE void *sqlite3Malloc(int n){
17653   void *p;
17654   if( n<=0               /* IMP: R-65312-04917 */ 
17655    || n>=0x7fffff00
17656   ){
17657     /* A memory allocation of a number of bytes which is near the maximum
17658     ** signed integer value might cause an integer overflow inside of the
17659     ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving
17660     ** 255 bytes of overhead.  SQLite itself will never use anything near
17661     ** this amount.  The only way to reach the limit is with sqlite3_malloc() */
17662     p = 0;
17663   }else if( sqlite3GlobalConfig.bMemstat ){
17664     sqlite3_mutex_enter(mem0.mutex);
17665     mallocWithAlarm(n, &p);
17666     sqlite3_mutex_leave(mem0.mutex);
17667   }else{
17668     p = sqlite3GlobalConfig.m.xMalloc(n);
17669   }
17670   assert( EIGHT_BYTE_ALIGNMENT(p) );  /* IMP: R-04675-44850 */
17671   return p;
17672 }
17673
17674 /*
17675 ** This version of the memory allocation is for use by the application.
17676 ** First make sure the memory subsystem is initialized, then do the
17677 ** allocation.
17678 */
17679 SQLITE_API void *sqlite3_malloc(int n){
17680 #ifndef SQLITE_OMIT_AUTOINIT
17681   if( sqlite3_initialize() ) return 0;
17682 #endif
17683   return sqlite3Malloc(n);
17684 }
17685
17686 /*
17687 ** Each thread may only have a single outstanding allocation from
17688 ** xScratchMalloc().  We verify this constraint in the single-threaded
17689 ** case by setting scratchAllocOut to 1 when an allocation
17690 ** is outstanding clearing it when the allocation is freed.
17691 */
17692 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
17693 static int scratchAllocOut = 0;
17694 #endif
17695
17696
17697 /*
17698 ** Allocate memory that is to be used and released right away.
17699 ** This routine is similar to alloca() in that it is not intended
17700 ** for situations where the memory might be held long-term.  This
17701 ** routine is intended to get memory to old large transient data
17702 ** structures that would not normally fit on the stack of an
17703 ** embedded processor.
17704 */
17705 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
17706   void *p;
17707   assert( n>0 );
17708
17709   sqlite3_mutex_enter(mem0.mutex);
17710   if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
17711     p = mem0.pScratchFree;
17712     mem0.pScratchFree = mem0.pScratchFree->pNext;
17713     mem0.nScratchFree--;
17714     sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
17715     sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
17716     sqlite3_mutex_leave(mem0.mutex);
17717   }else{
17718     if( sqlite3GlobalConfig.bMemstat ){
17719       sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
17720       n = mallocWithAlarm(n, &p);
17721       if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
17722       sqlite3_mutex_leave(mem0.mutex);
17723     }else{
17724       sqlite3_mutex_leave(mem0.mutex);
17725       p = sqlite3GlobalConfig.m.xMalloc(n);
17726     }
17727     sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
17728   }
17729   assert( sqlite3_mutex_notheld(mem0.mutex) );
17730
17731
17732 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
17733   /* Verify that no more than two scratch allocations per thread
17734   ** are outstanding at one time.  (This is only checked in the
17735   ** single-threaded case since checking in the multi-threaded case
17736   ** would be much more complicated.) */
17737   assert( scratchAllocOut<=1 );
17738   if( p ) scratchAllocOut++;
17739 #endif
17740
17741   return p;
17742 }
17743 SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
17744   if( p ){
17745
17746 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
17747     /* Verify that no more than two scratch allocation per thread
17748     ** is outstanding at one time.  (This is only checked in the
17749     ** single-threaded case since checking in the multi-threaded case
17750     ** would be much more complicated.) */
17751     assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
17752     scratchAllocOut--;
17753 #endif
17754
17755     if( p>=sqlite3GlobalConfig.pScratch && p<mem0.pScratchEnd ){
17756       /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
17757       ScratchFreeslot *pSlot;
17758       pSlot = (ScratchFreeslot*)p;
17759       sqlite3_mutex_enter(mem0.mutex);
17760       pSlot->pNext = mem0.pScratchFree;
17761       mem0.pScratchFree = pSlot;
17762       mem0.nScratchFree++;
17763       assert( mem0.nScratchFree<=sqlite3GlobalConfig.nScratch );
17764       sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
17765       sqlite3_mutex_leave(mem0.mutex);
17766     }else{
17767       /* Release memory back to the heap */
17768       assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
17769       assert( sqlite3MemdebugNoType(p, ~MEMTYPE_SCRATCH) );
17770       sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
17771       if( sqlite3GlobalConfig.bMemstat ){
17772         int iSize = sqlite3MallocSize(p);
17773         sqlite3_mutex_enter(mem0.mutex);
17774         sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
17775         sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
17776         sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
17777         sqlite3GlobalConfig.m.xFree(p);
17778         sqlite3_mutex_leave(mem0.mutex);
17779       }else{
17780         sqlite3GlobalConfig.m.xFree(p);
17781       }
17782     }
17783   }
17784 }
17785
17786 /*
17787 ** TRUE if p is a lookaside memory allocation from db
17788 */
17789 #ifndef SQLITE_OMIT_LOOKASIDE
17790 static int isLookaside(sqlite3 *db, void *p){
17791   return p && p>=db->lookaside.pStart && p<db->lookaside.pEnd;
17792 }
17793 #else
17794 #define isLookaside(A,B) 0
17795 #endif
17796
17797 /*
17798 ** Return the size of a memory allocation previously obtained from
17799 ** sqlite3Malloc() or sqlite3_malloc().
17800 */
17801 SQLITE_PRIVATE int sqlite3MallocSize(void *p){
17802   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
17803   assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
17804   return sqlite3GlobalConfig.m.xSize(p);
17805 }
17806 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
17807   assert( db==0 || sqlite3_mutex_held(db->mutex) );
17808   if( db && isLookaside(db, p) ){
17809     return db->lookaside.sz;
17810   }else{
17811     assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
17812     assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
17813     assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
17814     return sqlite3GlobalConfig.m.xSize(p);
17815   }
17816 }
17817
17818 /*
17819 ** Free memory previously obtained from sqlite3Malloc().
17820 */
17821 SQLITE_API void sqlite3_free(void *p){
17822   if( p==0 ) return;  /* IMP: R-49053-54554 */
17823   assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
17824   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
17825   if( sqlite3GlobalConfig.bMemstat ){
17826     sqlite3_mutex_enter(mem0.mutex);
17827     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
17828     sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
17829     sqlite3GlobalConfig.m.xFree(p);
17830     sqlite3_mutex_leave(mem0.mutex);
17831   }else{
17832     sqlite3GlobalConfig.m.xFree(p);
17833   }
17834 }
17835
17836 /*
17837 ** Free memory that might be associated with a particular database
17838 ** connection.
17839 */
17840 SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
17841   assert( db==0 || sqlite3_mutex_held(db->mutex) );
17842   if( db ){
17843     if( db->pnBytesFreed ){
17844       *db->pnBytesFreed += sqlite3DbMallocSize(db, p);
17845       return;
17846     }
17847     if( isLookaside(db, p) ){
17848       LookasideSlot *pBuf = (LookasideSlot*)p;
17849       pBuf->pNext = db->lookaside.pFree;
17850       db->lookaside.pFree = pBuf;
17851       db->lookaside.nOut--;
17852       return;
17853     }
17854   }
17855   assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
17856   assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
17857   assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
17858   sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
17859   sqlite3_free(p);
17860 }
17861
17862 /*
17863 ** Change the size of an existing memory allocation
17864 */
17865 SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, int nBytes){
17866   int nOld, nNew;
17867   void *pNew;
17868   if( pOld==0 ){
17869     return sqlite3Malloc(nBytes); /* IMP: R-28354-25769 */
17870   }
17871   if( nBytes<=0 ){
17872     sqlite3_free(pOld); /* IMP: R-31593-10574 */
17873     return 0;
17874   }
17875   if( nBytes>=0x7fffff00 ){
17876     /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
17877     return 0;
17878   }
17879   nOld = sqlite3MallocSize(pOld);
17880   /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
17881   ** argument to xRealloc is always a value returned by a prior call to
17882   ** xRoundup. */
17883   nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);
17884   if( nOld==nNew ){
17885     pNew = pOld;
17886   }else if( sqlite3GlobalConfig.bMemstat ){
17887     sqlite3_mutex_enter(mem0.mutex);
17888     sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes);
17889     if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED)+nNew-nOld >= 
17890           mem0.alarmThreshold ){
17891       sqlite3MallocAlarm(nNew-nOld);
17892     }
17893     assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
17894     assert( sqlite3MemdebugNoType(pOld, ~MEMTYPE_HEAP) );
17895     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
17896     if( pNew==0 && mem0.alarmCallback ){
17897       sqlite3MallocAlarm(nBytes);
17898       pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
17899     }
17900     if( pNew ){
17901       nNew = sqlite3MallocSize(pNew);
17902       sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
17903     }
17904     sqlite3_mutex_leave(mem0.mutex);
17905   }else{
17906     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
17907   }
17908   assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-04675-44850 */
17909   return pNew;
17910 }
17911
17912 /*
17913 ** The public interface to sqlite3Realloc.  Make sure that the memory
17914 ** subsystem is initialized prior to invoking sqliteRealloc.
17915 */
17916 SQLITE_API void *sqlite3_realloc(void *pOld, int n){
17917 #ifndef SQLITE_OMIT_AUTOINIT
17918   if( sqlite3_initialize() ) return 0;
17919 #endif
17920   return sqlite3Realloc(pOld, n);
17921 }
17922
17923
17924 /*
17925 ** Allocate and zero memory.
17926 */ 
17927 SQLITE_PRIVATE void *sqlite3MallocZero(int n){
17928   void *p = sqlite3Malloc(n);
17929   if( p ){
17930     memset(p, 0, n);
17931   }
17932   return p;
17933 }
17934
17935 /*
17936 ** Allocate and zero memory.  If the allocation fails, make
17937 ** the mallocFailed flag in the connection pointer.
17938 */
17939 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, int n){
17940   void *p = sqlite3DbMallocRaw(db, n);
17941   if( p ){
17942     memset(p, 0, n);
17943   }
17944   return p;
17945 }
17946
17947 /*
17948 ** Allocate and zero memory.  If the allocation fails, make
17949 ** the mallocFailed flag in the connection pointer.
17950 **
17951 ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
17952 ** failure on the same database connection) then always return 0.
17953 ** Hence for a particular database connection, once malloc starts
17954 ** failing, it fails consistently until mallocFailed is reset.
17955 ** This is an important assumption.  There are many places in the
17956 ** code that do things like this:
17957 **
17958 **         int *a = (int*)sqlite3DbMallocRaw(db, 100);
17959 **         int *b = (int*)sqlite3DbMallocRaw(db, 200);
17960 **         if( b ) a[10] = 9;
17961 **
17962 ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
17963 ** that all prior mallocs (ex: "a") worked too.
17964 */
17965 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, int n){
17966   void *p;
17967   assert( db==0 || sqlite3_mutex_held(db->mutex) );
17968   assert( db==0 || db->pnBytesFreed==0 );
17969 #ifndef SQLITE_OMIT_LOOKASIDE
17970   if( db ){
17971     LookasideSlot *pBuf;
17972     if( db->mallocFailed ){
17973       return 0;
17974     }
17975     if( db->lookaside.bEnabled && n<=db->lookaside.sz
17976          && (pBuf = db->lookaside.pFree)!=0 ){
17977       db->lookaside.pFree = pBuf->pNext;
17978       db->lookaside.nOut++;
17979       if( db->lookaside.nOut>db->lookaside.mxOut ){
17980         db->lookaside.mxOut = db->lookaside.nOut;
17981       }
17982       return (void*)pBuf;
17983     }
17984   }
17985 #else
17986   if( db && db->mallocFailed ){
17987     return 0;
17988   }
17989 #endif
17990   p = sqlite3Malloc(n);
17991   if( !p && db ){
17992     db->mallocFailed = 1;
17993   }
17994   sqlite3MemdebugSetType(p, MEMTYPE_DB |
17995          ((db && db->lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
17996   return p;
17997 }
17998
17999 /*
18000 ** Resize the block of memory pointed to by p to n bytes. If the
18001 ** resize fails, set the mallocFailed flag in the connection object.
18002 */
18003 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
18004   void *pNew = 0;
18005   assert( db!=0 );
18006   assert( sqlite3_mutex_held(db->mutex) );
18007   if( db->mallocFailed==0 ){
18008     if( p==0 ){
18009       return sqlite3DbMallocRaw(db, n);
18010     }
18011     if( isLookaside(db, p) ){
18012       if( n<=db->lookaside.sz ){
18013         return p;
18014       }
18015       pNew = sqlite3DbMallocRaw(db, n);
18016       if( pNew ){
18017         memcpy(pNew, p, db->lookaside.sz);
18018         sqlite3DbFree(db, p);
18019       }
18020     }else{
18021       assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
18022       assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
18023       sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
18024       pNew = sqlite3_realloc(p, n);
18025       if( !pNew ){
18026         sqlite3MemdebugSetType(p, MEMTYPE_DB|MEMTYPE_HEAP);
18027         db->mallocFailed = 1;
18028       }
18029       sqlite3MemdebugSetType(pNew, MEMTYPE_DB | 
18030             (db->lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
18031     }
18032   }
18033   return pNew;
18034 }
18035
18036 /*
18037 ** Attempt to reallocate p.  If the reallocation fails, then free p
18038 ** and set the mallocFailed flag in the database connection.
18039 */
18040 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
18041   void *pNew;
18042   pNew = sqlite3DbRealloc(db, p, n);
18043   if( !pNew ){
18044     sqlite3DbFree(db, p);
18045   }
18046   return pNew;
18047 }
18048
18049 /*
18050 ** Make a copy of a string in memory obtained from sqliteMalloc(). These 
18051 ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
18052 ** is because when memory debugging is turned on, these two functions are 
18053 ** called via macros that record the current file and line number in the
18054 ** ThreadData structure.
18055 */
18056 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
18057   char *zNew;
18058   size_t n;
18059   if( z==0 ){
18060     return 0;
18061   }
18062   n = sqlite3Strlen30(z) + 1;
18063   assert( (n&0x7fffffff)==n );
18064   zNew = sqlite3DbMallocRaw(db, (int)n);
18065   if( zNew ){
18066     memcpy(zNew, z, n);
18067   }
18068   return zNew;
18069 }
18070 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
18071   char *zNew;
18072   if( z==0 ){
18073     return 0;
18074   }
18075   assert( (n&0x7fffffff)==n );
18076   zNew = sqlite3DbMallocRaw(db, n+1);
18077   if( zNew ){
18078     memcpy(zNew, z, n);
18079     zNew[n] = 0;
18080   }
18081   return zNew;
18082 }
18083
18084 /*
18085 ** Create a string from the zFromat argument and the va_list that follows.
18086 ** Store the string in memory obtained from sqliteMalloc() and make *pz
18087 ** point to that string.
18088 */
18089 SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
18090   va_list ap;
18091   char *z;
18092
18093   va_start(ap, zFormat);
18094   z = sqlite3VMPrintf(db, zFormat, ap);
18095   va_end(ap);
18096   sqlite3DbFree(db, *pz);
18097   *pz = z;
18098 }
18099
18100
18101 /*
18102 ** This function must be called before exiting any API function (i.e. 
18103 ** returning control to the user) that has called sqlite3_malloc or
18104 ** sqlite3_realloc.
18105 **
18106 ** The returned value is normally a copy of the second argument to this
18107 ** function. However, if a malloc() failure has occurred since the previous
18108 ** invocation SQLITE_NOMEM is returned instead. 
18109 **
18110 ** If the first argument, db, is not NULL and a malloc() error has occurred,
18111 ** then the connection error-code (the value returned by sqlite3_errcode())
18112 ** is set to SQLITE_NOMEM.
18113 */
18114 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
18115   /* If the db handle is not NULL, then we must hold the connection handle
18116   ** mutex here. Otherwise the read (and possible write) of db->mallocFailed 
18117   ** is unsafe, as is the call to sqlite3Error().
18118   */
18119   assert( !db || sqlite3_mutex_held(db->mutex) );
18120   if( db && (db->mallocFailed || rc==SQLITE_IOERR_NOMEM) ){
18121     sqlite3Error(db, SQLITE_NOMEM, 0);
18122     db->mallocFailed = 0;
18123     rc = SQLITE_NOMEM;
18124   }
18125   return rc & (db ? db->errMask : 0xff);
18126 }
18127
18128 /************** End of malloc.c **********************************************/
18129 /************** Begin file printf.c ******************************************/
18130 /*
18131 ** The "printf" code that follows dates from the 1980's.  It is in
18132 ** the public domain.  The original comments are included here for
18133 ** completeness.  They are very out-of-date but might be useful as
18134 ** an historical reference.  Most of the "enhancements" have been backed
18135 ** out so that the functionality is now the same as standard printf().
18136 **
18137 **************************************************************************
18138 **
18139 ** The following modules is an enhanced replacement for the "printf" subroutines
18140 ** found in the standard C library.  The following enhancements are
18141 ** supported:
18142 **
18143 **      +  Additional functions.  The standard set of "printf" functions
18144 **         includes printf, fprintf, sprintf, vprintf, vfprintf, and
18145 **         vsprintf.  This module adds the following:
18146 **
18147 **           *  snprintf -- Works like sprintf, but has an extra argument
18148 **                          which is the size of the buffer written to.
18149 **
18150 **           *  mprintf --  Similar to sprintf.  Writes output to memory
18151 **                          obtained from malloc.
18152 **
18153 **           *  xprintf --  Calls a function to dispose of output.
18154 **
18155 **           *  nprintf --  No output, but returns the number of characters
18156 **                          that would have been output by printf.
18157 **
18158 **           *  A v- version (ex: vsnprintf) of every function is also
18159 **              supplied.
18160 **
18161 **      +  A few extensions to the formatting notation are supported:
18162 **
18163 **           *  The "=" flag (similar to "-") causes the output to be
18164 **              be centered in the appropriately sized field.
18165 **
18166 **           *  The %b field outputs an integer in binary notation.
18167 **
18168 **           *  The %c field now accepts a precision.  The character output
18169 **              is repeated by the number of times the precision specifies.
18170 **
18171 **           *  The %' field works like %c, but takes as its character the
18172 **              next character of the format string, instead of the next
18173 **              argument.  For example,  printf("%.78'-")  prints 78 minus
18174 **              signs, the same as  printf("%.78c",'-').
18175 **
18176 **      +  When compiled using GCC on a SPARC, this version of printf is
18177 **         faster than the library printf for SUN OS 4.1.
18178 **
18179 **      +  All functions are fully reentrant.
18180 **
18181 */
18182
18183 /*
18184 ** Conversion types fall into various categories as defined by the
18185 ** following enumeration.
18186 */
18187 #define etRADIX       1 /* Integer types.  %d, %x, %o, and so forth */
18188 #define etFLOAT       2 /* Floating point.  %f */
18189 #define etEXP         3 /* Exponentional notation. %e and %E */
18190 #define etGENERIC     4 /* Floating or exponential, depending on exponent. %g */
18191 #define etSIZE        5 /* Return number of characters processed so far. %n */
18192 #define etSTRING      6 /* Strings. %s */
18193 #define etDYNSTRING   7 /* Dynamically allocated strings. %z */
18194 #define etPERCENT     8 /* Percent symbol. %% */
18195 #define etCHARX       9 /* Characters. %c */
18196 /* The rest are extensions, not normally found in printf() */
18197 #define etSQLESCAPE  10 /* Strings with '\'' doubled.  %q */
18198 #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
18199                           NULL pointers replaced by SQL NULL.  %Q */
18200 #define etTOKEN      12 /* a pointer to a Token structure */
18201 #define etSRCLIST    13 /* a pointer to a SrcList */
18202 #define etPOINTER    14 /* The %p conversion */
18203 #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
18204 #define etORDINAL    16 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
18205
18206 #define etINVALID     0 /* Any unrecognized conversion type */
18207
18208
18209 /*
18210 ** An "etByte" is an 8-bit unsigned value.
18211 */
18212 typedef unsigned char etByte;
18213
18214 /*
18215 ** Each builtin conversion character (ex: the 'd' in "%d") is described
18216 ** by an instance of the following structure
18217 */
18218 typedef struct et_info {   /* Information about each format field */
18219   char fmttype;            /* The format field code letter */
18220   etByte base;             /* The base for radix conversion */
18221   etByte flags;            /* One or more of FLAG_ constants below */
18222   etByte type;             /* Conversion paradigm */
18223   etByte charset;          /* Offset into aDigits[] of the digits string */
18224   etByte prefix;           /* Offset into aPrefix[] of the prefix string */
18225 } et_info;
18226
18227 /*
18228 ** Allowed values for et_info.flags
18229 */
18230 #define FLAG_SIGNED  1     /* True if the value to convert is signed */
18231 #define FLAG_INTERN  2     /* True if for internal use only */
18232 #define FLAG_STRING  4     /* Allow infinity precision */
18233
18234
18235 /*
18236 ** The following table is searched linearly, so it is good to put the
18237 ** most frequently used conversion types first.
18238 */
18239 static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
18240 static const char aPrefix[] = "-x0\000X0";
18241 static const et_info fmtinfo[] = {
18242   {  'd', 10, 1, etRADIX,      0,  0 },
18243   {  's',  0, 4, etSTRING,     0,  0 },
18244   {  'g',  0, 1, etGENERIC,    30, 0 },
18245   {  'z',  0, 4, etDYNSTRING,  0,  0 },
18246   {  'q',  0, 4, etSQLESCAPE,  0,  0 },
18247   {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
18248   {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
18249   {  'c',  0, 0, etCHARX,      0,  0 },
18250   {  'o',  8, 0, etRADIX,      0,  2 },
18251   {  'u', 10, 0, etRADIX,      0,  0 },
18252   {  'x', 16, 0, etRADIX,      16, 1 },
18253   {  'X', 16, 0, etRADIX,      0,  4 },
18254 #ifndef SQLITE_OMIT_FLOATING_POINT
18255   {  'f',  0, 1, etFLOAT,      0,  0 },
18256   {  'e',  0, 1, etEXP,        30, 0 },
18257   {  'E',  0, 1, etEXP,        14, 0 },
18258   {  'G',  0, 1, etGENERIC,    14, 0 },
18259 #endif
18260   {  'i', 10, 1, etRADIX,      0,  0 },
18261   {  'n',  0, 0, etSIZE,       0,  0 },
18262   {  '%',  0, 0, etPERCENT,    0,  0 },
18263   {  'p', 16, 0, etPOINTER,    0,  1 },
18264
18265 /* All the rest have the FLAG_INTERN bit set and are thus for internal
18266 ** use only */
18267   {  'T',  0, 2, etTOKEN,      0,  0 },
18268   {  'S',  0, 2, etSRCLIST,    0,  0 },
18269   {  'r', 10, 3, etORDINAL,    0,  0 },
18270 };
18271
18272 /*
18273 ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
18274 ** conversions will work.
18275 */
18276 #ifndef SQLITE_OMIT_FLOATING_POINT
18277 /*
18278 ** "*val" is a double such that 0.1 <= *val < 10.0
18279 ** Return the ascii code for the leading digit of *val, then
18280 ** multiply "*val" by 10.0 to renormalize.
18281 **
18282 ** Example:
18283 **     input:     *val = 3.14159
18284 **     output:    *val = 1.4159    function return = '3'
18285 **
18286 ** The counter *cnt is incremented each time.  After counter exceeds
18287 ** 16 (the number of significant digits in a 64-bit float) '0' is
18288 ** always returned.
18289 */
18290 static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
18291   int digit;
18292   LONGDOUBLE_TYPE d;
18293   if( (*cnt)++ >= 16 ) return '0';
18294   digit = (int)*val;
18295   d = digit;
18296   digit += '0';
18297   *val = (*val - d)*10.0;
18298   return (char)digit;
18299 }
18300 #endif /* SQLITE_OMIT_FLOATING_POINT */
18301
18302 /*
18303 ** Append N space characters to the given string buffer.
18304 */
18305 static void appendSpace(StrAccum *pAccum, int N){
18306   static const char zSpaces[] = "                             ";
18307   while( N>=(int)sizeof(zSpaces)-1 ){
18308     sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
18309     N -= sizeof(zSpaces)-1;
18310   }
18311   if( N>0 ){
18312     sqlite3StrAccumAppend(pAccum, zSpaces, N);
18313   }
18314 }
18315
18316 /*
18317 ** On machines with a small stack size, you can redefine the
18318 ** SQLITE_PRINT_BUF_SIZE to be less than 350.
18319 */
18320 #ifndef SQLITE_PRINT_BUF_SIZE
18321 # if defined(SQLITE_SMALL_STACK)
18322 #   define SQLITE_PRINT_BUF_SIZE 50
18323 # else
18324 #   define SQLITE_PRINT_BUF_SIZE 350
18325 # endif
18326 #endif
18327 #define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
18328
18329 /*
18330 ** The root program.  All variations call this core.
18331 **
18332 ** INPUTS:
18333 **   func   This is a pointer to a function taking three arguments
18334 **            1. A pointer to anything.  Same as the "arg" parameter.
18335 **            2. A pointer to the list of characters to be output
18336 **               (Note, this list is NOT null terminated.)
18337 **            3. An integer number of characters to be output.
18338 **               (Note: This number might be zero.)
18339 **
18340 **   arg    This is the pointer to anything which will be passed as the
18341 **          first argument to "func".  Use it for whatever you like.
18342 **
18343 **   fmt    This is the format string, as in the usual print.
18344 **
18345 **   ap     This is a pointer to a list of arguments.  Same as in
18346 **          vfprint.
18347 **
18348 ** OUTPUTS:
18349 **          The return value is the total number of characters sent to
18350 **          the function "func".  Returns -1 on a error.
18351 **
18352 ** Note that the order in which automatic variables are declared below
18353 ** seems to make a big difference in determining how fast this beast
18354 ** will run.
18355 */
18356 SQLITE_PRIVATE void sqlite3VXPrintf(
18357   StrAccum *pAccum,                  /* Accumulate results here */
18358   int useExtended,                   /* Allow extended %-conversions */
18359   const char *fmt,                   /* Format string */
18360   va_list ap                         /* arguments */
18361 ){
18362   int c;                     /* Next character in the format string */
18363   char *bufpt;               /* Pointer to the conversion buffer */
18364   int precision;             /* Precision of the current field */
18365   int length;                /* Length of the field */
18366   int idx;                   /* A general purpose loop counter */
18367   int width;                 /* Width of the current field */
18368   etByte flag_leftjustify;   /* True if "-" flag is present */
18369   etByte flag_plussign;      /* True if "+" flag is present */
18370   etByte flag_blanksign;     /* True if " " flag is present */
18371   etByte flag_alternateform; /* True if "#" flag is present */
18372   etByte flag_altform2;      /* True if "!" flag is present */
18373   etByte flag_zeropad;       /* True if field width constant starts with zero */
18374   etByte flag_long;          /* True if "l" flag is present */
18375   etByte flag_longlong;      /* True if the "ll" flag is present */
18376   etByte done;               /* Loop termination flag */
18377   sqlite_uint64 longvalue;   /* Value for integer types */
18378   LONGDOUBLE_TYPE realvalue; /* Value for real types */
18379   const et_info *infop;      /* Pointer to the appropriate info structure */
18380   char buf[etBUFSIZE];       /* Conversion buffer */
18381   char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
18382   etByte xtype = 0;          /* Conversion paradigm */
18383   char *zExtra;              /* Extra memory used for etTCLESCAPE conversions */
18384 #ifndef SQLITE_OMIT_FLOATING_POINT
18385   int  exp, e2;              /* exponent of real numbers */
18386   double rounder;            /* Used for rounding floating point values */
18387   etByte flag_dp;            /* True if decimal point should be shown */
18388   etByte flag_rtz;           /* True if trailing zeros should be removed */
18389   etByte flag_exp;           /* True to force display of the exponent */
18390   int nsd;                   /* Number of significant digits returned */
18391 #endif
18392
18393   length = 0;
18394   bufpt = 0;
18395   for(; (c=(*fmt))!=0; ++fmt){
18396     if( c!='%' ){
18397       int amt;
18398       bufpt = (char *)fmt;
18399       amt = 1;
18400       while( (c=(*++fmt))!='%' && c!=0 ) amt++;
18401       sqlite3StrAccumAppend(pAccum, bufpt, amt);
18402       if( c==0 ) break;
18403     }
18404     if( (c=(*++fmt))==0 ){
18405       sqlite3StrAccumAppend(pAccum, "%", 1);
18406       break;
18407     }
18408     /* Find out what flags are present */
18409     flag_leftjustify = flag_plussign = flag_blanksign = 
18410      flag_alternateform = flag_altform2 = flag_zeropad = 0;
18411     done = 0;
18412     do{
18413       switch( c ){
18414         case '-':   flag_leftjustify = 1;     break;
18415         case '+':   flag_plussign = 1;        break;
18416         case ' ':   flag_blanksign = 1;       break;
18417         case '#':   flag_alternateform = 1;   break;
18418         case '!':   flag_altform2 = 1;        break;
18419         case '0':   flag_zeropad = 1;         break;
18420         default:    done = 1;                 break;
18421       }
18422     }while( !done && (c=(*++fmt))!=0 );
18423     /* Get the field width */
18424     width = 0;
18425     if( c=='*' ){
18426       width = va_arg(ap,int);
18427       if( width<0 ){
18428         flag_leftjustify = 1;
18429         width = -width;
18430       }
18431       c = *++fmt;
18432     }else{
18433       while( c>='0' && c<='9' ){
18434         width = width*10 + c - '0';
18435         c = *++fmt;
18436       }
18437     }
18438     if( width > etBUFSIZE-10 ){
18439       width = etBUFSIZE-10;
18440     }
18441     /* Get the precision */
18442     if( c=='.' ){
18443       precision = 0;
18444       c = *++fmt;
18445       if( c=='*' ){
18446         precision = va_arg(ap,int);
18447         if( precision<0 ) precision = -precision;
18448         c = *++fmt;
18449       }else{
18450         while( c>='0' && c<='9' ){
18451           precision = precision*10 + c - '0';
18452           c = *++fmt;
18453         }
18454       }
18455     }else{
18456       precision = -1;
18457     }
18458     /* Get the conversion type modifier */
18459     if( c=='l' ){
18460       flag_long = 1;
18461       c = *++fmt;
18462       if( c=='l' ){
18463         flag_longlong = 1;
18464         c = *++fmt;
18465       }else{
18466         flag_longlong = 0;
18467       }
18468     }else{
18469       flag_long = flag_longlong = 0;
18470     }
18471     /* Fetch the info entry for the field */
18472     infop = &fmtinfo[0];
18473     xtype = etINVALID;
18474     for(idx=0; idx<ArraySize(fmtinfo); idx++){
18475       if( c==fmtinfo[idx].fmttype ){
18476         infop = &fmtinfo[idx];
18477         if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
18478           xtype = infop->type;
18479         }else{
18480           return;
18481         }
18482         break;
18483       }
18484     }
18485     zExtra = 0;
18486
18487
18488     /* Limit the precision to prevent overflowing buf[] during conversion */
18489     if( precision>etBUFSIZE-40 && (infop->flags & FLAG_STRING)==0 ){
18490       precision = etBUFSIZE-40;
18491     }
18492
18493     /*
18494     ** At this point, variables are initialized as follows:
18495     **
18496     **   flag_alternateform          TRUE if a '#' is present.
18497     **   flag_altform2               TRUE if a '!' is present.
18498     **   flag_plussign               TRUE if a '+' is present.
18499     **   flag_leftjustify            TRUE if a '-' is present or if the
18500     **                               field width was negative.
18501     **   flag_zeropad                TRUE if the width began with 0.
18502     **   flag_long                   TRUE if the letter 'l' (ell) prefixed
18503     **                               the conversion character.
18504     **   flag_longlong               TRUE if the letter 'll' (ell ell) prefixed
18505     **                               the conversion character.
18506     **   flag_blanksign              TRUE if a ' ' is present.
18507     **   width                       The specified field width.  This is
18508     **                               always non-negative.  Zero is the default.
18509     **   precision                   The specified precision.  The default
18510     **                               is -1.
18511     **   xtype                       The class of the conversion.
18512     **   infop                       Pointer to the appropriate info struct.
18513     */
18514     switch( xtype ){
18515       case etPOINTER:
18516         flag_longlong = sizeof(char*)==sizeof(i64);
18517         flag_long = sizeof(char*)==sizeof(long int);
18518         /* Fall through into the next case */
18519       case etORDINAL:
18520       case etRADIX:
18521         if( infop->flags & FLAG_SIGNED ){
18522           i64 v;
18523           if( flag_longlong ){
18524             v = va_arg(ap,i64);
18525           }else if( flag_long ){
18526             v = va_arg(ap,long int);
18527           }else{
18528             v = va_arg(ap,int);
18529           }
18530           if( v<0 ){
18531             longvalue = -v;
18532             prefix = '-';
18533           }else{
18534             longvalue = v;
18535             if( flag_plussign )        prefix = '+';
18536             else if( flag_blanksign )  prefix = ' ';
18537             else                       prefix = 0;
18538           }
18539         }else{
18540           if( flag_longlong ){
18541             longvalue = va_arg(ap,u64);
18542           }else if( flag_long ){
18543             longvalue = va_arg(ap,unsigned long int);
18544           }else{
18545             longvalue = va_arg(ap,unsigned int);
18546           }
18547           prefix = 0;
18548         }
18549         if( longvalue==0 ) flag_alternateform = 0;
18550         if( flag_zeropad && precision<width-(prefix!=0) ){
18551           precision = width-(prefix!=0);
18552         }
18553         bufpt = &buf[etBUFSIZE-1];
18554         if( xtype==etORDINAL ){
18555           static const char zOrd[] = "thstndrd";
18556           int x = (int)(longvalue % 10);
18557           if( x>=4 || (longvalue/10)%10==1 ){
18558             x = 0;
18559           }
18560           buf[etBUFSIZE-3] = zOrd[x*2];
18561           buf[etBUFSIZE-2] = zOrd[x*2+1];
18562           bufpt -= 2;
18563         }
18564         {
18565           register const char *cset;      /* Use registers for speed */
18566           register int base;
18567           cset = &aDigits[infop->charset];
18568           base = infop->base;
18569           do{                                           /* Convert to ascii */
18570             *(--bufpt) = cset[longvalue%base];
18571             longvalue = longvalue/base;
18572           }while( longvalue>0 );
18573         }
18574         length = (int)(&buf[etBUFSIZE-1]-bufpt);
18575         for(idx=precision-length; idx>0; idx--){
18576           *(--bufpt) = '0';                             /* Zero pad */
18577         }
18578         if( prefix ) *(--bufpt) = prefix;               /* Add sign */
18579         if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
18580           const char *pre;
18581           char x;
18582           pre = &aPrefix[infop->prefix];
18583           for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
18584         }
18585         length = (int)(&buf[etBUFSIZE-1]-bufpt);
18586         break;
18587       case etFLOAT:
18588       case etEXP:
18589       case etGENERIC:
18590         realvalue = va_arg(ap,double);
18591 #ifdef SQLITE_OMIT_FLOATING_POINT
18592         length = 0;
18593 #else
18594         if( precision<0 ) precision = 6;         /* Set default precision */
18595         if( precision>etBUFSIZE/2-10 ) precision = etBUFSIZE/2-10;
18596         if( realvalue<0.0 ){
18597           realvalue = -realvalue;
18598           prefix = '-';
18599         }else{
18600           if( flag_plussign )          prefix = '+';
18601           else if( flag_blanksign )    prefix = ' ';
18602           else                         prefix = 0;
18603         }
18604         if( xtype==etGENERIC && precision>0 ) precision--;
18605 #if 0
18606         /* Rounding works like BSD when the constant 0.4999 is used.  Wierd! */
18607         for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
18608 #else
18609         /* It makes more sense to use 0.5 */
18610         for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
18611 #endif
18612         if( xtype==etFLOAT ) realvalue += rounder;
18613         /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
18614         exp = 0;
18615         if( sqlite3IsNaN((double)realvalue) ){
18616           bufpt = "NaN";
18617           length = 3;
18618           break;
18619         }
18620         if( realvalue>0.0 ){
18621           while( realvalue>=1e32 && exp<=350 ){ realvalue *= 1e-32; exp+=32; }
18622           while( realvalue>=1e8 && exp<=350 ){ realvalue *= 1e-8; exp+=8; }
18623           while( realvalue>=10.0 && exp<=350 ){ realvalue *= 0.1; exp++; }
18624           while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
18625           while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
18626           if( exp>350 ){
18627             if( prefix=='-' ){
18628               bufpt = "-Inf";
18629             }else if( prefix=='+' ){
18630               bufpt = "+Inf";
18631             }else{
18632               bufpt = "Inf";
18633             }
18634             length = sqlite3Strlen30(bufpt);
18635             break;
18636           }
18637         }
18638         bufpt = buf;
18639         /*
18640         ** If the field type is etGENERIC, then convert to either etEXP
18641         ** or etFLOAT, as appropriate.
18642         */
18643         flag_exp = xtype==etEXP;
18644         if( xtype!=etFLOAT ){
18645           realvalue += rounder;
18646           if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
18647         }
18648         if( xtype==etGENERIC ){
18649           flag_rtz = !flag_alternateform;
18650           if( exp<-4 || exp>precision ){
18651             xtype = etEXP;
18652           }else{
18653             precision = precision - exp;
18654             xtype = etFLOAT;
18655           }
18656         }else{
18657           flag_rtz = 0;
18658         }
18659         if( xtype==etEXP ){
18660           e2 = 0;
18661         }else{
18662           e2 = exp;
18663         }
18664         nsd = 0;
18665         flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
18666         /* The sign in front of the number */
18667         if( prefix ){
18668           *(bufpt++) = prefix;
18669         }
18670         /* Digits prior to the decimal point */
18671         if( e2<0 ){
18672           *(bufpt++) = '0';
18673         }else{
18674           for(; e2>=0; e2--){
18675             *(bufpt++) = et_getdigit(&realvalue,&nsd);
18676           }
18677         }
18678         /* The decimal point */
18679         if( flag_dp ){
18680           *(bufpt++) = '.';
18681         }
18682         /* "0" digits after the decimal point but before the first
18683         ** significant digit of the number */
18684         for(e2++; e2<0; precision--, e2++){
18685           assert( precision>0 );
18686           *(bufpt++) = '0';
18687         }
18688         /* Significant digits after the decimal point */
18689         while( (precision--)>0 ){
18690           *(bufpt++) = et_getdigit(&realvalue,&nsd);
18691         }
18692         /* Remove trailing zeros and the "." if no digits follow the "." */
18693         if( flag_rtz && flag_dp ){
18694           while( bufpt[-1]=='0' ) *(--bufpt) = 0;
18695           assert( bufpt>buf );
18696           if( bufpt[-1]=='.' ){
18697             if( flag_altform2 ){
18698               *(bufpt++) = '0';
18699             }else{
18700               *(--bufpt) = 0;
18701             }
18702           }
18703         }
18704         /* Add the "eNNN" suffix */
18705         if( flag_exp || xtype==etEXP ){
18706           *(bufpt++) = aDigits[infop->charset];
18707           if( exp<0 ){
18708             *(bufpt++) = '-'; exp = -exp;
18709           }else{
18710             *(bufpt++) = '+';
18711           }
18712           if( exp>=100 ){
18713             *(bufpt++) = (char)((exp/100)+'0');        /* 100's digit */
18714             exp %= 100;
18715           }
18716           *(bufpt++) = (char)(exp/10+'0');             /* 10's digit */
18717           *(bufpt++) = (char)(exp%10+'0');             /* 1's digit */
18718         }
18719         *bufpt = 0;
18720
18721         /* The converted number is in buf[] and zero terminated. Output it.
18722         ** Note that the number is in the usual order, not reversed as with
18723         ** integer conversions. */
18724         length = (int)(bufpt-buf);
18725         bufpt = buf;
18726
18727         /* Special case:  Add leading zeros if the flag_zeropad flag is
18728         ** set and we are not left justified */
18729         if( flag_zeropad && !flag_leftjustify && length < width){
18730           int i;
18731           int nPad = width - length;
18732           for(i=width; i>=nPad; i--){
18733             bufpt[i] = bufpt[i-nPad];
18734           }
18735           i = prefix!=0;
18736           while( nPad-- ) bufpt[i++] = '0';
18737           length = width;
18738         }
18739 #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
18740         break;
18741       case etSIZE:
18742         *(va_arg(ap,int*)) = pAccum->nChar;
18743         length = width = 0;
18744         break;
18745       case etPERCENT:
18746         buf[0] = '%';
18747         bufpt = buf;
18748         length = 1;
18749         break;
18750       case etCHARX:
18751         c = va_arg(ap,int);
18752         buf[0] = (char)c;
18753         if( precision>=0 ){
18754           for(idx=1; idx<precision; idx++) buf[idx] = (char)c;
18755           length = precision;
18756         }else{
18757           length =1;
18758         }
18759         bufpt = buf;
18760         break;
18761       case etSTRING:
18762       case etDYNSTRING:
18763         bufpt = va_arg(ap,char*);
18764         if( bufpt==0 ){
18765           bufpt = "";
18766         }else if( xtype==etDYNSTRING ){
18767           zExtra = bufpt;
18768         }
18769         if( precision>=0 ){
18770           for(length=0; length<precision && bufpt[length]; length++){}
18771         }else{
18772           length = sqlite3Strlen30(bufpt);
18773         }
18774         break;
18775       case etSQLESCAPE:
18776       case etSQLESCAPE2:
18777       case etSQLESCAPE3: {
18778         int i, j, k, n, isnull;
18779         int needQuote;
18780         char ch;
18781         char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
18782         char *escarg = va_arg(ap,char*);
18783         isnull = escarg==0;
18784         if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
18785         k = precision;
18786         for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
18787           if( ch==q )  n++;
18788         }
18789         needQuote = !isnull && xtype==etSQLESCAPE2;
18790         n += i + 1 + needQuote*2;
18791         if( n>etBUFSIZE ){
18792           bufpt = zExtra = sqlite3Malloc( n );
18793           if( bufpt==0 ){
18794             pAccum->mallocFailed = 1;
18795             return;
18796           }
18797         }else{
18798           bufpt = buf;
18799         }
18800         j = 0;
18801         if( needQuote ) bufpt[j++] = q;
18802         k = i;
18803         for(i=0; i<k; i++){
18804           bufpt[j++] = ch = escarg[i];
18805           if( ch==q ) bufpt[j++] = ch;
18806         }
18807         if( needQuote ) bufpt[j++] = q;
18808         bufpt[j] = 0;
18809         length = j;
18810         /* The precision in %q and %Q means how many input characters to
18811         ** consume, not the length of the output...
18812         ** if( precision>=0 && precision<length ) length = precision; */
18813         break;
18814       }
18815       case etTOKEN: {
18816         Token *pToken = va_arg(ap, Token*);
18817         if( pToken ){
18818           sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
18819         }
18820         length = width = 0;
18821         break;
18822       }
18823       case etSRCLIST: {
18824         SrcList *pSrc = va_arg(ap, SrcList*);
18825         int k = va_arg(ap, int);
18826         struct SrcList_item *pItem = &pSrc->a[k];
18827         assert( k>=0 && k<pSrc->nSrc );
18828         if( pItem->zDatabase ){
18829           sqlite3StrAccumAppend(pAccum, pItem->zDatabase, -1);
18830           sqlite3StrAccumAppend(pAccum, ".", 1);
18831         }
18832         sqlite3StrAccumAppend(pAccum, pItem->zName, -1);
18833         length = width = 0;
18834         break;
18835       }
18836       default: {
18837         assert( xtype==etINVALID );
18838         return;
18839       }
18840     }/* End switch over the format type */
18841     /*
18842     ** The text of the conversion is pointed to by "bufpt" and is
18843     ** "length" characters long.  The field width is "width".  Do
18844     ** the output.
18845     */
18846     if( !flag_leftjustify ){
18847       register int nspace;
18848       nspace = width-length;
18849       if( nspace>0 ){
18850         appendSpace(pAccum, nspace);
18851       }
18852     }
18853     if( length>0 ){
18854       sqlite3StrAccumAppend(pAccum, bufpt, length);
18855     }
18856     if( flag_leftjustify ){
18857       register int nspace;
18858       nspace = width-length;
18859       if( nspace>0 ){
18860         appendSpace(pAccum, nspace);
18861       }
18862     }
18863     if( zExtra ){
18864       sqlite3_free(zExtra);
18865     }
18866   }/* End for loop over the format string */
18867 } /* End of function */
18868
18869 /*
18870 ** Append N bytes of text from z to the StrAccum object.
18871 */
18872 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
18873   assert( z!=0 || N==0 );
18874   if( p->tooBig | p->mallocFailed ){
18875     testcase(p->tooBig);
18876     testcase(p->mallocFailed);
18877     return;
18878   }
18879   if( N<0 ){
18880     N = sqlite3Strlen30(z);
18881   }
18882   if( N==0 || NEVER(z==0) ){
18883     return;
18884   }
18885   if( p->nChar+N >= p->nAlloc ){
18886     char *zNew;
18887     if( !p->useMalloc ){
18888       p->tooBig = 1;
18889       N = p->nAlloc - p->nChar - 1;
18890       if( N<=0 ){
18891         return;
18892       }
18893     }else{
18894       i64 szNew = p->nChar;
18895       szNew += N + 1;
18896       if( szNew > p->mxAlloc ){
18897         sqlite3StrAccumReset(p);
18898         p->tooBig = 1;
18899         return;
18900       }else{
18901         p->nAlloc = (int)szNew;
18902       }
18903       if( p->useMalloc==1 ){
18904         zNew = sqlite3DbMallocRaw(p->db, p->nAlloc );
18905       }else{
18906         zNew = sqlite3_malloc(p->nAlloc);
18907       }
18908       if( zNew ){
18909         memcpy(zNew, p->zText, p->nChar);
18910         sqlite3StrAccumReset(p);
18911         p->zText = zNew;
18912       }else{
18913         p->mallocFailed = 1;
18914         sqlite3StrAccumReset(p);
18915         return;
18916       }
18917     }
18918   }
18919   memcpy(&p->zText[p->nChar], z, N);
18920   p->nChar += N;
18921 }
18922
18923 /*
18924 ** Finish off a string by making sure it is zero-terminated.
18925 ** Return a pointer to the resulting string.  Return a NULL
18926 ** pointer if any kind of error was encountered.
18927 */
18928 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
18929   if( p->zText ){
18930     p->zText[p->nChar] = 0;
18931     if( p->useMalloc && p->zText==p->zBase ){
18932       if( p->useMalloc==1 ){
18933         p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
18934       }else{
18935         p->zText = sqlite3_malloc(p->nChar+1);
18936       }
18937       if( p->zText ){
18938         memcpy(p->zText, p->zBase, p->nChar+1);
18939       }else{
18940         p->mallocFailed = 1;
18941       }
18942     }
18943   }
18944   return p->zText;
18945 }
18946
18947 /*
18948 ** Reset an StrAccum string.  Reclaim all malloced memory.
18949 */
18950 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
18951   if( p->zText!=p->zBase ){
18952     if( p->useMalloc==1 ){
18953       sqlite3DbFree(p->db, p->zText);
18954     }else{
18955       sqlite3_free(p->zText);
18956     }
18957   }
18958   p->zText = 0;
18959 }
18960
18961 /*
18962 ** Initialize a string accumulator
18963 */
18964 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
18965   p->zText = p->zBase = zBase;
18966   p->db = 0;
18967   p->nChar = 0;
18968   p->nAlloc = n;
18969   p->mxAlloc = mx;
18970   p->useMalloc = 1;
18971   p->tooBig = 0;
18972   p->mallocFailed = 0;
18973 }
18974
18975 /*
18976 ** Print into memory obtained from sqliteMalloc().  Use the internal
18977 ** %-conversion extensions.
18978 */
18979 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
18980   char *z;
18981   char zBase[SQLITE_PRINT_BUF_SIZE];
18982   StrAccum acc;
18983   assert( db!=0 );
18984   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
18985                       db->aLimit[SQLITE_LIMIT_LENGTH]);
18986   acc.db = db;
18987   sqlite3VXPrintf(&acc, 1, zFormat, ap);
18988   z = sqlite3StrAccumFinish(&acc);
18989   if( acc.mallocFailed ){
18990     db->mallocFailed = 1;
18991   }
18992   return z;
18993 }
18994
18995 /*
18996 ** Print into memory obtained from sqliteMalloc().  Use the internal
18997 ** %-conversion extensions.
18998 */
18999 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
19000   va_list ap;
19001   char *z;
19002   va_start(ap, zFormat);
19003   z = sqlite3VMPrintf(db, zFormat, ap);
19004   va_end(ap);
19005   return z;
19006 }
19007
19008 /*
19009 ** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
19010 ** the string and before returnning.  This routine is intended to be used
19011 ** to modify an existing string.  For example:
19012 **
19013 **       x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
19014 **
19015 */
19016 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
19017   va_list ap;
19018   char *z;
19019   va_start(ap, zFormat);
19020   z = sqlite3VMPrintf(db, zFormat, ap);
19021   va_end(ap);
19022   sqlite3DbFree(db, zStr);
19023   return z;
19024 }
19025
19026 /*
19027 ** Print into memory obtained from sqlite3_malloc().  Omit the internal
19028 ** %-conversion extensions.
19029 */
19030 SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
19031   char *z;
19032   char zBase[SQLITE_PRINT_BUF_SIZE];
19033   StrAccum acc;
19034 #ifndef SQLITE_OMIT_AUTOINIT
19035   if( sqlite3_initialize() ) return 0;
19036 #endif
19037   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
19038   acc.useMalloc = 2;
19039   sqlite3VXPrintf(&acc, 0, zFormat, ap);
19040   z = sqlite3StrAccumFinish(&acc);
19041   return z;
19042 }
19043
19044 /*
19045 ** Print into memory obtained from sqlite3_malloc()().  Omit the internal
19046 ** %-conversion extensions.
19047 */
19048 SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
19049   va_list ap;
19050   char *z;
19051 #ifndef SQLITE_OMIT_AUTOINIT
19052   if( sqlite3_initialize() ) return 0;
19053 #endif
19054   va_start(ap, zFormat);
19055   z = sqlite3_vmprintf(zFormat, ap);
19056   va_end(ap);
19057   return z;
19058 }
19059
19060 /*
19061 ** sqlite3_snprintf() works like snprintf() except that it ignores the
19062 ** current locale settings.  This is important for SQLite because we
19063 ** are not able to use a "," as the decimal point in place of "." as
19064 ** specified by some locales.
19065 */
19066 SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
19067   char *z;
19068   va_list ap;
19069   StrAccum acc;
19070
19071   if( n<=0 ){
19072     return zBuf;
19073   }
19074   sqlite3StrAccumInit(&acc, zBuf, n, 0);
19075   acc.useMalloc = 0;
19076   va_start(ap,zFormat);
19077   sqlite3VXPrintf(&acc, 0, zFormat, ap);
19078   va_end(ap);
19079   z = sqlite3StrAccumFinish(&acc);
19080   return z;
19081 }
19082
19083 /*
19084 ** This is the routine that actually formats the sqlite3_log() message.
19085 ** We house it in a separate routine from sqlite3_log() to avoid using
19086 ** stack space on small-stack systems when logging is disabled.
19087 **
19088 ** sqlite3_log() must render into a static buffer.  It cannot dynamically
19089 ** allocate memory because it might be called while the memory allocator
19090 ** mutex is held.
19091 */
19092 static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
19093   StrAccum acc;                          /* String accumulator */
19094   char zMsg[SQLITE_PRINT_BUF_SIZE*3];    /* Complete log message */
19095
19096   sqlite3StrAccumInit(&acc, zMsg, sizeof(zMsg), 0);
19097   acc.useMalloc = 0;
19098   sqlite3VXPrintf(&acc, 0, zFormat, ap);
19099   sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
19100                            sqlite3StrAccumFinish(&acc));
19101 }
19102
19103 /*
19104 ** Format and write a message to the log if logging is enabled.
19105 */
19106 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
19107   va_list ap;                             /* Vararg list */
19108   if( sqlite3GlobalConfig.xLog ){
19109     va_start(ap, zFormat);
19110     renderLogMsg(iErrCode, zFormat, ap);
19111     va_end(ap);
19112   }
19113 }
19114
19115 #if defined(SQLITE_DEBUG)
19116 /*
19117 ** A version of printf() that understands %lld.  Used for debugging.
19118 ** The printf() built into some versions of windows does not understand %lld
19119 ** and segfaults if you give it a long long int.
19120 */
19121 SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
19122   va_list ap;
19123   StrAccum acc;
19124   char zBuf[500];
19125   sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
19126   acc.useMalloc = 0;
19127   va_start(ap,zFormat);
19128   sqlite3VXPrintf(&acc, 0, zFormat, ap);
19129   va_end(ap);
19130   sqlite3StrAccumFinish(&acc);
19131   fprintf(stdout,"%s", zBuf);
19132   fflush(stdout);
19133 }
19134 #endif
19135
19136 #ifndef SQLITE_OMIT_TRACE
19137 /*
19138 ** variable-argument wrapper around sqlite3VXPrintf().
19139 */
19140 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
19141   va_list ap;
19142   va_start(ap,zFormat);
19143   sqlite3VXPrintf(p, 1, zFormat, ap);
19144   va_end(ap);
19145 }
19146 #endif
19147
19148 /************** End of printf.c **********************************************/
19149 /************** Begin file random.c ******************************************/
19150 /*
19151 ** 2001 September 15
19152 **
19153 ** The author disclaims copyright to this source code.  In place of
19154 ** a legal notice, here is a blessing:
19155 **
19156 **    May you do good and not evil.
19157 **    May you find forgiveness for yourself and forgive others.
19158 **    May you share freely, never taking more than you give.
19159 **
19160 *************************************************************************
19161 ** This file contains code to implement a pseudo-random number
19162 ** generator (PRNG) for SQLite.
19163 **
19164 ** Random numbers are used by some of the database backends in order
19165 ** to generate random integer keys for tables or random filenames.
19166 */
19167
19168
19169 /* All threads share a single random number generator.
19170 ** This structure is the current state of the generator.
19171 */
19172 static SQLITE_WSD struct sqlite3PrngType {
19173   unsigned char isInit;          /* True if initialized */
19174   unsigned char i, j;            /* State variables */
19175   unsigned char s[256];          /* State variables */
19176 } sqlite3Prng;
19177
19178 /*
19179 ** Get a single 8-bit random value from the RC4 PRNG.  The Mutex
19180 ** must be held while executing this routine.
19181 **
19182 ** Why not just use a library random generator like lrand48() for this?
19183 ** Because the OP_NewRowid opcode in the VDBE depends on having a very
19184 ** good source of random numbers.  The lrand48() library function may
19185 ** well be good enough.  But maybe not.  Or maybe lrand48() has some
19186 ** subtle problems on some systems that could cause problems.  It is hard
19187 ** to know.  To minimize the risk of problems due to bad lrand48()
19188 ** implementations, SQLite uses this random number generator based
19189 ** on RC4, which we know works very well.
19190 **
19191 ** (Later):  Actually, OP_NewRowid does not depend on a good source of
19192 ** randomness any more.  But we will leave this code in all the same.
19193 */
19194 static u8 randomByte(void){
19195   unsigned char t;
19196
19197
19198   /* The "wsdPrng" macro will resolve to the pseudo-random number generator
19199   ** state vector.  If writable static data is unsupported on the target,
19200   ** we have to locate the state vector at run-time.  In the more common
19201   ** case where writable static data is supported, wsdPrng can refer directly
19202   ** to the "sqlite3Prng" state vector declared above.
19203   */
19204 #ifdef SQLITE_OMIT_WSD
19205   struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
19206 # define wsdPrng p[0]
19207 #else
19208 # define wsdPrng sqlite3Prng
19209 #endif
19210
19211
19212   /* Initialize the state of the random number generator once,
19213   ** the first time this routine is called.  The seed value does
19214   ** not need to contain a lot of randomness since we are not
19215   ** trying to do secure encryption or anything like that...
19216   **
19217   ** Nothing in this file or anywhere else in SQLite does any kind of
19218   ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random
19219   ** number generator) not as an encryption device.
19220   */
19221   if( !wsdPrng.isInit ){
19222     int i;
19223     char k[256];
19224     wsdPrng.j = 0;
19225     wsdPrng.i = 0;
19226     sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
19227     for(i=0; i<256; i++){
19228       wsdPrng.s[i] = (u8)i;
19229     }
19230     for(i=0; i<256; i++){
19231       wsdPrng.j += wsdPrng.s[i] + k[i];
19232       t = wsdPrng.s[wsdPrng.j];
19233       wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
19234       wsdPrng.s[i] = t;
19235     }
19236     wsdPrng.isInit = 1;
19237   }
19238
19239   /* Generate and return single random byte
19240   */
19241   wsdPrng.i++;
19242   t = wsdPrng.s[wsdPrng.i];
19243   wsdPrng.j += t;
19244   wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
19245   wsdPrng.s[wsdPrng.j] = t;
19246   t += wsdPrng.s[wsdPrng.i];
19247   return wsdPrng.s[t];
19248 }
19249
19250 /*
19251 ** Return N random bytes.
19252 */
19253 SQLITE_API void sqlite3_randomness(int N, void *pBuf){
19254   unsigned char *zBuf = pBuf;
19255 #if SQLITE_THREADSAFE
19256   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
19257 #endif
19258   sqlite3_mutex_enter(mutex);
19259   while( N-- ){
19260     *(zBuf++) = randomByte();
19261   }
19262   sqlite3_mutex_leave(mutex);
19263 }
19264
19265 #ifndef SQLITE_OMIT_BUILTIN_TEST
19266 /*
19267 ** For testing purposes, we sometimes want to preserve the state of
19268 ** PRNG and restore the PRNG to its saved state at a later time, or
19269 ** to reset the PRNG to its initial state.  These routines accomplish
19270 ** those tasks.
19271 **
19272 ** The sqlite3_test_control() interface calls these routines to
19273 ** control the PRNG.
19274 */
19275 static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
19276 SQLITE_PRIVATE void sqlite3PrngSaveState(void){
19277   memcpy(
19278     &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
19279     &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
19280     sizeof(sqlite3Prng)
19281   );
19282 }
19283 SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
19284   memcpy(
19285     &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
19286     &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
19287     sizeof(sqlite3Prng)
19288   );
19289 }
19290 SQLITE_PRIVATE void sqlite3PrngResetState(void){
19291   GLOBAL(struct sqlite3PrngType, sqlite3Prng).isInit = 0;
19292 }
19293 #endif /* SQLITE_OMIT_BUILTIN_TEST */
19294
19295 /************** End of random.c **********************************************/
19296 /************** Begin file utf.c *********************************************/
19297 /*
19298 ** 2004 April 13
19299 **
19300 ** The author disclaims copyright to this source code.  In place of
19301 ** a legal notice, here is a blessing:
19302 **
19303 **    May you do good and not evil.
19304 **    May you find forgiveness for yourself and forgive others.
19305 **    May you share freely, never taking more than you give.
19306 **
19307 *************************************************************************
19308 ** This file contains routines used to translate between UTF-8, 
19309 ** UTF-16, UTF-16BE, and UTF-16LE.
19310 **
19311 ** Notes on UTF-8:
19312 **
19313 **   Byte-0    Byte-1    Byte-2    Byte-3    Value
19314 **  0xxxxxxx                                 00000000 00000000 0xxxxxxx
19315 **  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx
19316 **  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx
19317 **  11110uuu  10uuzzzz  10yyyyyy  10xxxxxx   000uuuuu zzzzyyyy yyxxxxxx
19318 **
19319 **
19320 ** Notes on UTF-16:  (with wwww+1==uuuuu)
19321 **
19322 **      Word-0               Word-1          Value
19323 **  110110ww wwzzzzyy   110111yy yyxxxxxx    000uuuuu zzzzyyyy yyxxxxxx
19324 **  zzzzyyyy yyxxxxxx                        00000000 zzzzyyyy yyxxxxxx
19325 **
19326 **
19327 ** BOM or Byte Order Mark:
19328 **     0xff 0xfe   little-endian utf-16 follows
19329 **     0xfe 0xff   big-endian utf-16 follows
19330 **
19331 */
19332
19333 #ifndef SQLITE_AMALGAMATION
19334 /*
19335 ** The following constant value is used by the SQLITE_BIGENDIAN and
19336 ** SQLITE_LITTLEENDIAN macros.
19337 */
19338 SQLITE_PRIVATE const int sqlite3one = 1;
19339 #endif /* SQLITE_AMALGAMATION */
19340
19341 /*
19342 ** This lookup table is used to help decode the first byte of
19343 ** a multi-byte UTF8 character.
19344 */
19345 static const unsigned char sqlite3Utf8Trans1[] = {
19346   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
19347   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
19348   0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
19349   0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
19350   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
19351   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
19352   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
19353   0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
19354 };
19355
19356
19357 #define WRITE_UTF8(zOut, c) {                          \
19358   if( c<0x00080 ){                                     \
19359     *zOut++ = (u8)(c&0xFF);                            \
19360   }                                                    \
19361   else if( c<0x00800 ){                                \
19362     *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
19363     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
19364   }                                                    \
19365   else if( c<0x10000 ){                                \
19366     *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
19367     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
19368     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
19369   }else{                                               \
19370     *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
19371     *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
19372     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
19373     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
19374   }                                                    \
19375 }
19376
19377 #define WRITE_UTF16LE(zOut, c) {                                    \
19378   if( c<=0xFFFF ){                                                  \
19379     *zOut++ = (u8)(c&0x00FF);                                       \
19380     *zOut++ = (u8)((c>>8)&0x00FF);                                  \
19381   }else{                                                            \
19382     *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
19383     *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
19384     *zOut++ = (u8)(c&0x00FF);                                       \
19385     *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
19386   }                                                                 \
19387 }
19388
19389 #define WRITE_UTF16BE(zOut, c) {                                    \
19390   if( c<=0xFFFF ){                                                  \
19391     *zOut++ = (u8)((c>>8)&0x00FF);                                  \
19392     *zOut++ = (u8)(c&0x00FF);                                       \
19393   }else{                                                            \
19394     *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
19395     *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
19396     *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
19397     *zOut++ = (u8)(c&0x00FF);                                       \
19398   }                                                                 \
19399 }
19400
19401 #define READ_UTF16LE(zIn, TERM, c){                                   \
19402   c = (*zIn++);                                                       \
19403   c += ((*zIn++)<<8);                                                 \
19404   if( c>=0xD800 && c<0xE000 && TERM ){                                \
19405     int c2 = (*zIn++);                                                \
19406     c2 += ((*zIn++)<<8);                                              \
19407     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
19408   }                                                                   \
19409 }
19410
19411 #define READ_UTF16BE(zIn, TERM, c){                                   \
19412   c = ((*zIn++)<<8);                                                  \
19413   c += (*zIn++);                                                      \
19414   if( c>=0xD800 && c<0xE000 && TERM ){                                \
19415     int c2 = ((*zIn++)<<8);                                           \
19416     c2 += (*zIn++);                                                   \
19417     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
19418   }                                                                   \
19419 }
19420
19421 /*
19422 ** Translate a single UTF-8 character.  Return the unicode value.
19423 **
19424 ** During translation, assume that the byte that zTerm points
19425 ** is a 0x00.
19426 **
19427 ** Write a pointer to the next unread byte back into *pzNext.
19428 **
19429 ** Notes On Invalid UTF-8:
19430 **
19431 **  *  This routine never allows a 7-bit character (0x00 through 0x7f) to
19432 **     be encoded as a multi-byte character.  Any multi-byte character that
19433 **     attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
19434 **
19435 **  *  This routine never allows a UTF16 surrogate value to be encoded.
19436 **     If a multi-byte character attempts to encode a value between
19437 **     0xd800 and 0xe000 then it is rendered as 0xfffd.
19438 **
19439 **  *  Bytes in the range of 0x80 through 0xbf which occur as the first
19440 **     byte of a character are interpreted as single-byte characters
19441 **     and rendered as themselves even though they are technically
19442 **     invalid characters.
19443 **
19444 **  *  This routine accepts an infinite number of different UTF8 encodings
19445 **     for unicode values 0x80 and greater.  It do not change over-length
19446 **     encodings to 0xfffd as some systems recommend.
19447 */
19448 #define READ_UTF8(zIn, zTerm, c)                           \
19449   c = *(zIn++);                                            \
19450   if( c>=0xc0 ){                                           \
19451     c = sqlite3Utf8Trans1[c-0xc0];                         \
19452     while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
19453       c = (c<<6) + (0x3f & *(zIn++));                      \
19454     }                                                      \
19455     if( c<0x80                                             \
19456         || (c&0xFFFFF800)==0xD800                          \
19457         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
19458   }
19459 SQLITE_PRIVATE int sqlite3Utf8Read(
19460   const unsigned char *zIn,       /* First byte of UTF-8 character */
19461   const unsigned char **pzNext    /* Write first byte past UTF-8 char here */
19462 ){
19463   int c;
19464
19465   /* Same as READ_UTF8() above but without the zTerm parameter.
19466   ** For this routine, we assume the UTF8 string is always zero-terminated.
19467   */
19468   c = *(zIn++);
19469   if( c>=0xc0 ){
19470     c = sqlite3Utf8Trans1[c-0xc0];
19471     while( (*zIn & 0xc0)==0x80 ){
19472       c = (c<<6) + (0x3f & *(zIn++));
19473     }
19474     if( c<0x80
19475         || (c&0xFFFFF800)==0xD800
19476         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }
19477   }
19478   *pzNext = zIn;
19479   return c;
19480 }
19481
19482
19483
19484
19485 /*
19486 ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
19487 ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
19488 */ 
19489 /* #define TRANSLATE_TRACE 1 */
19490
19491 #ifndef SQLITE_OMIT_UTF16
19492 /*
19493 ** This routine transforms the internal text encoding used by pMem to
19494 ** desiredEnc. It is an error if the string is already of the desired
19495 ** encoding, or if *pMem does not contain a string value.
19496 */
19497 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
19498   int len;                    /* Maximum length of output string in bytes */
19499   unsigned char *zOut;                  /* Output buffer */
19500   unsigned char *zIn;                   /* Input iterator */
19501   unsigned char *zTerm;                 /* End of input */
19502   unsigned char *z;                     /* Output iterator */
19503   unsigned int c;
19504
19505   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
19506   assert( pMem->flags&MEM_Str );
19507   assert( pMem->enc!=desiredEnc );
19508   assert( pMem->enc!=0 );
19509   assert( pMem->n>=0 );
19510
19511 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
19512   {
19513     char zBuf[100];
19514     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
19515     fprintf(stderr, "INPUT:  %s\n", zBuf);
19516   }
19517 #endif
19518
19519   /* If the translation is between UTF-16 little and big endian, then 
19520   ** all that is required is to swap the byte order. This case is handled
19521   ** differently from the others.
19522   */
19523   if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
19524     u8 temp;
19525     int rc;
19526     rc = sqlite3VdbeMemMakeWriteable(pMem);
19527     if( rc!=SQLITE_OK ){
19528       assert( rc==SQLITE_NOMEM );
19529       return SQLITE_NOMEM;
19530     }
19531     zIn = (u8*)pMem->z;
19532     zTerm = &zIn[pMem->n&~1];
19533     while( zIn<zTerm ){
19534       temp = *zIn;
19535       *zIn = *(zIn+1);
19536       zIn++;
19537       *zIn++ = temp;
19538     }
19539     pMem->enc = desiredEnc;
19540     goto translate_out;
19541   }
19542
19543   /* Set len to the maximum number of bytes required in the output buffer. */
19544   if( desiredEnc==SQLITE_UTF8 ){
19545     /* When converting from UTF-16, the maximum growth results from
19546     ** translating a 2-byte character to a 4-byte UTF-8 character.
19547     ** A single byte is required for the output string
19548     ** nul-terminator.
19549     */
19550     pMem->n &= ~1;
19551     len = pMem->n * 2 + 1;
19552   }else{
19553     /* When converting from UTF-8 to UTF-16 the maximum growth is caused
19554     ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
19555     ** character. Two bytes are required in the output buffer for the
19556     ** nul-terminator.
19557     */
19558     len = pMem->n * 2 + 2;
19559   }
19560
19561   /* Set zIn to point at the start of the input buffer and zTerm to point 1
19562   ** byte past the end.
19563   **
19564   ** Variable zOut is set to point at the output buffer, space obtained
19565   ** from sqlite3_malloc().
19566   */
19567   zIn = (u8*)pMem->z;
19568   zTerm = &zIn[pMem->n];
19569   zOut = sqlite3DbMallocRaw(pMem->db, len);
19570   if( !zOut ){
19571     return SQLITE_NOMEM;
19572   }
19573   z = zOut;
19574
19575   if( pMem->enc==SQLITE_UTF8 ){
19576     if( desiredEnc==SQLITE_UTF16LE ){
19577       /* UTF-8 -> UTF-16 Little-endian */
19578       while( zIn<zTerm ){
19579         /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
19580         READ_UTF8(zIn, zTerm, c);
19581         WRITE_UTF16LE(z, c);
19582       }
19583     }else{
19584       assert( desiredEnc==SQLITE_UTF16BE );
19585       /* UTF-8 -> UTF-16 Big-endian */
19586       while( zIn<zTerm ){
19587         /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
19588         READ_UTF8(zIn, zTerm, c);
19589         WRITE_UTF16BE(z, c);
19590       }
19591     }
19592     pMem->n = (int)(z - zOut);
19593     *z++ = 0;
19594   }else{
19595     assert( desiredEnc==SQLITE_UTF8 );
19596     if( pMem->enc==SQLITE_UTF16LE ){
19597       /* UTF-16 Little-endian -> UTF-8 */
19598       while( zIn<zTerm ){
19599         READ_UTF16LE(zIn, zIn<zTerm, c); 
19600         WRITE_UTF8(z, c);
19601       }
19602     }else{
19603       /* UTF-16 Big-endian -> UTF-8 */
19604       while( zIn<zTerm ){
19605         READ_UTF16BE(zIn, zIn<zTerm, c); 
19606         WRITE_UTF8(z, c);
19607       }
19608     }
19609     pMem->n = (int)(z - zOut);
19610   }
19611   *z = 0;
19612   assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
19613
19614   sqlite3VdbeMemRelease(pMem);
19615   pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);
19616   pMem->enc = desiredEnc;
19617   pMem->flags |= (MEM_Term|MEM_Dyn);
19618   pMem->z = (char*)zOut;
19619   pMem->zMalloc = pMem->z;
19620
19621 translate_out:
19622 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
19623   {
19624     char zBuf[100];
19625     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
19626     fprintf(stderr, "OUTPUT: %s\n", zBuf);
19627   }
19628 #endif
19629   return SQLITE_OK;
19630 }
19631
19632 /*
19633 ** This routine checks for a byte-order mark at the beginning of the 
19634 ** UTF-16 string stored in *pMem. If one is present, it is removed and
19635 ** the encoding of the Mem adjusted. This routine does not do any
19636 ** byte-swapping, it just sets Mem.enc appropriately.
19637 **
19638 ** The allocation (static, dynamic etc.) and encoding of the Mem may be
19639 ** changed by this function.
19640 */
19641 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
19642   int rc = SQLITE_OK;
19643   u8 bom = 0;
19644
19645   assert( pMem->n>=0 );
19646   if( pMem->n>1 ){
19647     u8 b1 = *(u8 *)pMem->z;
19648     u8 b2 = *(((u8 *)pMem->z) + 1);
19649     if( b1==0xFE && b2==0xFF ){
19650       bom = SQLITE_UTF16BE;
19651     }
19652     if( b1==0xFF && b2==0xFE ){
19653       bom = SQLITE_UTF16LE;
19654     }
19655   }
19656   
19657   if( bom ){
19658     rc = sqlite3VdbeMemMakeWriteable(pMem);
19659     if( rc==SQLITE_OK ){
19660       pMem->n -= 2;
19661       memmove(pMem->z, &pMem->z[2], pMem->n);
19662       pMem->z[pMem->n] = '\0';
19663       pMem->z[pMem->n+1] = '\0';
19664       pMem->flags |= MEM_Term;
19665       pMem->enc = bom;
19666     }
19667   }
19668   return rc;
19669 }
19670 #endif /* SQLITE_OMIT_UTF16 */
19671
19672 /*
19673 ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
19674 ** return the number of unicode characters in pZ up to (but not including)
19675 ** the first 0x00 byte. If nByte is not less than zero, return the
19676 ** number of unicode characters in the first nByte of pZ (or up to 
19677 ** the first 0x00, whichever comes first).
19678 */
19679 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
19680   int r = 0;
19681   const u8 *z = (const u8*)zIn;
19682   const u8 *zTerm;
19683   if( nByte>=0 ){
19684     zTerm = &z[nByte];
19685   }else{
19686     zTerm = (const u8*)(-1);
19687   }
19688   assert( z<=zTerm );
19689   while( *z!=0 && z<zTerm ){
19690     SQLITE_SKIP_UTF8(z);
19691     r++;
19692   }
19693   return r;
19694 }
19695
19696 /* This test function is not currently used by the automated test-suite. 
19697 ** Hence it is only available in debug builds.
19698 */
19699 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
19700 /*
19701 ** Translate UTF-8 to UTF-8.
19702 **
19703 ** This has the effect of making sure that the string is well-formed
19704 ** UTF-8.  Miscoded characters are removed.
19705 **
19706 ** The translation is done in-place (since it is impossible for the
19707 ** correct UTF-8 encoding to be longer than a malformed encoding).
19708 */
19709 SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
19710   unsigned char *zOut = zIn;
19711   unsigned char *zStart = zIn;
19712   u32 c;
19713
19714   while( zIn[0] ){
19715     c = sqlite3Utf8Read(zIn, (const u8**)&zIn);
19716     if( c!=0xfffd ){
19717       WRITE_UTF8(zOut, c);
19718     }
19719   }
19720   *zOut = 0;
19721   return (int)(zOut - zStart);
19722 }
19723 #endif
19724
19725 #ifndef SQLITE_OMIT_UTF16
19726 /*
19727 ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
19728 ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
19729 ** be freed by the calling function.
19730 **
19731 ** NULL is returned if there is an allocation error.
19732 */
19733 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
19734   Mem m;
19735   memset(&m, 0, sizeof(m));
19736   m.db = db;
19737   sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
19738   sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
19739   if( db->mallocFailed ){
19740     sqlite3VdbeMemRelease(&m);
19741     m.z = 0;
19742   }
19743   assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
19744   assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
19745   assert( (m.flags & MEM_Dyn)!=0 || db->mallocFailed );
19746   assert( m.z || db->mallocFailed );
19747   return m.z;
19748 }
19749
19750 /*
19751 ** Convert a UTF-8 string to the UTF-16 encoding specified by parameter
19752 ** enc. A pointer to the new string is returned, and the value of *pnOut
19753 ** is set to the length of the returned string in bytes. The call should
19754 ** arrange to call sqlite3DbFree() on the returned pointer when it is
19755 ** no longer required.
19756 ** 
19757 ** If a malloc failure occurs, NULL is returned and the db.mallocFailed
19758 ** flag set.
19759 */
19760 #ifdef SQLITE_ENABLE_STAT2
19761 SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *db, u8 enc, char *z, int n, int *pnOut){
19762   Mem m;
19763   memset(&m, 0, sizeof(m));
19764   m.db = db;
19765   sqlite3VdbeMemSetStr(&m, z, n, SQLITE_UTF8, SQLITE_STATIC);
19766   if( sqlite3VdbeMemTranslate(&m, enc) ){
19767     assert( db->mallocFailed );
19768     return 0;
19769   }
19770   assert( m.z==m.zMalloc );
19771   *pnOut = m.n;
19772   return m.z;
19773 }
19774 #endif
19775
19776 /*
19777 ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
19778 ** Return the number of bytes in the first nChar unicode characters
19779 ** in pZ.  nChar must be non-negative.
19780 */
19781 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
19782   int c;
19783   unsigned char const *z = zIn;
19784   int n = 0;
19785   
19786   if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
19787     while( n<nChar ){
19788       READ_UTF16BE(z, 1, c);
19789       n++;
19790     }
19791   }else{
19792     while( n<nChar ){
19793       READ_UTF16LE(z, 1, c);
19794       n++;
19795     }
19796   }
19797   return (int)(z-(unsigned char const *)zIn);
19798 }
19799
19800 #if defined(SQLITE_TEST)
19801 /*
19802 ** This routine is called from the TCL test function "translate_selftest".
19803 ** It checks that the primitives for serializing and deserializing
19804 ** characters in each encoding are inverses of each other.
19805 */
19806 SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
19807   unsigned int i, t;
19808   unsigned char zBuf[20];
19809   unsigned char *z;
19810   int n;
19811   unsigned int c;
19812
19813   for(i=0; i<0x00110000; i++){
19814     z = zBuf;
19815     WRITE_UTF8(z, i);
19816     n = (int)(z-zBuf);
19817     assert( n>0 && n<=4 );
19818     z[0] = 0;
19819     z = zBuf;
19820     c = sqlite3Utf8Read(z, (const u8**)&z);
19821     t = i;
19822     if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
19823     if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
19824     assert( c==t );
19825     assert( (z-zBuf)==n );
19826   }
19827   for(i=0; i<0x00110000; i++){
19828     if( i>=0xD800 && i<0xE000 ) continue;
19829     z = zBuf;
19830     WRITE_UTF16LE(z, i);
19831     n = (int)(z-zBuf);
19832     assert( n>0 && n<=4 );
19833     z[0] = 0;
19834     z = zBuf;
19835     READ_UTF16LE(z, 1, c);
19836     assert( c==i );
19837     assert( (z-zBuf)==n );
19838   }
19839   for(i=0; i<0x00110000; i++){
19840     if( i>=0xD800 && i<0xE000 ) continue;
19841     z = zBuf;
19842     WRITE_UTF16BE(z, i);
19843     n = (int)(z-zBuf);
19844     assert( n>0 && n<=4 );
19845     z[0] = 0;
19846     z = zBuf;
19847     READ_UTF16BE(z, 1, c);
19848     assert( c==i );
19849     assert( (z-zBuf)==n );
19850   }
19851 }
19852 #endif /* SQLITE_TEST */
19853 #endif /* SQLITE_OMIT_UTF16 */
19854
19855 /************** End of utf.c *************************************************/
19856 /************** Begin file util.c ********************************************/
19857 /*
19858 ** 2001 September 15
19859 **
19860 ** The author disclaims copyright to this source code.  In place of
19861 ** a legal notice, here is a blessing:
19862 **
19863 **    May you do good and not evil.
19864 **    May you find forgiveness for yourself and forgive others.
19865 **    May you share freely, never taking more than you give.
19866 **
19867 *************************************************************************
19868 ** Utility functions used throughout sqlite.
19869 **
19870 ** This file contains functions for allocating memory, comparing
19871 ** strings, and stuff like that.
19872 **
19873 */
19874 #ifdef SQLITE_HAVE_ISNAN
19875 # include <math.h>
19876 #endif
19877
19878 /*
19879 ** Routine needed to support the testcase() macro.
19880 */
19881 #ifdef SQLITE_COVERAGE_TEST
19882 SQLITE_PRIVATE void sqlite3Coverage(int x){
19883   static int dummy = 0;
19884   dummy += x;
19885 }
19886 #endif
19887
19888 #ifndef SQLITE_OMIT_FLOATING_POINT
19889 /*
19890 ** Return true if the floating point value is Not a Number (NaN).
19891 **
19892 ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
19893 ** Otherwise, we have our own implementation that works on most systems.
19894 */
19895 SQLITE_PRIVATE int sqlite3IsNaN(double x){
19896   int rc;   /* The value return */
19897 #if !defined(SQLITE_HAVE_ISNAN)
19898   /*
19899   ** Systems that support the isnan() library function should probably
19900   ** make use of it by compiling with -DSQLITE_HAVE_ISNAN.  But we have
19901   ** found that many systems do not have a working isnan() function so
19902   ** this implementation is provided as an alternative.
19903   **
19904   ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
19905   ** On the other hand, the use of -ffast-math comes with the following
19906   ** warning:
19907   **
19908   **      This option [-ffast-math] should never be turned on by any
19909   **      -O option since it can result in incorrect output for programs
19910   **      which depend on an exact implementation of IEEE or ISO 
19911   **      rules/specifications for math functions.
19912   **
19913   ** Under MSVC, this NaN test may fail if compiled with a floating-
19914   ** point precision mode other than /fp:precise.  From the MSDN 
19915   ** documentation:
19916   **
19917   **      The compiler [with /fp:precise] will properly handle comparisons 
19918   **      involving NaN. For example, x != x evaluates to true if x is NaN 
19919   **      ...
19920   */
19921 #ifdef __FAST_MATH__
19922 # error SQLite will not work correctly with the -ffast-math option of GCC.
19923 #endif
19924   volatile double y = x;
19925   volatile double z = y;
19926   rc = (y!=z);
19927 #else  /* if defined(SQLITE_HAVE_ISNAN) */
19928   rc = isnan(x);
19929 #endif /* SQLITE_HAVE_ISNAN */
19930   testcase( rc );
19931   return rc;
19932 }
19933 #endif /* SQLITE_OMIT_FLOATING_POINT */
19934
19935 /*
19936 ** Compute a string length that is limited to what can be stored in
19937 ** lower 30 bits of a 32-bit signed integer.
19938 **
19939 ** The value returned will never be negative.  Nor will it ever be greater
19940 ** than the actual length of the string.  For very long strings (greater
19941 ** than 1GiB) the value returned might be less than the true string length.
19942 */
19943 SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
19944   const char *z2 = z;
19945   if( z==0 ) return 0;
19946   while( *z2 ){ z2++; }
19947   return 0x3fffffff & (int)(z2 - z);
19948 }
19949
19950 /*
19951 ** Set the most recent error code and error string for the sqlite
19952 ** handle "db". The error code is set to "err_code".
19953 **
19954 ** If it is not NULL, string zFormat specifies the format of the
19955 ** error string in the style of the printf functions: The following
19956 ** format characters are allowed:
19957 **
19958 **      %s      Insert a string
19959 **      %z      A string that should be freed after use
19960 **      %d      Insert an integer
19961 **      %T      Insert a token
19962 **      %S      Insert the first element of a SrcList
19963 **
19964 ** zFormat and any string tokens that follow it are assumed to be
19965 ** encoded in UTF-8.
19966 **
19967 ** To clear the most recent error for sqlite handle "db", sqlite3Error
19968 ** should be called with err_code set to SQLITE_OK and zFormat set
19969 ** to NULL.
19970 */
19971 SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
19972   if( db && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){
19973     db->errCode = err_code;
19974     if( zFormat ){
19975       char *z;
19976       va_list ap;
19977       va_start(ap, zFormat);
19978       z = sqlite3VMPrintf(db, zFormat, ap);
19979       va_end(ap);
19980       sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
19981     }else{
19982       sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
19983     }
19984   }
19985 }
19986
19987 /*
19988 ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
19989 ** The following formatting characters are allowed:
19990 **
19991 **      %s      Insert a string
19992 **      %z      A string that should be freed after use
19993 **      %d      Insert an integer
19994 **      %T      Insert a token
19995 **      %S      Insert the first element of a SrcList
19996 **
19997 ** This function should be used to report any error that occurs whilst
19998 ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
19999 ** last thing the sqlite3_prepare() function does is copy the error
20000 ** stored by this function into the database handle using sqlite3Error().
20001 ** Function sqlite3Error() should be used during statement execution
20002 ** (sqlite3_step() etc.).
20003 */
20004 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
20005   char *zMsg;
20006   va_list ap;
20007   sqlite3 *db = pParse->db;
20008   va_start(ap, zFormat);
20009   zMsg = sqlite3VMPrintf(db, zFormat, ap);
20010   va_end(ap);
20011   if( db->suppressErr ){
20012     sqlite3DbFree(db, zMsg);
20013   }else{
20014     pParse->nErr++;
20015     sqlite3DbFree(db, pParse->zErrMsg);
20016     pParse->zErrMsg = zMsg;
20017     pParse->rc = SQLITE_ERROR;
20018   }
20019 }
20020
20021 /*
20022 ** Convert an SQL-style quoted string into a normal string by removing
20023 ** the quote characters.  The conversion is done in-place.  If the
20024 ** input does not begin with a quote character, then this routine
20025 ** is a no-op.
20026 **
20027 ** The input string must be zero-terminated.  A new zero-terminator
20028 ** is added to the dequoted string.
20029 **
20030 ** The return value is -1 if no dequoting occurs or the length of the
20031 ** dequoted string, exclusive of the zero terminator, if dequoting does
20032 ** occur.
20033 **
20034 ** 2002-Feb-14: This routine is extended to remove MS-Access style
20035 ** brackets from around identifers.  For example:  "[a-b-c]" becomes
20036 ** "a-b-c".
20037 */
20038 SQLITE_PRIVATE int sqlite3Dequote(char *z){
20039   char quote;
20040   int i, j;
20041   if( z==0 ) return -1;
20042   quote = z[0];
20043   switch( quote ){
20044     case '\'':  break;
20045     case '"':   break;
20046     case '`':   break;                /* For MySQL compatibility */
20047     case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
20048     default:    return -1;
20049   }
20050   for(i=1, j=0; ALWAYS(z[i]); i++){
20051     if( z[i]==quote ){
20052       if( z[i+1]==quote ){
20053         z[j++] = quote;
20054         i++;
20055       }else{
20056         break;
20057       }
20058     }else{
20059       z[j++] = z[i];
20060     }
20061   }
20062   z[j] = 0;
20063   return j;
20064 }
20065
20066 /* Convenient short-hand */
20067 #define UpperToLower sqlite3UpperToLower
20068
20069 /*
20070 ** Some systems have stricmp().  Others have strcasecmp().  Because
20071 ** there is no consistency, we will define our own.
20072 **
20073 ** IMPLEMENTATION-OF: R-20522-24639 The sqlite3_strnicmp() API allows
20074 ** applications and extensions to compare the contents of two buffers
20075 ** containing UTF-8 strings in a case-independent fashion, using the same
20076 ** definition of case independence that SQLite uses internally when
20077 ** comparing identifiers.
20078 */
20079 SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
20080   register unsigned char *a, *b;
20081   a = (unsigned char *)zLeft;
20082   b = (unsigned char *)zRight;
20083   while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
20084   return UpperToLower[*a] - UpperToLower[*b];
20085 }
20086 SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
20087   register unsigned char *a, *b;
20088   a = (unsigned char *)zLeft;
20089   b = (unsigned char *)zRight;
20090   while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
20091   return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
20092 }
20093
20094 /*
20095 ** The string z[] is an text representation of a real number.
20096 ** Convert this string to a double and write it into *pResult.
20097 **
20098 ** The string z[] is length bytes in length (bytes, not characters) and
20099 ** uses the encoding enc.  The string is not necessarily zero-terminated.
20100 **
20101 ** Return TRUE if the result is a valid real number (or integer) and FALSE
20102 ** if the string is empty or contains extraneous text.  Valid numbers
20103 ** are in one of these formats:
20104 **
20105 **    [+-]digits[E[+-]digits]
20106 **    [+-]digits.[digits][E[+-]digits]
20107 **    [+-].digits[E[+-]digits]
20108 **
20109 ** Leading and trailing whitespace is ignored for the purpose of determining
20110 ** validity.
20111 **
20112 ** If some prefix of the input string is a valid number, this routine
20113 ** returns FALSE but it still converts the prefix and writes the result
20114 ** into *pResult.
20115 */
20116 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
20117 #ifndef SQLITE_OMIT_FLOATING_POINT
20118   int incr = (enc==SQLITE_UTF8?1:2);
20119   const char *zEnd = z + length;
20120   /* sign * significand * (10 ^ (esign * exponent)) */
20121   int sign = 1;    /* sign of significand */
20122   i64 s = 0;       /* significand */
20123   int d = 0;       /* adjust exponent for shifting decimal point */
20124   int esign = 1;   /* sign of exponent */
20125   int e = 0;       /* exponent */
20126   int eValid = 1;  /* True exponent is either not used or is well-formed */
20127   double result;
20128   int nDigits = 0;
20129
20130   *pResult = 0.0;   /* Default return value, in case of an error */
20131
20132   if( enc==SQLITE_UTF16BE ) z++;
20133
20134   /* skip leading spaces */
20135   while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
20136   if( z>=zEnd ) return 0;
20137
20138   /* get sign of significand */
20139   if( *z=='-' ){
20140     sign = -1;
20141     z+=incr;
20142   }else if( *z=='+' ){
20143     z+=incr;
20144   }
20145
20146   /* skip leading zeroes */
20147   while( z<zEnd && z[0]=='0' ) z+=incr, nDigits++;
20148
20149   /* copy max significant digits to significand */
20150   while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
20151     s = s*10 + (*z - '0');
20152     z+=incr, nDigits++;
20153   }
20154
20155   /* skip non-significant significand digits
20156   ** (increase exponent by d to shift decimal left) */
20157   while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
20158   if( z>=zEnd ) goto do_atof_calc;
20159
20160   /* if decimal point is present */
20161   if( *z=='.' ){
20162     z+=incr;
20163     /* copy digits from after decimal to significand
20164     ** (decrease exponent by d to shift decimal right) */
20165     while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
20166       s = s*10 + (*z - '0');
20167       z+=incr, nDigits++, d--;
20168     }
20169     /* skip non-significant digits */
20170     while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++;
20171   }
20172   if( z>=zEnd ) goto do_atof_calc;
20173
20174   /* if exponent is present */
20175   if( *z=='e' || *z=='E' ){
20176     z+=incr;
20177     eValid = 0;
20178     if( z>=zEnd ) goto do_atof_calc;
20179     /* get sign of exponent */
20180     if( *z=='-' ){
20181       esign = -1;
20182       z+=incr;
20183     }else if( *z=='+' ){
20184       z+=incr;
20185     }
20186     /* copy digits to exponent */
20187     while( z<zEnd && sqlite3Isdigit(*z) ){
20188       e = e*10 + (*z - '0');
20189       z+=incr;
20190       eValid = 1;
20191     }
20192   }
20193
20194   /* skip trailing spaces */
20195   if( nDigits && eValid ){
20196     while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
20197   }
20198
20199 do_atof_calc:
20200   /* adjust exponent by d, and update sign */
20201   e = (e*esign) + d;
20202   if( e<0 ) {
20203     esign = -1;
20204     e *= -1;
20205   } else {
20206     esign = 1;
20207   }
20208
20209   /* if 0 significand */
20210   if( !s ) {
20211     /* In the IEEE 754 standard, zero is signed.
20212     ** Add the sign if we've seen at least one digit */
20213     result = (sign<0 && nDigits) ? -(double)0 : (double)0;
20214   } else {
20215     /* attempt to reduce exponent */
20216     if( esign>0 ){
20217       while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
20218     }else{
20219       while( !(s%10) && e>0 ) e--,s/=10;
20220     }
20221
20222     /* adjust the sign of significand */
20223     s = sign<0 ? -s : s;
20224
20225     /* if exponent, scale significand as appropriate
20226     ** and store in result. */
20227     if( e ){
20228       double scale = 1.0;
20229       /* attempt to handle extremely small/large numbers better */
20230       if( e>307 && e<342 ){
20231         while( e%308 ) { scale *= 1.0e+1; e -= 1; }
20232         if( esign<0 ){
20233           result = s / scale;
20234           result /= 1.0e+308;
20235         }else{
20236           result = s * scale;
20237           result *= 1.0e+308;
20238         }
20239       }else{
20240         /* 1.0e+22 is the largest power of 10 than can be 
20241         ** represented exactly. */
20242         while( e%22 ) { scale *= 1.0e+1; e -= 1; }
20243         while( e>0 ) { scale *= 1.0e+22; e -= 22; }
20244         if( esign<0 ){
20245           result = s / scale;
20246         }else{
20247           result = s * scale;
20248         }
20249       }
20250     } else {
20251       result = (double)s;
20252     }
20253   }
20254
20255   /* store the result */
20256   *pResult = result;
20257
20258   /* return true if number and no extra non-whitespace chracters after */
20259   return z>=zEnd && nDigits>0 && eValid;
20260 #else
20261   return !sqlite3Atoi64(z, pResult, length, enc);
20262 #endif /* SQLITE_OMIT_FLOATING_POINT */
20263 }
20264
20265 /*
20266 ** Compare the 19-character string zNum against the text representation
20267 ** value 2^63:  9223372036854775808.  Return negative, zero, or positive
20268 ** if zNum is less than, equal to, or greater than the string.
20269 ** Note that zNum must contain exactly 19 characters.
20270 **
20271 ** Unlike memcmp() this routine is guaranteed to return the difference
20272 ** in the values of the last digit if the only difference is in the
20273 ** last digit.  So, for example,
20274 **
20275 **      compare2pow63("9223372036854775800", 1)
20276 **
20277 ** will return -8.
20278 */
20279 static int compare2pow63(const char *zNum, int incr){
20280   int c = 0;
20281   int i;
20282                     /* 012345678901234567 */
20283   const char *pow63 = "922337203685477580";
20284   for(i=0; c==0 && i<18; i++){
20285     c = (zNum[i*incr]-pow63[i])*10;
20286   }
20287   if( c==0 ){
20288     c = zNum[18*incr] - '8';
20289     testcase( c==(-1) );
20290     testcase( c==0 );
20291     testcase( c==(+1) );
20292   }
20293   return c;
20294 }
20295
20296
20297 /*
20298 ** Convert zNum to a 64-bit signed integer and write
20299 ** the value of the integer into *pNum.
20300 ** If zNum is exactly 9223372036854665808, return 2.
20301 ** This is a special case as the context will determine
20302 ** if it is too big (used as a negative).
20303 ** If zNum is not an integer or is an integer that 
20304 ** is too large to be expressed with 64 bits,
20305 ** then return 1.  Otherwise return 0.
20306 **
20307 ** length is the number of bytes in the string (bytes, not characters).
20308 ** The string is not necessarily zero-terminated.  The encoding is
20309 ** given by enc.
20310 */
20311 SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
20312   int incr = (enc==SQLITE_UTF8?1:2);
20313   i64 v = 0;
20314   int neg = 0; /* assume positive */
20315   int i;
20316   int c = 0;
20317   const char *zStart;
20318   const char *zEnd = zNum + length;
20319   if( enc==SQLITE_UTF16BE ) zNum++;
20320   while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
20321   if( zNum>=zEnd ) goto do_atoi_calc;
20322   if( *zNum=='-' ){
20323     neg = 1;
20324     zNum+=incr;
20325   }else if( *zNum=='+' ){
20326     zNum+=incr;
20327   }
20328 do_atoi_calc:
20329   zStart = zNum;
20330   while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
20331   for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
20332     v = v*10 + c - '0';
20333   }
20334   *pNum = neg ? -v : v;
20335   testcase( i==18 );
20336   testcase( i==19 );
20337   testcase( i==20 );
20338   if( (c!=0 && &zNum[i]<zEnd) || (i==0 && zStart==zNum) || i>19*incr ){
20339     /* zNum is empty or contains non-numeric text or is longer
20340     ** than 19 digits (thus guaranteeing that it is too large) */
20341     return 1;
20342   }else if( i<19*incr ){
20343     /* Less than 19 digits, so we know that it fits in 64 bits */
20344     return 0;
20345   }else{
20346     /* 19-digit numbers must be no larger than 9223372036854775807 if positive
20347     ** or 9223372036854775808 if negative.  Note that 9223372036854665808
20348     ** is 2^63. Return 1 if to large */
20349     c=compare2pow63(zNum, incr);
20350     if( c==0 && neg==0 ) return 2; /* too big, exactly 9223372036854665808 */
20351     return c<neg ? 0 : 1;
20352   }
20353 }
20354
20355 /*
20356 ** If zNum represents an integer that will fit in 32-bits, then set
20357 ** *pValue to that integer and return true.  Otherwise return false.
20358 **
20359 ** Any non-numeric characters that following zNum are ignored.
20360 ** This is different from sqlite3Atoi64() which requires the
20361 ** input number to be zero-terminated.
20362 */
20363 SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
20364   sqlite_int64 v = 0;
20365   int i, c;
20366   int neg = 0;
20367   if( zNum[0]=='-' ){
20368     neg = 1;
20369     zNum++;
20370   }else if( zNum[0]=='+' ){
20371     zNum++;
20372   }
20373   while( zNum[0]=='0' ) zNum++;
20374   for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
20375     v = v*10 + c;
20376   }
20377
20378   /* The longest decimal representation of a 32 bit integer is 10 digits:
20379   **
20380   **             1234567890
20381   **     2^31 -> 2147483648
20382   */
20383   testcase( i==10 );
20384   if( i>10 ){
20385     return 0;
20386   }
20387   testcase( v-neg==2147483647 );
20388   if( v-neg>2147483647 ){
20389     return 0;
20390   }
20391   if( neg ){
20392     v = -v;
20393   }
20394   *pValue = (int)v;
20395   return 1;
20396 }
20397
20398 /*
20399 ** The variable-length integer encoding is as follows:
20400 **
20401 ** KEY:
20402 **         A = 0xxxxxxx    7 bits of data and one flag bit
20403 **         B = 1xxxxxxx    7 bits of data and one flag bit
20404 **         C = xxxxxxxx    8 bits of data
20405 **
20406 **  7 bits - A
20407 ** 14 bits - BA
20408 ** 21 bits - BBA
20409 ** 28 bits - BBBA
20410 ** 35 bits - BBBBA
20411 ** 42 bits - BBBBBA
20412 ** 49 bits - BBBBBBA
20413 ** 56 bits - BBBBBBBA
20414 ** 64 bits - BBBBBBBBC
20415 */
20416
20417 /*
20418 ** Write a 64-bit variable-length integer to memory starting at p[0].
20419 ** The length of data write will be between 1 and 9 bytes.  The number
20420 ** of bytes written is returned.
20421 **
20422 ** A variable-length integer consists of the lower 7 bits of each byte
20423 ** for all bytes that have the 8th bit set and one byte with the 8th
20424 ** bit clear.  Except, if we get to the 9th byte, it stores the full
20425 ** 8 bits and is the last byte.
20426 */
20427 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
20428   int i, j, n;
20429   u8 buf[10];
20430   if( v & (((u64)0xff000000)<<32) ){
20431     p[8] = (u8)v;
20432     v >>= 8;
20433     for(i=7; i>=0; i--){
20434       p[i] = (u8)((v & 0x7f) | 0x80);
20435       v >>= 7;
20436     }
20437     return 9;
20438   }    
20439   n = 0;
20440   do{
20441     buf[n++] = (u8)((v & 0x7f) | 0x80);
20442     v >>= 7;
20443   }while( v!=0 );
20444   buf[0] &= 0x7f;
20445   assert( n<=9 );
20446   for(i=0, j=n-1; j>=0; j--, i++){
20447     p[i] = buf[j];
20448   }
20449   return n;
20450 }
20451
20452 /*
20453 ** This routine is a faster version of sqlite3PutVarint() that only
20454 ** works for 32-bit positive integers and which is optimized for
20455 ** the common case of small integers.  A MACRO version, putVarint32,
20456 ** is provided which inlines the single-byte case.  All code should use
20457 ** the MACRO version as this function assumes the single-byte case has
20458 ** already been handled.
20459 */
20460 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char *p, u32 v){
20461 #ifndef putVarint32
20462   if( (v & ~0x7f)==0 ){
20463     p[0] = v;
20464     return 1;
20465   }
20466 #endif
20467   if( (v & ~0x3fff)==0 ){
20468     p[0] = (u8)((v>>7) | 0x80);
20469     p[1] = (u8)(v & 0x7f);
20470     return 2;
20471   }
20472   return sqlite3PutVarint(p, v);
20473 }
20474
20475 /*
20476 ** Bitmasks used by sqlite3GetVarint().  These precomputed constants
20477 ** are defined here rather than simply putting the constant expressions
20478 ** inline in order to work around bugs in the RVT compiler.
20479 **
20480 ** SLOT_2_0     A mask for  (0x7f<<14) | 0x7f
20481 **
20482 ** SLOT_4_2_0   A mask for  (0x7f<<28) | SLOT_2_0
20483 */
20484 #define SLOT_2_0     0x001fc07f
20485 #define SLOT_4_2_0   0xf01fc07f
20486
20487
20488 /*
20489 ** Read a 64-bit variable-length integer from memory starting at p[0].
20490 ** Return the number of bytes read.  The value is stored in *v.
20491 */
20492 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
20493   u32 a,b,s;
20494
20495   a = *p;
20496   /* a: p0 (unmasked) */
20497   if (!(a&0x80))
20498   {
20499     *v = a;
20500     return 1;
20501   }
20502
20503   p++;
20504   b = *p;
20505   /* b: p1 (unmasked) */
20506   if (!(b&0x80))
20507   {
20508     a &= 0x7f;
20509     a = a<<7;
20510     a |= b;
20511     *v = a;
20512     return 2;
20513   }
20514
20515   /* Verify that constants are precomputed correctly */
20516   assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
20517   assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
20518
20519   p++;
20520   a = a<<14;
20521   a |= *p;
20522   /* a: p0<<14 | p2 (unmasked) */
20523   if (!(a&0x80))
20524   {
20525     a &= SLOT_2_0;
20526     b &= 0x7f;
20527     b = b<<7;
20528     a |= b;
20529     *v = a;
20530     return 3;
20531   }
20532
20533   /* CSE1 from below */
20534   a &= SLOT_2_0;
20535   p++;
20536   b = b<<14;
20537   b |= *p;
20538   /* b: p1<<14 | p3 (unmasked) */
20539   if (!(b&0x80))
20540   {
20541     b &= SLOT_2_0;
20542     /* moved CSE1 up */
20543     /* a &= (0x7f<<14)|(0x7f); */
20544     a = a<<7;
20545     a |= b;
20546     *v = a;
20547     return 4;
20548   }
20549
20550   /* a: p0<<14 | p2 (masked) */
20551   /* b: p1<<14 | p3 (unmasked) */
20552   /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
20553   /* moved CSE1 up */
20554   /* a &= (0x7f<<14)|(0x7f); */
20555   b &= SLOT_2_0;
20556   s = a;
20557   /* s: p0<<14 | p2 (masked) */
20558
20559   p++;
20560   a = a<<14;
20561   a |= *p;
20562   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
20563   if (!(a&0x80))
20564   {
20565     /* we can skip these cause they were (effectively) done above in calc'ing s */
20566     /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
20567     /* b &= (0x7f<<14)|(0x7f); */
20568     b = b<<7;
20569     a |= b;
20570     s = s>>18;
20571     *v = ((u64)s)<<32 | a;
20572     return 5;
20573   }
20574
20575   /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
20576   s = s<<7;
20577   s |= b;
20578   /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
20579
20580   p++;
20581   b = b<<14;
20582   b |= *p;
20583   /* b: p1<<28 | p3<<14 | p5 (unmasked) */
20584   if (!(b&0x80))
20585   {
20586     /* we can skip this cause it was (effectively) done above in calc'ing s */
20587     /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
20588     a &= SLOT_2_0;
20589     a = a<<7;
20590     a |= b;
20591     s = s>>18;
20592     *v = ((u64)s)<<32 | a;
20593     return 6;
20594   }
20595
20596   p++;
20597   a = a<<14;
20598   a |= *p;
20599   /* a: p2<<28 | p4<<14 | p6 (unmasked) */
20600   if (!(a&0x80))
20601   {
20602     a &= SLOT_4_2_0;
20603     b &= SLOT_2_0;
20604     b = b<<7;
20605     a |= b;
20606     s = s>>11;
20607     *v = ((u64)s)<<32 | a;
20608     return 7;
20609   }
20610
20611   /* CSE2 from below */
20612   a &= SLOT_2_0;
20613   p++;
20614   b = b<<14;
20615   b |= *p;
20616   /* b: p3<<28 | p5<<14 | p7 (unmasked) */
20617   if (!(b&0x80))
20618   {
20619     b &= SLOT_4_2_0;
20620     /* moved CSE2 up */
20621     /* a &= (0x7f<<14)|(0x7f); */
20622     a = a<<7;
20623     a |= b;
20624     s = s>>4;
20625     *v = ((u64)s)<<32 | a;
20626     return 8;
20627   }
20628
20629   p++;
20630   a = a<<15;
20631   a |= *p;
20632   /* a: p4<<29 | p6<<15 | p8 (unmasked) */
20633
20634   /* moved CSE2 up */
20635   /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
20636   b &= SLOT_2_0;
20637   b = b<<8;
20638   a |= b;
20639
20640   s = s<<4;
20641   b = p[-4];
20642   b &= 0x7f;
20643   b = b>>3;
20644   s |= b;
20645
20646   *v = ((u64)s)<<32 | a;
20647
20648   return 9;
20649 }
20650
20651 /*
20652 ** Read a 32-bit variable-length integer from memory starting at p[0].
20653 ** Return the number of bytes read.  The value is stored in *v.
20654 **
20655 ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
20656 ** integer, then set *v to 0xffffffff.
20657 **
20658 ** A MACRO version, getVarint32, is provided which inlines the 
20659 ** single-byte case.  All code should use the MACRO version as 
20660 ** this function assumes the single-byte case has already been handled.
20661 */
20662 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
20663   u32 a,b;
20664
20665   /* The 1-byte case.  Overwhelmingly the most common.  Handled inline
20666   ** by the getVarin32() macro */
20667   a = *p;
20668   /* a: p0 (unmasked) */
20669 #ifndef getVarint32
20670   if (!(a&0x80))
20671   {
20672     /* Values between 0 and 127 */
20673     *v = a;
20674     return 1;
20675   }
20676 #endif
20677
20678   /* The 2-byte case */
20679   p++;
20680   b = *p;
20681   /* b: p1 (unmasked) */
20682   if (!(b&0x80))
20683   {
20684     /* Values between 128 and 16383 */
20685     a &= 0x7f;
20686     a = a<<7;
20687     *v = a | b;
20688     return 2;
20689   }
20690
20691   /* The 3-byte case */
20692   p++;
20693   a = a<<14;
20694   a |= *p;
20695   /* a: p0<<14 | p2 (unmasked) */
20696   if (!(a&0x80))
20697   {
20698     /* Values between 16384 and 2097151 */
20699     a &= (0x7f<<14)|(0x7f);
20700     b &= 0x7f;
20701     b = b<<7;
20702     *v = a | b;
20703     return 3;
20704   }
20705
20706   /* A 32-bit varint is used to store size information in btrees.
20707   ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
20708   ** A 3-byte varint is sufficient, for example, to record the size
20709   ** of a 1048569-byte BLOB or string.
20710   **
20711   ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
20712   ** rare larger cases can be handled by the slower 64-bit varint
20713   ** routine.
20714   */
20715 #if 1
20716   {
20717     u64 v64;
20718     u8 n;
20719
20720     p -= 2;
20721     n = sqlite3GetVarint(p, &v64);
20722     assert( n>3 && n<=9 );
20723     if( (v64 & SQLITE_MAX_U32)!=v64 ){
20724       *v = 0xffffffff;
20725     }else{
20726       *v = (u32)v64;
20727     }
20728     return n;
20729   }
20730
20731 #else
20732   /* For following code (kept for historical record only) shows an
20733   ** unrolling for the 3- and 4-byte varint cases.  This code is
20734   ** slightly faster, but it is also larger and much harder to test.
20735   */
20736   p++;
20737   b = b<<14;
20738   b |= *p;
20739   /* b: p1<<14 | p3 (unmasked) */
20740   if (!(b&0x80))
20741   {
20742     /* Values between 2097152 and 268435455 */
20743     b &= (0x7f<<14)|(0x7f);
20744     a &= (0x7f<<14)|(0x7f);
20745     a = a<<7;
20746     *v = a | b;
20747     return 4;
20748   }
20749
20750   p++;
20751   a = a<<14;
20752   a |= *p;
20753   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
20754   if (!(a&0x80))
20755   {
20756     /* Values  between 268435456 and 34359738367 */
20757     a &= SLOT_4_2_0;
20758     b &= SLOT_4_2_0;
20759     b = b<<7;
20760     *v = a | b;
20761     return 5;
20762   }
20763
20764   /* We can only reach this point when reading a corrupt database
20765   ** file.  In that case we are not in any hurry.  Use the (relatively
20766   ** slow) general-purpose sqlite3GetVarint() routine to extract the
20767   ** value. */
20768   {
20769     u64 v64;
20770     u8 n;
20771
20772     p -= 4;
20773     n = sqlite3GetVarint(p, &v64);
20774     assert( n>5 && n<=9 );
20775     *v = (u32)v64;
20776     return n;
20777   }
20778 #endif
20779 }
20780
20781 /*
20782 ** Return the number of bytes that will be needed to store the given
20783 ** 64-bit integer.
20784 */
20785 SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
20786   int i = 0;
20787   do{
20788     i++;
20789     v >>= 7;
20790   }while( v!=0 && ALWAYS(i<9) );
20791   return i;
20792 }
20793
20794
20795 /*
20796 ** Read or write a four-byte big-endian integer value.
20797 */
20798 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
20799   return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
20800 }
20801 SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
20802   p[0] = (u8)(v>>24);
20803   p[1] = (u8)(v>>16);
20804   p[2] = (u8)(v>>8);
20805   p[3] = (u8)v;
20806 }
20807
20808
20809
20810 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
20811 /*
20812 ** Translate a single byte of Hex into an integer.
20813 ** This routine only works if h really is a valid hexadecimal
20814 ** character:  0..9a..fA..F
20815 */
20816 static u8 hexToInt(int h){
20817   assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
20818 #ifdef SQLITE_ASCII
20819   h += 9*(1&(h>>6));
20820 #endif
20821 #ifdef SQLITE_EBCDIC
20822   h += 9*(1&~(h>>4));
20823 #endif
20824   return (u8)(h & 0xf);
20825 }
20826 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
20827
20828 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
20829 /*
20830 ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
20831 ** value.  Return a pointer to its binary value.  Space to hold the
20832 ** binary value has been obtained from malloc and must be freed by
20833 ** the calling routine.
20834 */
20835 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
20836   char *zBlob;
20837   int i;
20838
20839   zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
20840   n--;
20841   if( zBlob ){
20842     for(i=0; i<n; i+=2){
20843       zBlob[i/2] = (hexToInt(z[i])<<4) | hexToInt(z[i+1]);
20844     }
20845     zBlob[i/2] = 0;
20846   }
20847   return zBlob;
20848 }
20849 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
20850
20851 /*
20852 ** Log an error that is an API call on a connection pointer that should
20853 ** not have been used.  The "type" of connection pointer is given as the
20854 ** argument.  The zType is a word like "NULL" or "closed" or "invalid".
20855 */
20856 static void logBadConnection(const char *zType){
20857   sqlite3_log(SQLITE_MISUSE, 
20858      "API call with %s database connection pointer",
20859      zType
20860   );
20861 }
20862
20863 /*
20864 ** Check to make sure we have a valid db pointer.  This test is not
20865 ** foolproof but it does provide some measure of protection against
20866 ** misuse of the interface such as passing in db pointers that are
20867 ** NULL or which have been previously closed.  If this routine returns
20868 ** 1 it means that the db pointer is valid and 0 if it should not be
20869 ** dereferenced for any reason.  The calling function should invoke
20870 ** SQLITE_MISUSE immediately.
20871 **
20872 ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
20873 ** use.  sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
20874 ** open properly and is not fit for general use but which can be
20875 ** used as an argument to sqlite3_errmsg() or sqlite3_close().
20876 */
20877 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
20878   u32 magic;
20879   if( db==0 ){
20880     logBadConnection("NULL");
20881     return 0;
20882   }
20883   magic = db->magic;
20884   if( magic!=SQLITE_MAGIC_OPEN ){
20885     if( sqlite3SafetyCheckSickOrOk(db) ){
20886       testcase( sqlite3GlobalConfig.xLog!=0 );
20887       logBadConnection("unopened");
20888     }
20889     return 0;
20890   }else{
20891     return 1;
20892   }
20893 }
20894 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
20895   u32 magic;
20896   magic = db->magic;
20897   if( magic!=SQLITE_MAGIC_SICK &&
20898       magic!=SQLITE_MAGIC_OPEN &&
20899       magic!=SQLITE_MAGIC_BUSY ){
20900     testcase( sqlite3GlobalConfig.xLog!=0 );
20901     logBadConnection("invalid");
20902     return 0;
20903   }else{
20904     return 1;
20905   }
20906 }
20907
20908 /************** End of util.c ************************************************/
20909 /************** Begin file hash.c ********************************************/
20910 /*
20911 ** 2001 September 22
20912 **
20913 ** The author disclaims copyright to this source code.  In place of
20914 ** a legal notice, here is a blessing:
20915 **
20916 **    May you do good and not evil.
20917 **    May you find forgiveness for yourself and forgive others.
20918 **    May you share freely, never taking more than you give.
20919 **
20920 *************************************************************************
20921 ** This is the implementation of generic hash-tables
20922 ** used in SQLite.
20923 */
20924
20925 /* Turn bulk memory into a hash table object by initializing the
20926 ** fields of the Hash structure.
20927 **
20928 ** "pNew" is a pointer to the hash table that is to be initialized.
20929 */
20930 SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
20931   assert( pNew!=0 );
20932   pNew->first = 0;
20933   pNew->count = 0;
20934   pNew->htsize = 0;
20935   pNew->ht = 0;
20936 }
20937
20938 /* Remove all entries from a hash table.  Reclaim all memory.
20939 ** Call this routine to delete a hash table or to reset a hash table
20940 ** to the empty state.
20941 */
20942 SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
20943   HashElem *elem;         /* For looping over all elements of the table */
20944
20945   assert( pH!=0 );
20946   elem = pH->first;
20947   pH->first = 0;
20948   sqlite3_free(pH->ht);
20949   pH->ht = 0;
20950   pH->htsize = 0;
20951   while( elem ){
20952     HashElem *next_elem = elem->next;
20953     sqlite3_free(elem);
20954     elem = next_elem;
20955   }
20956   pH->count = 0;
20957 }
20958
20959 /*
20960 ** The hashing function.
20961 */
20962 static unsigned int strHash(const char *z, int nKey){
20963   int h = 0;
20964   assert( nKey>=0 );
20965   while( nKey > 0  ){
20966     h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];
20967     nKey--;
20968   }
20969   return h;
20970 }
20971
20972
20973 /* Link pNew element into the hash table pH.  If pEntry!=0 then also
20974 ** insert pNew into the pEntry hash bucket.
20975 */
20976 static void insertElement(
20977   Hash *pH,              /* The complete hash table */
20978   struct _ht *pEntry,    /* The entry into which pNew is inserted */
20979   HashElem *pNew         /* The element to be inserted */
20980 ){
20981   HashElem *pHead;       /* First element already in pEntry */
20982   if( pEntry ){
20983     pHead = pEntry->count ? pEntry->chain : 0;
20984     pEntry->count++;
20985     pEntry->chain = pNew;
20986   }else{
20987     pHead = 0;
20988   }
20989   if( pHead ){
20990     pNew->next = pHead;
20991     pNew->prev = pHead->prev;
20992     if( pHead->prev ){ pHead->prev->next = pNew; }
20993     else             { pH->first = pNew; }
20994     pHead->prev = pNew;
20995   }else{
20996     pNew->next = pH->first;
20997     if( pH->first ){ pH->first->prev = pNew; }
20998     pNew->prev = 0;
20999     pH->first = pNew;
21000   }
21001 }
21002
21003
21004 /* Resize the hash table so that it cantains "new_size" buckets.
21005 **
21006 ** The hash table might fail to resize if sqlite3_malloc() fails or
21007 ** if the new size is the same as the prior size.
21008 ** Return TRUE if the resize occurs and false if not.
21009 */
21010 static int rehash(Hash *pH, unsigned int new_size){
21011   struct _ht *new_ht;            /* The new hash table */
21012   HashElem *elem, *next_elem;    /* For looping over existing elements */
21013
21014 #if SQLITE_MALLOC_SOFT_LIMIT>0
21015   if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
21016     new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
21017   }
21018   if( new_size==pH->htsize ) return 0;
21019 #endif
21020
21021   /* The inability to allocates space for a larger hash table is
21022   ** a performance hit but it is not a fatal error.  So mark the
21023   ** allocation as a benign.
21024   */
21025   sqlite3BeginBenignMalloc();
21026   new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
21027   sqlite3EndBenignMalloc();
21028
21029   if( new_ht==0 ) return 0;
21030   sqlite3_free(pH->ht);
21031   pH->ht = new_ht;
21032   pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
21033   memset(new_ht, 0, new_size*sizeof(struct _ht));
21034   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
21035     unsigned int h = strHash(elem->pKey, elem->nKey) % new_size;
21036     next_elem = elem->next;
21037     insertElement(pH, &new_ht[h], elem);
21038   }
21039   return 1;
21040 }
21041
21042 /* This function (for internal use only) locates an element in an
21043 ** hash table that matches the given key.  The hash for this key has
21044 ** already been computed and is passed as the 4th parameter.
21045 */
21046 static HashElem *findElementGivenHash(
21047   const Hash *pH,     /* The pH to be searched */
21048   const char *pKey,   /* The key we are searching for */
21049   int nKey,           /* Bytes in key (not counting zero terminator) */
21050   unsigned int h      /* The hash for this key. */
21051 ){
21052   HashElem *elem;                /* Used to loop thru the element list */
21053   int count;                     /* Number of elements left to test */
21054
21055   if( pH->ht ){
21056     struct _ht *pEntry = &pH->ht[h];
21057     elem = pEntry->chain;
21058     count = pEntry->count;
21059   }else{
21060     elem = pH->first;
21061     count = pH->count;
21062   }
21063   while( count-- && ALWAYS(elem) ){
21064     if( elem->nKey==nKey && sqlite3StrNICmp(elem->pKey,pKey,nKey)==0 ){ 
21065       return elem;
21066     }
21067     elem = elem->next;
21068   }
21069   return 0;
21070 }
21071
21072 /* Remove a single entry from the hash table given a pointer to that
21073 ** element and a hash on the element's key.
21074 */
21075 static void removeElementGivenHash(
21076   Hash *pH,         /* The pH containing "elem" */
21077   HashElem* elem,   /* The element to be removed from the pH */
21078   unsigned int h    /* Hash value for the element */
21079 ){
21080   struct _ht *pEntry;
21081   if( elem->prev ){
21082     elem->prev->next = elem->next; 
21083   }else{
21084     pH->first = elem->next;
21085   }
21086   if( elem->next ){
21087     elem->next->prev = elem->prev;
21088   }
21089   if( pH->ht ){
21090     pEntry = &pH->ht[h];
21091     if( pEntry->chain==elem ){
21092       pEntry->chain = elem->next;
21093     }
21094     pEntry->count--;
21095     assert( pEntry->count>=0 );
21096   }
21097   sqlite3_free( elem );
21098   pH->count--;
21099   if( pH->count<=0 ){
21100     assert( pH->first==0 );
21101     assert( pH->count==0 );
21102     sqlite3HashClear(pH);
21103   }
21104 }
21105
21106 /* Attempt to locate an element of the hash table pH with a key
21107 ** that matches pKey,nKey.  Return the data for this element if it is
21108 ** found, or NULL if there is no match.
21109 */
21110 SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey, int nKey){
21111   HashElem *elem;    /* The element that matches key */
21112   unsigned int h;    /* A hash on key */
21113
21114   assert( pH!=0 );
21115   assert( pKey!=0 );
21116   assert( nKey>=0 );
21117   if( pH->ht ){
21118     h = strHash(pKey, nKey) % pH->htsize;
21119   }else{
21120     h = 0;
21121   }
21122   elem = findElementGivenHash(pH, pKey, nKey, h);
21123   return elem ? elem->data : 0;
21124 }
21125
21126 /* Insert an element into the hash table pH.  The key is pKey,nKey
21127 ** and the data is "data".
21128 **
21129 ** If no element exists with a matching key, then a new
21130 ** element is created and NULL is returned.
21131 **
21132 ** If another element already exists with the same key, then the
21133 ** new data replaces the old data and the old data is returned.
21134 ** The key is not copied in this instance.  If a malloc fails, then
21135 ** the new data is returned and the hash table is unchanged.
21136 **
21137 ** If the "data" parameter to this function is NULL, then the
21138 ** element corresponding to "key" is removed from the hash table.
21139 */
21140 SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, int nKey, void *data){
21141   unsigned int h;       /* the hash of the key modulo hash table size */
21142   HashElem *elem;       /* Used to loop thru the element list */
21143   HashElem *new_elem;   /* New element added to the pH */
21144
21145   assert( pH!=0 );
21146   assert( pKey!=0 );
21147   assert( nKey>=0 );
21148   if( pH->htsize ){
21149     h = strHash(pKey, nKey) % pH->htsize;
21150   }else{
21151     h = 0;
21152   }
21153   elem = findElementGivenHash(pH,pKey,nKey,h);
21154   if( elem ){
21155     void *old_data = elem->data;
21156     if( data==0 ){
21157       removeElementGivenHash(pH,elem,h);
21158     }else{
21159       elem->data = data;
21160       elem->pKey = pKey;
21161       assert(nKey==elem->nKey);
21162     }
21163     return old_data;
21164   }
21165   if( data==0 ) return 0;
21166   new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
21167   if( new_elem==0 ) return data;
21168   new_elem->pKey = pKey;
21169   new_elem->nKey = nKey;
21170   new_elem->data = data;
21171   pH->count++;
21172   if( pH->count>=10 && pH->count > 2*pH->htsize ){
21173     if( rehash(pH, pH->count*2) ){
21174       assert( pH->htsize>0 );
21175       h = strHash(pKey, nKey) % pH->htsize;
21176     }
21177   }
21178   if( pH->ht ){
21179     insertElement(pH, &pH->ht[h], new_elem);
21180   }else{
21181     insertElement(pH, 0, new_elem);
21182   }
21183   return 0;
21184 }
21185
21186 /************** End of hash.c ************************************************/
21187 /************** Begin file opcodes.c *****************************************/
21188 /* Automatically generated.  Do not edit */
21189 /* See the mkopcodec.awk script for details. */
21190 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
21191 SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
21192  static const char *const azName[] = { "?",
21193      /*   1 */ "Goto",
21194      /*   2 */ "Gosub",
21195      /*   3 */ "Return",
21196      /*   4 */ "Yield",
21197      /*   5 */ "HaltIfNull",
21198      /*   6 */ "Halt",
21199      /*   7 */ "Integer",
21200      /*   8 */ "Int64",
21201      /*   9 */ "String",
21202      /*  10 */ "Null",
21203      /*  11 */ "Blob",
21204      /*  12 */ "Variable",
21205      /*  13 */ "Move",
21206      /*  14 */ "Copy",
21207      /*  15 */ "SCopy",
21208      /*  16 */ "ResultRow",
21209      /*  17 */ "CollSeq",
21210      /*  18 */ "Function",
21211      /*  19 */ "Not",
21212      /*  20 */ "AddImm",
21213      /*  21 */ "MustBeInt",
21214      /*  22 */ "RealAffinity",
21215      /*  23 */ "Permutation",
21216      /*  24 */ "Compare",
21217      /*  25 */ "Jump",
21218      /*  26 */ "If",
21219      /*  27 */ "IfNot",
21220      /*  28 */ "Column",
21221      /*  29 */ "Affinity",
21222      /*  30 */ "MakeRecord",
21223      /*  31 */ "Count",
21224      /*  32 */ "Savepoint",
21225      /*  33 */ "AutoCommit",
21226      /*  34 */ "Transaction",
21227      /*  35 */ "ReadCookie",
21228      /*  36 */ "SetCookie",
21229      /*  37 */ "VerifyCookie",
21230      /*  38 */ "OpenRead",
21231      /*  39 */ "OpenWrite",
21232      /*  40 */ "OpenAutoindex",
21233      /*  41 */ "OpenEphemeral",
21234      /*  42 */ "OpenPseudo",
21235      /*  43 */ "Close",
21236      /*  44 */ "SeekLt",
21237      /*  45 */ "SeekLe",
21238      /*  46 */ "SeekGe",
21239      /*  47 */ "SeekGt",
21240      /*  48 */ "Seek",
21241      /*  49 */ "NotFound",
21242      /*  50 */ "Found",
21243      /*  51 */ "IsUnique",
21244      /*  52 */ "NotExists",
21245      /*  53 */ "Sequence",
21246      /*  54 */ "NewRowid",
21247      /*  55 */ "Insert",
21248      /*  56 */ "InsertInt",
21249      /*  57 */ "Delete",
21250      /*  58 */ "ResetCount",
21251      /*  59 */ "RowKey",
21252      /*  60 */ "RowData",
21253      /*  61 */ "Rowid",
21254      /*  62 */ "NullRow",
21255      /*  63 */ "Last",
21256      /*  64 */ "Sort",
21257      /*  65 */ "Rewind",
21258      /*  66 */ "Prev",
21259      /*  67 */ "Next",
21260      /*  68 */ "Or",
21261      /*  69 */ "And",
21262      /*  70 */ "IdxInsert",
21263      /*  71 */ "IdxDelete",
21264      /*  72 */ "IdxRowid",
21265      /*  73 */ "IsNull",
21266      /*  74 */ "NotNull",
21267      /*  75 */ "Ne",
21268      /*  76 */ "Eq",
21269      /*  77 */ "Gt",
21270      /*  78 */ "Le",
21271      /*  79 */ "Lt",
21272      /*  80 */ "Ge",
21273      /*  81 */ "IdxLT",
21274      /*  82 */ "BitAnd",
21275      /*  83 */ "BitOr",
21276      /*  84 */ "ShiftLeft",
21277      /*  85 */ "ShiftRight",
21278      /*  86 */ "Add",
21279      /*  87 */ "Subtract",
21280      /*  88 */ "Multiply",
21281      /*  89 */ "Divide",
21282      /*  90 */ "Remainder",
21283      /*  91 */ "Concat",
21284      /*  92 */ "IdxGE",
21285      /*  93 */ "BitNot",
21286      /*  94 */ "String8",
21287      /*  95 */ "Destroy",
21288      /*  96 */ "Clear",
21289      /*  97 */ "CreateIndex",
21290      /*  98 */ "CreateTable",
21291      /*  99 */ "ParseSchema",
21292      /* 100 */ "LoadAnalysis",
21293      /* 101 */ "DropTable",
21294      /* 102 */ "DropIndex",
21295      /* 103 */ "DropTrigger",
21296      /* 104 */ "IntegrityCk",
21297      /* 105 */ "RowSetAdd",
21298      /* 106 */ "RowSetRead",
21299      /* 107 */ "RowSetTest",
21300      /* 108 */ "Program",
21301      /* 109 */ "Param",
21302      /* 110 */ "FkCounter",
21303      /* 111 */ "FkIfZero",
21304      /* 112 */ "MemMax",
21305      /* 113 */ "IfPos",
21306      /* 114 */ "IfNeg",
21307      /* 115 */ "IfZero",
21308      /* 116 */ "AggStep",
21309      /* 117 */ "AggFinal",
21310      /* 118 */ "Checkpoint",
21311      /* 119 */ "JournalMode",
21312      /* 120 */ "Vacuum",
21313      /* 121 */ "IncrVacuum",
21314      /* 122 */ "Expire",
21315      /* 123 */ "TableLock",
21316      /* 124 */ "VBegin",
21317      /* 125 */ "VCreate",
21318      /* 126 */ "VDestroy",
21319      /* 127 */ "VOpen",
21320      /* 128 */ "VFilter",
21321      /* 129 */ "VColumn",
21322      /* 130 */ "Real",
21323      /* 131 */ "VNext",
21324      /* 132 */ "VRename",
21325      /* 133 */ "VUpdate",
21326      /* 134 */ "Pagecount",
21327      /* 135 */ "Trace",
21328      /* 136 */ "Noop",
21329      /* 137 */ "Explain",
21330      /* 138 */ "NotUsed_138",
21331      /* 139 */ "NotUsed_139",
21332      /* 140 */ "NotUsed_140",
21333      /* 141 */ "ToText",
21334      /* 142 */ "ToBlob",
21335      /* 143 */ "ToNumeric",
21336      /* 144 */ "ToInt",
21337      /* 145 */ "ToReal",
21338   };
21339   return azName[i];
21340 }
21341 #endif
21342
21343 /************** End of opcodes.c *********************************************/
21344 /************** Begin file os_os2.c ******************************************/
21345 /*
21346 ** 2006 Feb 14
21347 **
21348 ** The author disclaims copyright to this source code.  In place of
21349 ** a legal notice, here is a blessing:
21350 **
21351 **    May you do good and not evil.
21352 **    May you find forgiveness for yourself and forgive others.
21353 **    May you share freely, never taking more than you give.
21354 **
21355 ******************************************************************************
21356 **
21357 ** This file contains code that is specific to OS/2.
21358 */
21359
21360
21361 #if SQLITE_OS_OS2
21362
21363 /*
21364 ** A Note About Memory Allocation:
21365 **
21366 ** This driver uses malloc()/free() directly rather than going through
21367 ** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
21368 ** are designed for use on embedded systems where memory is scarce and
21369 ** malloc failures happen frequently.  OS/2 does not typically run on
21370 ** embedded systems, and when it does the developers normally have bigger
21371 ** problems to worry about than running out of memory.  So there is not
21372 ** a compelling need to use the wrappers.
21373 **
21374 ** But there is a good reason to not use the wrappers.  If we use the
21375 ** wrappers then we will get simulated malloc() failures within this
21376 ** driver.  And that causes all kinds of problems for our tests.  We
21377 ** could enhance SQLite to deal with simulated malloc failures within
21378 ** the OS driver, but the code to deal with those failure would not
21379 ** be exercised on Linux (which does not need to malloc() in the driver)
21380 ** and so we would have difficulty writing coverage tests for that
21381 ** code.  Better to leave the code out, we think.
21382 **
21383 ** The point of this discussion is as follows:  When creating a new
21384 ** OS layer for an embedded system, if you use this file as an example,
21385 ** avoid the use of malloc()/free().  Those routines work ok on OS/2
21386 ** desktops but not so well in embedded systems.
21387 */
21388
21389 /*
21390 ** Macros used to determine whether or not to use threads.
21391 */
21392 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE
21393 # define SQLITE_OS2_THREADS 1
21394 #endif
21395
21396 /*
21397 ** Include code that is common to all os_*.c files
21398 */
21399 /************** Include os_common.h in the middle of os_os2.c ****************/
21400 /************** Begin file os_common.h ***************************************/
21401 /*
21402 ** 2004 May 22
21403 **
21404 ** The author disclaims copyright to this source code.  In place of
21405 ** a legal notice, here is a blessing:
21406 **
21407 **    May you do good and not evil.
21408 **    May you find forgiveness for yourself and forgive others.
21409 **    May you share freely, never taking more than you give.
21410 **
21411 ******************************************************************************
21412 **
21413 ** This file contains macros and a little bit of code that is common to
21414 ** all of the platform-specific files (os_*.c) and is #included into those
21415 ** files.
21416 **
21417 ** This file should be #included by the os_*.c files only.  It is not a
21418 ** general purpose header file.
21419 */
21420 #ifndef _OS_COMMON_H_
21421 #define _OS_COMMON_H_
21422
21423 /*
21424 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
21425 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
21426 ** switch.  The following code should catch this problem at compile-time.
21427 */
21428 #ifdef MEMORY_DEBUG
21429 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
21430 #endif
21431
21432 #ifdef SQLITE_DEBUG
21433 SQLITE_PRIVATE int sqlite3OSTrace = 0;
21434 #define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
21435 #else
21436 #define OSTRACE(X)
21437 #endif
21438
21439 /*
21440 ** Macros for performance tracing.  Normally turned off.  Only works
21441 ** on i486 hardware.
21442 */
21443 #ifdef SQLITE_PERFORMANCE_TRACE
21444
21445 /* 
21446 ** hwtime.h contains inline assembler code for implementing 
21447 ** high-performance timing routines.
21448 */
21449 /************** Include hwtime.h in the middle of os_common.h ****************/
21450 /************** Begin file hwtime.h ******************************************/
21451 /*
21452 ** 2008 May 27
21453 **
21454 ** The author disclaims copyright to this source code.  In place of
21455 ** a legal notice, here is a blessing:
21456 **
21457 **    May you do good and not evil.
21458 **    May you find forgiveness for yourself and forgive others.
21459 **    May you share freely, never taking more than you give.
21460 **
21461 ******************************************************************************
21462 **
21463 ** This file contains inline asm code for retrieving "high-performance"
21464 ** counters for x86 class CPUs.
21465 */
21466 #ifndef _HWTIME_H_
21467 #define _HWTIME_H_
21468
21469 /*
21470 ** The following routine only works on pentium-class (or newer) processors.
21471 ** It uses the RDTSC opcode to read the cycle count value out of the
21472 ** processor and returns that value.  This can be used for high-res
21473 ** profiling.
21474 */
21475 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
21476       (defined(i386) || defined(__i386__) || defined(_M_IX86))
21477
21478   #if defined(__GNUC__)
21479
21480   __inline__ sqlite_uint64 sqlite3Hwtime(void){
21481      unsigned int lo, hi;
21482      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
21483      return (sqlite_uint64)hi << 32 | lo;
21484   }
21485
21486   #elif defined(_MSC_VER)
21487
21488   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
21489      __asm {
21490         rdtsc
21491         ret       ; return value at EDX:EAX
21492      }
21493   }
21494
21495   #endif
21496
21497 #elif (defined(__GNUC__) && defined(__x86_64__))
21498
21499   __inline__ sqlite_uint64 sqlite3Hwtime(void){
21500       unsigned long val;
21501       __asm__ __volatile__ ("rdtsc" : "=A" (val));
21502       return val;
21503   }
21504  
21505 #elif (defined(__GNUC__) && defined(__ppc__))
21506
21507   __inline__ sqlite_uint64 sqlite3Hwtime(void){
21508       unsigned long long retval;
21509       unsigned long junk;
21510       __asm__ __volatile__ ("\n\
21511           1:      mftbu   %1\n\
21512                   mftb    %L0\n\
21513                   mftbu   %0\n\
21514                   cmpw    %0,%1\n\
21515                   bne     1b"
21516                   : "=r" (retval), "=r" (junk));
21517       return retval;
21518   }
21519
21520 #else
21521
21522   #error Need implementation of sqlite3Hwtime() for your platform.
21523
21524   /*
21525   ** To compile without implementing sqlite3Hwtime() for your platform,
21526   ** you can remove the above #error and use the following
21527   ** stub function.  You will lose timing support for many
21528   ** of the debugging and testing utilities, but it should at
21529   ** least compile and run.
21530   */
21531 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
21532
21533 #endif
21534
21535 #endif /* !defined(_HWTIME_H_) */
21536
21537 /************** End of hwtime.h **********************************************/
21538 /************** Continuing where we left off in os_common.h ******************/
21539
21540 static sqlite_uint64 g_start;
21541 static sqlite_uint64 g_elapsed;
21542 #define TIMER_START       g_start=sqlite3Hwtime()
21543 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
21544 #define TIMER_ELAPSED     g_elapsed
21545 #else
21546 #define TIMER_START
21547 #define TIMER_END
21548 #define TIMER_ELAPSED     ((sqlite_uint64)0)
21549 #endif
21550
21551 /*
21552 ** If we compile with the SQLITE_TEST macro set, then the following block
21553 ** of code will give us the ability to simulate a disk I/O error.  This
21554 ** is used for testing the I/O recovery logic.
21555 */
21556 #ifdef SQLITE_TEST
21557 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
21558 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
21559 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
21560 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
21561 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
21562 SQLITE_API int sqlite3_diskfull_pending = 0;
21563 SQLITE_API int sqlite3_diskfull = 0;
21564 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
21565 #define SimulateIOError(CODE)  \
21566   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
21567        || sqlite3_io_error_pending-- == 1 )  \
21568               { local_ioerr(); CODE; }
21569 static void local_ioerr(){
21570   IOTRACE(("IOERR\n"));
21571   sqlite3_io_error_hit++;
21572   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
21573 }
21574 #define SimulateDiskfullError(CODE) \
21575    if( sqlite3_diskfull_pending ){ \
21576      if( sqlite3_diskfull_pending == 1 ){ \
21577        local_ioerr(); \
21578        sqlite3_diskfull = 1; \
21579        sqlite3_io_error_hit = 1; \
21580        CODE; \
21581      }else{ \
21582        sqlite3_diskfull_pending--; \
21583      } \
21584    }
21585 #else
21586 #define SimulateIOErrorBenign(X)
21587 #define SimulateIOError(A)
21588 #define SimulateDiskfullError(A)
21589 #endif
21590
21591 /*
21592 ** When testing, keep a count of the number of open files.
21593 */
21594 #ifdef SQLITE_TEST
21595 SQLITE_API int sqlite3_open_file_count = 0;
21596 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
21597 #else
21598 #define OpenCounter(X)
21599 #endif
21600
21601 #endif /* !defined(_OS_COMMON_H_) */
21602
21603 /************** End of os_common.h *******************************************/
21604 /************** Continuing where we left off in os_os2.c *********************/
21605
21606 /*
21607 ** The os2File structure is subclass of sqlite3_file specific for the OS/2
21608 ** protability layer.
21609 */
21610 typedef struct os2File os2File;
21611 struct os2File {
21612   const sqlite3_io_methods *pMethod;  /* Always the first entry */
21613   HFILE h;                  /* Handle for accessing the file */
21614   char* pathToDel;          /* Name of file to delete on close, NULL if not */
21615   unsigned char locktype;   /* Type of lock currently held on this file */
21616 };
21617
21618 #define LOCK_TIMEOUT 10L /* the default locking timeout */
21619
21620 /*****************************************************************************
21621 ** The next group of routines implement the I/O methods specified
21622 ** by the sqlite3_io_methods object.
21623 ******************************************************************************/
21624
21625 /*
21626 ** Close a file.
21627 */
21628 static int os2Close( sqlite3_file *id ){
21629   APIRET rc = NO_ERROR;
21630   os2File *pFile;
21631   if( id && (pFile = (os2File*)id) != 0 ){
21632     OSTRACE(( "CLOSE %d\n", pFile->h ));
21633     rc = DosClose( pFile->h );
21634     pFile->locktype = NO_LOCK;
21635     if( pFile->pathToDel != NULL ){
21636       rc = DosForceDelete( (PSZ)pFile->pathToDel );
21637       free( pFile->pathToDel );
21638       pFile->pathToDel = NULL;
21639     }
21640     id = 0;
21641     OpenCounter( -1 );
21642   }
21643
21644   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
21645 }
21646
21647 /*
21648 ** Read data from a file into a buffer.  Return SQLITE_OK if all
21649 ** bytes were read successfully and SQLITE_IOERR if anything goes
21650 ** wrong.
21651 */
21652 static int os2Read(
21653   sqlite3_file *id,               /* File to read from */
21654   void *pBuf,                     /* Write content into this buffer */
21655   int amt,                        /* Number of bytes to read */
21656   sqlite3_int64 offset            /* Begin reading at this offset */
21657 ){
21658   ULONG fileLocation = 0L;
21659   ULONG got;
21660   os2File *pFile = (os2File*)id;
21661   assert( id!=0 );
21662   SimulateIOError( return SQLITE_IOERR_READ );
21663   OSTRACE(( "READ %d lock=%d\n", pFile->h, pFile->locktype ));
21664   if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
21665     return SQLITE_IOERR;
21666   }
21667   if( DosRead( pFile->h, pBuf, amt, &got ) != NO_ERROR ){
21668     return SQLITE_IOERR_READ;
21669   }
21670   if( got == (ULONG)amt )
21671     return SQLITE_OK;
21672   else {
21673     /* Unread portions of the input buffer must be zero-filled */
21674     memset(&((char*)pBuf)[got], 0, amt-got);
21675     return SQLITE_IOERR_SHORT_READ;
21676   }
21677 }
21678
21679 /*
21680 ** Write data from a buffer into a file.  Return SQLITE_OK on success
21681 ** or some other error code on failure.
21682 */
21683 static int os2Write(
21684   sqlite3_file *id,               /* File to write into */
21685   const void *pBuf,               /* The bytes to be written */
21686   int amt,                        /* Number of bytes to write */
21687   sqlite3_int64 offset            /* Offset into the file to begin writing at */
21688 ){
21689   ULONG fileLocation = 0L;
21690   APIRET rc = NO_ERROR;
21691   ULONG wrote;
21692   os2File *pFile = (os2File*)id;
21693   assert( id!=0 );
21694   SimulateIOError( return SQLITE_IOERR_WRITE );
21695   SimulateDiskfullError( return SQLITE_FULL );
21696   OSTRACE(( "WRITE %d lock=%d\n", pFile->h, pFile->locktype ));
21697   if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
21698     return SQLITE_IOERR;
21699   }
21700   assert( amt>0 );
21701   while( amt > 0 &&
21702          ( rc = DosWrite( pFile->h, (PVOID)pBuf, amt, &wrote ) ) == NO_ERROR &&
21703          wrote > 0
21704   ){
21705     amt -= wrote;
21706     pBuf = &((char*)pBuf)[wrote];
21707   }
21708
21709   return ( rc != NO_ERROR || amt > (int)wrote ) ? SQLITE_FULL : SQLITE_OK;
21710 }
21711
21712 /*
21713 ** Truncate an open file to a specified size
21714 */
21715 static int os2Truncate( sqlite3_file *id, i64 nByte ){
21716   APIRET rc = NO_ERROR;
21717   os2File *pFile = (os2File*)id;
21718   OSTRACE(( "TRUNCATE %d %lld\n", pFile->h, nByte ));
21719   SimulateIOError( return SQLITE_IOERR_TRUNCATE );
21720   rc = DosSetFileSize( pFile->h, nByte );
21721   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR_TRUNCATE;
21722 }
21723
21724 #ifdef SQLITE_TEST
21725 /*
21726 ** Count the number of fullsyncs and normal syncs.  This is used to test
21727 ** that syncs and fullsyncs are occuring at the right times.
21728 */
21729 SQLITE_API int sqlite3_sync_count = 0;
21730 SQLITE_API int sqlite3_fullsync_count = 0;
21731 #endif
21732
21733 /*
21734 ** Make sure all writes to a particular file are committed to disk.
21735 */
21736 static int os2Sync( sqlite3_file *id, int flags ){
21737   os2File *pFile = (os2File*)id;
21738   OSTRACE(( "SYNC %d lock=%d\n", pFile->h, pFile->locktype ));
21739 #ifdef SQLITE_TEST
21740   if( flags & SQLITE_SYNC_FULL){
21741     sqlite3_fullsync_count++;
21742   }
21743   sqlite3_sync_count++;
21744 #endif
21745   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
21746   ** no-op
21747   */
21748 #ifdef SQLITE_NO_SYNC
21749   UNUSED_PARAMETER(pFile);
21750   return SQLITE_OK;
21751 #else
21752   return DosResetBuffer( pFile->h ) == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
21753 #endif
21754 }
21755
21756 /*
21757 ** Determine the current size of a file in bytes
21758 */
21759 static int os2FileSize( sqlite3_file *id, sqlite3_int64 *pSize ){
21760   APIRET rc = NO_ERROR;
21761   FILESTATUS3 fsts3FileInfo;
21762   memset(&fsts3FileInfo, 0, sizeof(fsts3FileInfo));
21763   assert( id!=0 );
21764   SimulateIOError( return SQLITE_IOERR_FSTAT );
21765   rc = DosQueryFileInfo( ((os2File*)id)->h, FIL_STANDARD, &fsts3FileInfo, sizeof(FILESTATUS3) );
21766   if( rc == NO_ERROR ){
21767     *pSize = fsts3FileInfo.cbFile;
21768     return SQLITE_OK;
21769   }else{
21770     return SQLITE_IOERR_FSTAT;
21771   }
21772 }
21773
21774 /*
21775 ** Acquire a reader lock.
21776 */
21777 static int getReadLock( os2File *pFile ){
21778   FILELOCK  LockArea,
21779             UnlockArea;
21780   APIRET res;
21781   memset(&LockArea, 0, sizeof(LockArea));
21782   memset(&UnlockArea, 0, sizeof(UnlockArea));
21783   LockArea.lOffset = SHARED_FIRST;
21784   LockArea.lRange = SHARED_SIZE;
21785   UnlockArea.lOffset = 0L;
21786   UnlockArea.lRange = 0L;
21787   res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
21788   OSTRACE(( "GETREADLOCK %d res=%d\n", pFile->h, res ));
21789   return res;
21790 }
21791
21792 /*
21793 ** Undo a readlock
21794 */
21795 static int unlockReadLock( os2File *id ){
21796   FILELOCK  LockArea,
21797             UnlockArea;
21798   APIRET res;
21799   memset(&LockArea, 0, sizeof(LockArea));
21800   memset(&UnlockArea, 0, sizeof(UnlockArea));
21801   LockArea.lOffset = 0L;
21802   LockArea.lRange = 0L;
21803   UnlockArea.lOffset = SHARED_FIRST;
21804   UnlockArea.lRange = SHARED_SIZE;
21805   res = DosSetFileLocks( id->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
21806   OSTRACE(( "UNLOCK-READLOCK file handle=%d res=%d?\n", id->h, res ));
21807   return res;
21808 }
21809
21810 /*
21811 ** Lock the file with the lock specified by parameter locktype - one
21812 ** of the following:
21813 **
21814 **     (1) SHARED_LOCK
21815 **     (2) RESERVED_LOCK
21816 **     (3) PENDING_LOCK
21817 **     (4) EXCLUSIVE_LOCK
21818 **
21819 ** Sometimes when requesting one lock state, additional lock states
21820 ** are inserted in between.  The locking might fail on one of the later
21821 ** transitions leaving the lock state different from what it started but
21822 ** still short of its goal.  The following chart shows the allowed
21823 ** transitions and the inserted intermediate states:
21824 **
21825 **    UNLOCKED -> SHARED
21826 **    SHARED -> RESERVED
21827 **    SHARED -> (PENDING) -> EXCLUSIVE
21828 **    RESERVED -> (PENDING) -> EXCLUSIVE
21829 **    PENDING -> EXCLUSIVE
21830 **
21831 ** This routine will only increase a lock.  The os2Unlock() routine
21832 ** erases all locks at once and returns us immediately to locking level 0.
21833 ** It is not possible to lower the locking level one step at a time.  You
21834 ** must go straight to locking level 0.
21835 */
21836 static int os2Lock( sqlite3_file *id, int locktype ){
21837   int rc = SQLITE_OK;       /* Return code from subroutines */
21838   APIRET res = NO_ERROR;    /* Result of an OS/2 lock call */
21839   int newLocktype;       /* Set pFile->locktype to this value before exiting */
21840   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
21841   FILELOCK  LockArea,
21842             UnlockArea;
21843   os2File *pFile = (os2File*)id;
21844   memset(&LockArea, 0, sizeof(LockArea));
21845   memset(&UnlockArea, 0, sizeof(UnlockArea));
21846   assert( pFile!=0 );
21847   OSTRACE(( "LOCK %d %d was %d\n", pFile->h, locktype, pFile->locktype ));
21848
21849   /* If there is already a lock of this type or more restrictive on the
21850   ** os2File, do nothing. Don't use the end_lock: exit path, as
21851   ** sqlite3_mutex_enter() hasn't been called yet.
21852   */
21853   if( pFile->locktype>=locktype ){
21854     OSTRACE(( "LOCK %d %d ok (already held)\n", pFile->h, locktype ));
21855     return SQLITE_OK;
21856   }
21857
21858   /* Make sure the locking sequence is correct
21859   */
21860   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
21861   assert( locktype!=PENDING_LOCK );
21862   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
21863
21864   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
21865   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
21866   ** the PENDING_LOCK byte is temporary.
21867   */
21868   newLocktype = pFile->locktype;
21869   if( pFile->locktype==NO_LOCK
21870       || (locktype==EXCLUSIVE_LOCK && pFile->locktype==RESERVED_LOCK)
21871   ){
21872     LockArea.lOffset = PENDING_BYTE;
21873     LockArea.lRange = 1L;
21874     UnlockArea.lOffset = 0L;
21875     UnlockArea.lRange = 0L;
21876
21877     /* wait longer than LOCK_TIMEOUT here not to have to try multiple times */
21878     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 100L, 0L );
21879     if( res == NO_ERROR ){
21880       gotPendingLock = 1;
21881       OSTRACE(( "LOCK %d pending lock boolean set.  res=%d\n", pFile->h, res ));
21882     }
21883   }
21884
21885   /* Acquire a shared lock
21886   */
21887   if( locktype==SHARED_LOCK && res == NO_ERROR ){
21888     assert( pFile->locktype==NO_LOCK );
21889     res = getReadLock(pFile);
21890     if( res == NO_ERROR ){
21891       newLocktype = SHARED_LOCK;
21892     }
21893     OSTRACE(( "LOCK %d acquire shared lock. res=%d\n", pFile->h, res ));
21894   }
21895
21896   /* Acquire a RESERVED lock
21897   */
21898   if( locktype==RESERVED_LOCK && res == NO_ERROR ){
21899     assert( pFile->locktype==SHARED_LOCK );
21900     LockArea.lOffset = RESERVED_BYTE;
21901     LockArea.lRange = 1L;
21902     UnlockArea.lOffset = 0L;
21903     UnlockArea.lRange = 0L;
21904     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21905     if( res == NO_ERROR ){
21906       newLocktype = RESERVED_LOCK;
21907     }
21908     OSTRACE(( "LOCK %d acquire reserved lock. res=%d\n", pFile->h, res ));
21909   }
21910
21911   /* Acquire a PENDING lock
21912   */
21913   if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
21914     newLocktype = PENDING_LOCK;
21915     gotPendingLock = 0;
21916     OSTRACE(( "LOCK %d acquire pending lock. pending lock boolean unset.\n",
21917                pFile->h ));
21918   }
21919
21920   /* Acquire an EXCLUSIVE lock
21921   */
21922   if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
21923     assert( pFile->locktype>=SHARED_LOCK );
21924     res = unlockReadLock(pFile);
21925     OSTRACE(( "unreadlock = %d\n", res ));
21926     LockArea.lOffset = SHARED_FIRST;
21927     LockArea.lRange = SHARED_SIZE;
21928     UnlockArea.lOffset = 0L;
21929     UnlockArea.lRange = 0L;
21930     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21931     if( res == NO_ERROR ){
21932       newLocktype = EXCLUSIVE_LOCK;
21933     }else{
21934       OSTRACE(( "OS/2 error-code = %d\n", res ));
21935       getReadLock(pFile);
21936     }
21937     OSTRACE(( "LOCK %d acquire exclusive lock.  res=%d\n", pFile->h, res ));
21938   }
21939
21940   /* If we are holding a PENDING lock that ought to be released, then
21941   ** release it now.
21942   */
21943   if( gotPendingLock && locktype==SHARED_LOCK ){
21944     int r;
21945     LockArea.lOffset = 0L;
21946     LockArea.lRange = 0L;
21947     UnlockArea.lOffset = PENDING_BYTE;
21948     UnlockArea.lRange = 1L;
21949     r = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21950     OSTRACE(( "LOCK %d unlocking pending/is shared. r=%d\n", pFile->h, r ));
21951   }
21952
21953   /* Update the state of the lock has held in the file descriptor then
21954   ** return the appropriate result code.
21955   */
21956   if( res == NO_ERROR ){
21957     rc = SQLITE_OK;
21958   }else{
21959     OSTRACE(( "LOCK FAILED %d trying for %d but got %d\n", pFile->h,
21960               locktype, newLocktype ));
21961     rc = SQLITE_BUSY;
21962   }
21963   pFile->locktype = newLocktype;
21964   OSTRACE(( "LOCK %d now %d\n", pFile->h, pFile->locktype ));
21965   return rc;
21966 }
21967
21968 /*
21969 ** This routine checks if there is a RESERVED lock held on the specified
21970 ** file by this or any other process. If such a lock is held, return
21971 ** non-zero, otherwise zero.
21972 */
21973 static int os2CheckReservedLock( sqlite3_file *id, int *pOut ){
21974   int r = 0;
21975   os2File *pFile = (os2File*)id;
21976   assert( pFile!=0 );
21977   if( pFile->locktype>=RESERVED_LOCK ){
21978     r = 1;
21979     OSTRACE(( "TEST WR-LOCK %d %d (local)\n", pFile->h, r ));
21980   }else{
21981     FILELOCK  LockArea,
21982               UnlockArea;
21983     APIRET rc = NO_ERROR;
21984     memset(&LockArea, 0, sizeof(LockArea));
21985     memset(&UnlockArea, 0, sizeof(UnlockArea));
21986     LockArea.lOffset = RESERVED_BYTE;
21987     LockArea.lRange = 1L;
21988     UnlockArea.lOffset = 0L;
21989     UnlockArea.lRange = 0L;
21990     rc = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21991     OSTRACE(( "TEST WR-LOCK %d lock reserved byte rc=%d\n", pFile->h, rc ));
21992     if( rc == NO_ERROR ){
21993       APIRET rcu = NO_ERROR; /* return code for unlocking */
21994       LockArea.lOffset = 0L;
21995       LockArea.lRange = 0L;
21996       UnlockArea.lOffset = RESERVED_BYTE;
21997       UnlockArea.lRange = 1L;
21998       rcu = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21999       OSTRACE(( "TEST WR-LOCK %d unlock reserved byte r=%d\n", pFile->h, rcu ));
22000     }
22001     r = !(rc == NO_ERROR);
22002     OSTRACE(( "TEST WR-LOCK %d %d (remote)\n", pFile->h, r ));
22003   }
22004   *pOut = r;
22005   return SQLITE_OK;
22006 }
22007
22008 /*
22009 ** Lower the locking level on file descriptor id to locktype.  locktype
22010 ** must be either NO_LOCK or SHARED_LOCK.
22011 **
22012 ** If the locking level of the file descriptor is already at or below
22013 ** the requested locking level, this routine is a no-op.
22014 **
22015 ** It is not possible for this routine to fail if the second argument
22016 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
22017 ** might return SQLITE_IOERR;
22018 */
22019 static int os2Unlock( sqlite3_file *id, int locktype ){
22020   int type;
22021   os2File *pFile = (os2File*)id;
22022   APIRET rc = SQLITE_OK;
22023   APIRET res = NO_ERROR;
22024   FILELOCK  LockArea,
22025             UnlockArea;
22026   memset(&LockArea, 0, sizeof(LockArea));
22027   memset(&UnlockArea, 0, sizeof(UnlockArea));
22028   assert( pFile!=0 );
22029   assert( locktype<=SHARED_LOCK );
22030   OSTRACE(( "UNLOCK %d to %d was %d\n", pFile->h, locktype, pFile->locktype ));
22031   type = pFile->locktype;
22032   if( type>=EXCLUSIVE_LOCK ){
22033     LockArea.lOffset = 0L;
22034     LockArea.lRange = 0L;
22035     UnlockArea.lOffset = SHARED_FIRST;
22036     UnlockArea.lRange = SHARED_SIZE;
22037     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22038     OSTRACE(( "UNLOCK %d exclusive lock res=%d\n", pFile->h, res ));
22039     if( locktype==SHARED_LOCK && getReadLock(pFile) != NO_ERROR ){
22040       /* This should never happen.  We should always be able to
22041       ** reacquire the read lock */
22042       OSTRACE(( "UNLOCK %d to %d getReadLock() failed\n", pFile->h, locktype ));
22043       rc = SQLITE_IOERR_UNLOCK;
22044     }
22045   }
22046   if( type>=RESERVED_LOCK ){
22047     LockArea.lOffset = 0L;
22048     LockArea.lRange = 0L;
22049     UnlockArea.lOffset = RESERVED_BYTE;
22050     UnlockArea.lRange = 1L;
22051     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22052     OSTRACE(( "UNLOCK %d reserved res=%d\n", pFile->h, res ));
22053   }
22054   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
22055     res = unlockReadLock(pFile);
22056     OSTRACE(( "UNLOCK %d is %d want %d res=%d\n",
22057               pFile->h, type, locktype, res ));
22058   }
22059   if( type>=PENDING_LOCK ){
22060     LockArea.lOffset = 0L;
22061     LockArea.lRange = 0L;
22062     UnlockArea.lOffset = PENDING_BYTE;
22063     UnlockArea.lRange = 1L;
22064     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22065     OSTRACE(( "UNLOCK %d pending res=%d\n", pFile->h, res ));
22066   }
22067   pFile->locktype = locktype;
22068   OSTRACE(( "UNLOCK %d now %d\n", pFile->h, pFile->locktype ));
22069   return rc;
22070 }
22071
22072 /*
22073 ** Control and query of the open file handle.
22074 */
22075 static int os2FileControl(sqlite3_file *id, int op, void *pArg){
22076   switch( op ){
22077     case SQLITE_FCNTL_LOCKSTATE: {
22078       *(int*)pArg = ((os2File*)id)->locktype;
22079       OSTRACE(( "FCNTL_LOCKSTATE %d lock=%d\n",
22080                 ((os2File*)id)->h, ((os2File*)id)->locktype ));
22081       return SQLITE_OK;
22082     }
22083   }
22084   return SQLITE_ERROR;
22085 }
22086
22087 /*
22088 ** Return the sector size in bytes of the underlying block device for
22089 ** the specified file. This is almost always 512 bytes, but may be
22090 ** larger for some devices.
22091 **
22092 ** SQLite code assumes this function cannot fail. It also assumes that
22093 ** if two files are created in the same file-system directory (i.e.
22094 ** a database and its journal file) that the sector size will be the
22095 ** same for both.
22096 */
22097 static int os2SectorSize(sqlite3_file *id){
22098   return SQLITE_DEFAULT_SECTOR_SIZE;
22099 }
22100
22101 /*
22102 ** Return a vector of device characteristics.
22103 */
22104 static int os2DeviceCharacteristics(sqlite3_file *id){
22105   return 0;
22106 }
22107
22108
22109 /*
22110 ** Character set conversion objects used by conversion routines.
22111 */
22112 static UconvObject ucUtf8 = NULL; /* convert between UTF-8 and UCS-2 */
22113 static UconvObject uclCp = NULL;  /* convert between local codepage and UCS-2 */
22114
22115 /*
22116 ** Helper function to initialize the conversion objects from and to UTF-8.
22117 */
22118 static void initUconvObjects( void ){
22119   if( UniCreateUconvObject( UTF_8, &ucUtf8 ) != ULS_SUCCESS )
22120     ucUtf8 = NULL;
22121   if ( UniCreateUconvObject( (UniChar *)L"@path=yes", &uclCp ) != ULS_SUCCESS )
22122     uclCp = NULL;
22123 }
22124
22125 /*
22126 ** Helper function to free the conversion objects from and to UTF-8.
22127 */
22128 static void freeUconvObjects( void ){
22129   if ( ucUtf8 )
22130     UniFreeUconvObject( ucUtf8 );
22131   if ( uclCp )
22132     UniFreeUconvObject( uclCp );
22133   ucUtf8 = NULL;
22134   uclCp = NULL;
22135 }
22136
22137 /*
22138 ** Helper function to convert UTF-8 filenames to local OS/2 codepage.
22139 ** The two-step process: first convert the incoming UTF-8 string
22140 ** into UCS-2 and then from UCS-2 to the current codepage.
22141 ** The returned char pointer has to be freed.
22142 */
22143 static char *convertUtf8PathToCp( const char *in ){
22144   UniChar tempPath[CCHMAXPATH];
22145   char *out = (char *)calloc( CCHMAXPATH, 1 );
22146
22147   if( !out )
22148     return NULL;
22149
22150   if( !ucUtf8 || !uclCp )
22151     initUconvObjects();
22152
22153   /* determine string for the conversion of UTF-8 which is CP1208 */
22154   if( UniStrToUcs( ucUtf8, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
22155     return out; /* if conversion fails, return the empty string */
22156
22157   /* conversion for current codepage which can be used for paths */
22158   UniStrFromUcs( uclCp, out, tempPath, CCHMAXPATH );
22159
22160   return out;
22161 }
22162
22163 /*
22164 ** Helper function to convert filenames from local codepage to UTF-8.
22165 ** The two-step process: first convert the incoming codepage-specific
22166 ** string into UCS-2 and then from UCS-2 to the codepage of UTF-8.
22167 ** The returned char pointer has to be freed.
22168 **
22169 ** This function is non-static to be able to use this in shell.c and
22170 ** similar applications that take command line arguments.
22171 */
22172 char *convertCpPathToUtf8( const char *in ){
22173   UniChar tempPath[CCHMAXPATH];
22174   char *out = (char *)calloc( CCHMAXPATH, 1 );
22175
22176   if( !out )
22177     return NULL;
22178
22179   if( !ucUtf8 || !uclCp )
22180     initUconvObjects();
22181
22182   /* conversion for current codepage which can be used for paths */
22183   if( UniStrToUcs( uclCp, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
22184     return out; /* if conversion fails, return the empty string */
22185
22186   /* determine string for the conversion of UTF-8 which is CP1208 */
22187   UniStrFromUcs( ucUtf8, out, tempPath, CCHMAXPATH );
22188
22189   return out;
22190 }
22191
22192 /*
22193 ** This vector defines all the methods that can operate on an
22194 ** sqlite3_file for os2.
22195 */
22196 static const sqlite3_io_methods os2IoMethod = {
22197   1,                        /* iVersion */
22198   os2Close,
22199   os2Read,
22200   os2Write,
22201   os2Truncate,
22202   os2Sync,
22203   os2FileSize,
22204   os2Lock,
22205   os2Unlock,
22206   os2CheckReservedLock,
22207   os2FileControl,
22208   os2SectorSize,
22209   os2DeviceCharacteristics
22210 };
22211
22212 /***************************************************************************
22213 ** Here ends the I/O methods that form the sqlite3_io_methods object.
22214 **
22215 ** The next block of code implements the VFS methods.
22216 ****************************************************************************/
22217
22218 /*
22219 ** Create a temporary file name in zBuf.  zBuf must be big enough to
22220 ** hold at pVfs->mxPathname characters.
22221 */
22222 static int getTempname(int nBuf, char *zBuf ){
22223   static const unsigned char zChars[] =
22224     "abcdefghijklmnopqrstuvwxyz"
22225     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
22226     "0123456789";
22227   int i, j;
22228   char zTempPathBuf[3];
22229   PSZ zTempPath = (PSZ)&zTempPathBuf;
22230   if( sqlite3_temp_directory ){
22231     zTempPath = sqlite3_temp_directory;
22232   }else{
22233     if( DosScanEnv( (PSZ)"TEMP", &zTempPath ) ){
22234       if( DosScanEnv( (PSZ)"TMP", &zTempPath ) ){
22235         if( DosScanEnv( (PSZ)"TMPDIR", &zTempPath ) ){
22236            ULONG ulDriveNum = 0, ulDriveMap = 0;
22237            DosQueryCurrentDisk( &ulDriveNum, &ulDriveMap );
22238            sprintf( (char*)zTempPath, "%c:", (char)( 'A' + ulDriveNum - 1 ) );
22239         }
22240       }
22241     }
22242   }
22243   /* Strip off a trailing slashes or backslashes, otherwise we would get *
22244    * multiple (back)slashes which causes DosOpen() to fail.              *
22245    * Trailing spaces are not allowed, either.                            */
22246   j = sqlite3Strlen30(zTempPath);
22247   while( j > 0 && ( zTempPath[j-1] == '\\' || zTempPath[j-1] == '/'
22248                     || zTempPath[j-1] == ' ' ) ){
22249     j--;
22250   }
22251   zTempPath[j] = '\0';
22252   if( !sqlite3_temp_directory ){
22253     char *zTempPathUTF = convertCpPathToUtf8( zTempPath );
22254     sqlite3_snprintf( nBuf-30, zBuf,
22255                       "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPathUTF );
22256     free( zTempPathUTF );
22257   }else{
22258     sqlite3_snprintf( nBuf-30, zBuf,
22259                       "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath );
22260   }
22261   j = sqlite3Strlen30( zBuf );
22262   sqlite3_randomness( 20, &zBuf[j] );
22263   for( i = 0; i < 20; i++, j++ ){
22264     zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
22265   }
22266   zBuf[j] = 0;
22267   OSTRACE(( "TEMP FILENAME: %s\n", zBuf ));
22268   return SQLITE_OK;
22269 }
22270
22271
22272 /*
22273 ** Turn a relative pathname into a full pathname.  Write the full
22274 ** pathname into zFull[].  zFull[] will be at least pVfs->mxPathname
22275 ** bytes in size.
22276 */
22277 static int os2FullPathname(
22278   sqlite3_vfs *pVfs,          /* Pointer to vfs object */
22279   const char *zRelative,      /* Possibly relative input path */
22280   int nFull,                  /* Size of output buffer in bytes */
22281   char *zFull                 /* Output buffer */
22282 ){
22283   char *zRelativeCp = convertUtf8PathToCp( zRelative );
22284   char zFullCp[CCHMAXPATH] = "\0";
22285   char *zFullUTF;
22286   APIRET rc = DosQueryPathInfo( zRelativeCp, FIL_QUERYFULLNAME, zFullCp,
22287                                 CCHMAXPATH );
22288   free( zRelativeCp );
22289   zFullUTF = convertCpPathToUtf8( zFullCp );
22290   sqlite3_snprintf( nFull, zFull, zFullUTF );
22291   free( zFullUTF );
22292   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
22293 }
22294
22295
22296 /*
22297 ** Open a file.
22298 */
22299 static int os2Open(
22300   sqlite3_vfs *pVfs,            /* Not used */
22301   const char *zName,            /* Name of the file */
22302   sqlite3_file *id,             /* Write the SQLite file handle here */
22303   int flags,                    /* Open mode flags */
22304   int *pOutFlags                /* Status return flags */
22305 ){
22306   HFILE h;
22307   ULONG ulFileAttribute = FILE_NORMAL;
22308   ULONG ulOpenFlags = 0;
22309   ULONG ulOpenMode = 0;
22310   os2File *pFile = (os2File*)id;
22311   APIRET rc = NO_ERROR;
22312   ULONG ulAction;
22313   char *zNameCp;
22314   char zTmpname[CCHMAXPATH+1];    /* Buffer to hold name of temp file */
22315
22316   /* If the second argument to this function is NULL, generate a 
22317   ** temporary file name to use 
22318   */
22319   if( !zName ){
22320     int rc = getTempname(CCHMAXPATH+1, zTmpname);
22321     if( rc!=SQLITE_OK ){
22322       return rc;
22323     }
22324     zName = zTmpname;
22325   }
22326
22327
22328   memset( pFile, 0, sizeof(*pFile) );
22329
22330   OSTRACE(( "OPEN want %d\n", flags ));
22331
22332   if( flags & SQLITE_OPEN_READWRITE ){
22333     ulOpenMode |= OPEN_ACCESS_READWRITE;
22334     OSTRACE(( "OPEN read/write\n" ));
22335   }else{
22336     ulOpenMode |= OPEN_ACCESS_READONLY;
22337     OSTRACE(( "OPEN read only\n" ));
22338   }
22339
22340   if( flags & SQLITE_OPEN_CREATE ){
22341     ulOpenFlags |= OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_CREATE_IF_NEW;
22342     OSTRACE(( "OPEN open new/create\n" ));
22343   }else{
22344     ulOpenFlags |= OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_FAIL_IF_NEW;
22345     OSTRACE(( "OPEN open existing\n" ));
22346   }
22347
22348   if( flags & SQLITE_OPEN_MAIN_DB ){
22349     ulOpenMode |= OPEN_SHARE_DENYNONE;
22350     OSTRACE(( "OPEN share read/write\n" ));
22351   }else{
22352     ulOpenMode |= OPEN_SHARE_DENYWRITE;
22353     OSTRACE(( "OPEN share read only\n" ));
22354   }
22355
22356   if( flags & SQLITE_OPEN_DELETEONCLOSE ){
22357     char pathUtf8[CCHMAXPATH];
22358 #ifdef NDEBUG /* when debugging we want to make sure it is deleted */
22359     ulFileAttribute = FILE_HIDDEN;
22360 #endif
22361     os2FullPathname( pVfs, zName, CCHMAXPATH, pathUtf8 );
22362     pFile->pathToDel = convertUtf8PathToCp( pathUtf8 );
22363     OSTRACE(( "OPEN hidden/delete on close file attributes\n" ));
22364   }else{
22365     pFile->pathToDel = NULL;
22366     OSTRACE(( "OPEN normal file attribute\n" ));
22367   }
22368
22369   /* always open in random access mode for possibly better speed */
22370   ulOpenMode |= OPEN_FLAGS_RANDOM;
22371   ulOpenMode |= OPEN_FLAGS_FAIL_ON_ERROR;
22372   ulOpenMode |= OPEN_FLAGS_NOINHERIT;
22373
22374   zNameCp = convertUtf8PathToCp( zName );
22375   rc = DosOpen( (PSZ)zNameCp,
22376                 &h,
22377                 &ulAction,
22378                 0L,
22379                 ulFileAttribute,
22380                 ulOpenFlags,
22381                 ulOpenMode,
22382                 (PEAOP2)NULL );
22383   free( zNameCp );
22384   if( rc != NO_ERROR ){
22385     OSTRACE(( "OPEN Invalid handle rc=%d: zName=%s, ulAction=%#lx, ulAttr=%#lx, ulFlags=%#lx, ulMode=%#lx\n",
22386               rc, zName, ulAction, ulFileAttribute, ulOpenFlags, ulOpenMode ));
22387     if( pFile->pathToDel )
22388       free( pFile->pathToDel );
22389     pFile->pathToDel = NULL;
22390     if( flags & SQLITE_OPEN_READWRITE ){
22391       OSTRACE(( "OPEN %d Invalid handle\n",
22392                 ((flags | SQLITE_OPEN_READONLY) & ~SQLITE_OPEN_READWRITE) ));
22393       return os2Open( pVfs, zName, id,
22394                       ((flags | SQLITE_OPEN_READONLY) & ~SQLITE_OPEN_READWRITE),
22395                       pOutFlags );
22396     }else{
22397       return SQLITE_CANTOPEN;
22398     }
22399   }
22400
22401   if( pOutFlags ){
22402     *pOutFlags = flags & SQLITE_OPEN_READWRITE ? SQLITE_OPEN_READWRITE : SQLITE_OPEN_READONLY;
22403   }
22404
22405   pFile->pMethod = &os2IoMethod;
22406   pFile->h = h;
22407   OpenCounter(+1);
22408   OSTRACE(( "OPEN %d pOutFlags=%d\n", pFile->h, pOutFlags ));
22409   return SQLITE_OK;
22410 }
22411
22412 /*
22413 ** Delete the named file.
22414 */
22415 static int os2Delete(
22416   sqlite3_vfs *pVfs,                     /* Not used on os2 */
22417   const char *zFilename,                 /* Name of file to delete */
22418   int syncDir                            /* Not used on os2 */
22419 ){
22420   APIRET rc = NO_ERROR;
22421   char *zFilenameCp = convertUtf8PathToCp( zFilename );
22422   SimulateIOError( return SQLITE_IOERR_DELETE );
22423   rc = DosDelete( (PSZ)zFilenameCp );
22424   free( zFilenameCp );
22425   OSTRACE(( "DELETE \"%s\"\n", zFilename ));
22426   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR_DELETE;
22427 }
22428
22429 /*
22430 ** Check the existance and status of a file.
22431 */
22432 static int os2Access(
22433   sqlite3_vfs *pVfs,        /* Not used on os2 */
22434   const char *zFilename,    /* Name of file to check */
22435   int flags,                /* Type of test to make on this file */
22436   int *pOut                 /* Write results here */
22437 ){
22438   FILESTATUS3 fsts3ConfigInfo;
22439   APIRET rc = NO_ERROR;
22440   char *zFilenameCp = convertUtf8PathToCp( zFilename );
22441
22442   memset( &fsts3ConfigInfo, 0, sizeof(fsts3ConfigInfo) );
22443   rc = DosQueryPathInfo( (PSZ)zFilenameCp, FIL_STANDARD,
22444                          &fsts3ConfigInfo, sizeof(FILESTATUS3) );
22445   free( zFilenameCp );
22446   OSTRACE(( "ACCESS fsts3ConfigInfo.attrFile=%d flags=%d rc=%d\n",
22447             fsts3ConfigInfo.attrFile, flags, rc ));
22448   switch( flags ){
22449     case SQLITE_ACCESS_READ:
22450     case SQLITE_ACCESS_EXISTS:
22451       rc = (rc == NO_ERROR);
22452       OSTRACE(( "ACCESS %s access of read and exists  rc=%d\n", zFilename, rc));
22453       break;
22454     case SQLITE_ACCESS_READWRITE:
22455       rc = (rc == NO_ERROR) && ( (fsts3ConfigInfo.attrFile & FILE_READONLY) == 0 );
22456       OSTRACE(( "ACCESS %s access of read/write  rc=%d\n", zFilename, rc ));
22457       break;
22458     default:
22459       assert( !"Invalid flags argument" );
22460   }
22461   *pOut = rc;
22462   return SQLITE_OK;
22463 }
22464
22465
22466 #ifndef SQLITE_OMIT_LOAD_EXTENSION
22467 /*
22468 ** Interfaces for opening a shared library, finding entry points
22469 ** within the shared library, and closing the shared library.
22470 */
22471 /*
22472 ** Interfaces for opening a shared library, finding entry points
22473 ** within the shared library, and closing the shared library.
22474 */
22475 static void *os2DlOpen(sqlite3_vfs *pVfs, const char *zFilename){
22476   UCHAR loadErr[256];
22477   HMODULE hmod;
22478   APIRET rc;
22479   char *zFilenameCp = convertUtf8PathToCp(zFilename);
22480   rc = DosLoadModule((PSZ)loadErr, sizeof(loadErr), zFilenameCp, &hmod);
22481   free(zFilenameCp);
22482   return rc != NO_ERROR ? 0 : (void*)hmod;
22483 }
22484 /*
22485 ** A no-op since the error code is returned on the DosLoadModule call.
22486 ** os2Dlopen returns zero if DosLoadModule is not successful.
22487 */
22488 static void os2DlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
22489 /* no-op */
22490 }
22491 static void *os2DlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol){
22492   PFN pfn;
22493   APIRET rc;
22494   rc = DosQueryProcAddr((HMODULE)pHandle, 0L, zSymbol, &pfn);
22495   if( rc != NO_ERROR ){
22496     /* if the symbol itself was not found, search again for the same
22497      * symbol with an extra underscore, that might be needed depending
22498      * on the calling convention */
22499     char _zSymbol[256] = "_";
22500     strncat(_zSymbol, zSymbol, 255);
22501     rc = DosQueryProcAddr((HMODULE)pHandle, 0L, _zSymbol, &pfn);
22502   }
22503   return rc != NO_ERROR ? 0 : (void*)pfn;
22504 }
22505 static void os2DlClose(sqlite3_vfs *pVfs, void *pHandle){
22506   DosFreeModule((HMODULE)pHandle);
22507 }
22508 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
22509   #define os2DlOpen 0
22510   #define os2DlError 0
22511   #define os2DlSym 0
22512   #define os2DlClose 0
22513 #endif
22514
22515
22516 /*
22517 ** Write up to nBuf bytes of randomness into zBuf.
22518 */
22519 static int os2Randomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf ){
22520   int n = 0;
22521 #if defined(SQLITE_TEST)
22522   n = nBuf;
22523   memset(zBuf, 0, nBuf);
22524 #else
22525   int sizeofULong = sizeof(ULONG);
22526   if( (int)sizeof(DATETIME) <= nBuf - n ){
22527     DATETIME x;
22528     DosGetDateTime(&x);
22529     memcpy(&zBuf[n], &x, sizeof(x));
22530     n += sizeof(x);
22531   }
22532
22533   if( sizeofULong <= nBuf - n ){
22534     PPIB ppib;
22535     DosGetInfoBlocks(NULL, &ppib);
22536     memcpy(&zBuf[n], &ppib->pib_ulpid, sizeofULong);
22537     n += sizeofULong;
22538   }
22539
22540   if( sizeofULong <= nBuf - n ){
22541     PTIB ptib;
22542     DosGetInfoBlocks(&ptib, NULL);
22543     memcpy(&zBuf[n], &ptib->tib_ptib2->tib2_ultid, sizeofULong);
22544     n += sizeofULong;
22545   }
22546
22547   /* if we still haven't filled the buffer yet the following will */
22548   /* grab everything once instead of making several calls for a single item */
22549   if( sizeofULong <= nBuf - n ){
22550     ULONG ulSysInfo[QSV_MAX];
22551     DosQuerySysInfo(1L, QSV_MAX, ulSysInfo, sizeofULong * QSV_MAX);
22552
22553     memcpy(&zBuf[n], &ulSysInfo[QSV_MS_COUNT - 1], sizeofULong);
22554     n += sizeofULong;
22555
22556     if( sizeofULong <= nBuf - n ){
22557       memcpy(&zBuf[n], &ulSysInfo[QSV_TIMER_INTERVAL - 1], sizeofULong);
22558       n += sizeofULong;
22559     }
22560     if( sizeofULong <= nBuf - n ){
22561       memcpy(&zBuf[n], &ulSysInfo[QSV_TIME_LOW - 1], sizeofULong);
22562       n += sizeofULong;
22563     }
22564     if( sizeofULong <= nBuf - n ){
22565       memcpy(&zBuf[n], &ulSysInfo[QSV_TIME_HIGH - 1], sizeofULong);
22566       n += sizeofULong;
22567     }
22568     if( sizeofULong <= nBuf - n ){
22569       memcpy(&zBuf[n], &ulSysInfo[QSV_TOTAVAILMEM - 1], sizeofULong);
22570       n += sizeofULong;
22571     }
22572   }
22573 #endif
22574
22575   return n;
22576 }
22577
22578 /*
22579 ** Sleep for a little while.  Return the amount of time slept.
22580 ** The argument is the number of microseconds we want to sleep.
22581 ** The return value is the number of microseconds of sleep actually
22582 ** requested from the underlying operating system, a number which
22583 ** might be greater than or equal to the argument, but not less
22584 ** than the argument.
22585 */
22586 static int os2Sleep( sqlite3_vfs *pVfs, int microsec ){
22587   DosSleep( (microsec/1000) );
22588   return microsec;
22589 }
22590
22591 /*
22592 ** The following variable, if set to a non-zero value, becomes the result
22593 ** returned from sqlite3OsCurrentTime().  This is used for testing.
22594 */
22595 #ifdef SQLITE_TEST
22596 SQLITE_API int sqlite3_current_time = 0;
22597 #endif
22598
22599 /*
22600 ** Find the current time (in Universal Coordinated Time).  Write the
22601 ** current time and date as a Julian Day number into *prNow and
22602 ** return 0.  Return 1 if the time and date cannot be found.
22603 */
22604 int os2CurrentTime( sqlite3_vfs *pVfs, double *prNow ){
22605   double now;
22606   SHORT minute; /* needs to be able to cope with negative timezone offset */
22607   USHORT second, hour,
22608          day, month, year;
22609   DATETIME dt;
22610   DosGetDateTime( &dt );
22611   second = (USHORT)dt.seconds;
22612   minute = (SHORT)dt.minutes + dt.timezone;
22613   hour = (USHORT)dt.hours;
22614   day = (USHORT)dt.day;
22615   month = (USHORT)dt.month;
22616   year = (USHORT)dt.year;
22617
22618   /* Calculations from http://www.astro.keele.ac.uk/~rno/Astronomy/hjd.html
22619      http://www.astro.keele.ac.uk/~rno/Astronomy/hjd-0.1.c */
22620   /* Calculate the Julian days */
22621   now = day - 32076 +
22622     1461*(year + 4800 + (month - 14)/12)/4 +
22623     367*(month - 2 - (month - 14)/12*12)/12 -
22624     3*((year + 4900 + (month - 14)/12)/100)/4;
22625
22626   /* Add the fractional hours, mins and seconds */
22627   now += (hour + 12.0)/24.0;
22628   now += minute/1440.0;
22629   now += second/86400.0;
22630   *prNow = now;
22631 #ifdef SQLITE_TEST
22632   if( sqlite3_current_time ){
22633     *prNow = sqlite3_current_time/86400.0 + 2440587.5;
22634   }
22635 #endif
22636   return 0;
22637 }
22638
22639 static int os2GetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
22640   return 0;
22641 }
22642
22643 /*
22644 ** Initialize and deinitialize the operating system interface.
22645 */
22646 SQLITE_API int sqlite3_os_init(void){
22647   static sqlite3_vfs os2Vfs = {
22648     1,                 /* iVersion */
22649     sizeof(os2File),   /* szOsFile */
22650     CCHMAXPATH,        /* mxPathname */
22651     0,                 /* pNext */
22652     "os2",             /* zName */
22653     0,                 /* pAppData */
22654
22655     os2Open,           /* xOpen */
22656     os2Delete,         /* xDelete */
22657     os2Access,         /* xAccess */
22658     os2FullPathname,   /* xFullPathname */
22659     os2DlOpen,         /* xDlOpen */
22660     os2DlError,        /* xDlError */
22661     os2DlSym,          /* xDlSym */
22662     os2DlClose,        /* xDlClose */
22663     os2Randomness,     /* xRandomness */
22664     os2Sleep,          /* xSleep */
22665     os2CurrentTime,    /* xCurrentTime */
22666     os2GetLastError,   /* xGetLastError */
22667   };
22668   sqlite3_vfs_register(&os2Vfs, 1);
22669   initUconvObjects();
22670   return SQLITE_OK;
22671 }
22672 SQLITE_API int sqlite3_os_end(void){
22673   freeUconvObjects();
22674   return SQLITE_OK;
22675 }
22676
22677 #endif /* SQLITE_OS_OS2 */
22678
22679 /************** End of os_os2.c **********************************************/
22680 /************** Begin file os_unix.c *****************************************/
22681 /*
22682 ** 2004 May 22
22683 **
22684 ** The author disclaims copyright to this source code.  In place of
22685 ** a legal notice, here is a blessing:
22686 **
22687 **    May you do good and not evil.
22688 **    May you find forgiveness for yourself and forgive others.
22689 **    May you share freely, never taking more than you give.
22690 **
22691 ******************************************************************************
22692 **
22693 ** This file contains the VFS implementation for unix-like operating systems
22694 ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
22695 **
22696 ** There are actually several different VFS implementations in this file.
22697 ** The differences are in the way that file locking is done.  The default
22698 ** implementation uses Posix Advisory Locks.  Alternative implementations
22699 ** use flock(), dot-files, various proprietary locking schemas, or simply
22700 ** skip locking all together.
22701 **
22702 ** This source file is organized into divisions where the logic for various
22703 ** subfunctions is contained within the appropriate division.  PLEASE
22704 ** KEEP THE STRUCTURE OF THIS FILE INTACT.  New code should be placed
22705 ** in the correct division and should be clearly labeled.
22706 **
22707 ** The layout of divisions is as follows:
22708 **
22709 **   *  General-purpose declarations and utility functions.
22710 **   *  Unique file ID logic used by VxWorks.
22711 **   *  Various locking primitive implementations (all except proxy locking):
22712 **      + for Posix Advisory Locks
22713 **      + for no-op locks
22714 **      + for dot-file locks
22715 **      + for flock() locking
22716 **      + for named semaphore locks (VxWorks only)
22717 **      + for AFP filesystem locks (MacOSX only)
22718 **   *  sqlite3_file methods not associated with locking.
22719 **   *  Definitions of sqlite3_io_methods objects for all locking
22720 **      methods plus "finder" functions for each locking method.
22721 **   *  sqlite3_vfs method implementations.
22722 **   *  Locking primitives for the proxy uber-locking-method. (MacOSX only)
22723 **   *  Definitions of sqlite3_vfs objects for all locking methods
22724 **      plus implementations of sqlite3_os_init() and sqlite3_os_end().
22725 */
22726 #if SQLITE_OS_UNIX              /* This file is used on unix only */
22727
22728 /*
22729 ** There are various methods for file locking used for concurrency
22730 ** control:
22731 **
22732 **   1. POSIX locking (the default),
22733 **   2. No locking,
22734 **   3. Dot-file locking,
22735 **   4. flock() locking,
22736 **   5. AFP locking (OSX only),
22737 **   6. Named POSIX semaphores (VXWorks only),
22738 **   7. proxy locking. (OSX only)
22739 **
22740 ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
22741 ** is defined to 1.  The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
22742 ** selection of the appropriate locking style based on the filesystem
22743 ** where the database is located.  
22744 */
22745 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
22746 #  if defined(__APPLE__)
22747 #    define SQLITE_ENABLE_LOCKING_STYLE 1
22748 #  else
22749 #    define SQLITE_ENABLE_LOCKING_STYLE 0
22750 #  endif
22751 #endif
22752
22753 /*
22754 ** Define the OS_VXWORKS pre-processor macro to 1 if building on 
22755 ** vxworks, or 0 otherwise.
22756 */
22757 #ifndef OS_VXWORKS
22758 #  if defined(__RTP__) || defined(_WRS_KERNEL)
22759 #    define OS_VXWORKS 1
22760 #  else
22761 #    define OS_VXWORKS 0
22762 #  endif
22763 #endif
22764
22765 /*
22766 ** These #defines should enable >2GB file support on Posix if the
22767 ** underlying operating system supports it.  If the OS lacks
22768 ** large file support, these should be no-ops.
22769 **
22770 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
22771 ** on the compiler command line.  This is necessary if you are compiling
22772 ** on a recent machine (ex: RedHat 7.2) but you want your code to work
22773 ** on an older machine (ex: RedHat 6.0).  If you compile on RedHat 7.2
22774 ** without this option, LFS is enable.  But LFS does not exist in the kernel
22775 ** in RedHat 6.0, so the code won't work.  Hence, for maximum binary
22776 ** portability you should omit LFS.
22777 **
22778 ** The previous paragraph was written in 2005.  (This paragraph is written
22779 ** on 2008-11-28.) These days, all Linux kernels support large files, so
22780 ** you should probably leave LFS enabled.  But some embedded platforms might
22781 ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
22782 */
22783 #ifndef SQLITE_DISABLE_LFS
22784 # define _LARGE_FILE       1
22785 # ifndef _FILE_OFFSET_BITS
22786 #   define _FILE_OFFSET_BITS 64
22787 # endif
22788 # define _LARGEFILE_SOURCE 1
22789 #endif
22790
22791 /*
22792 ** standard include files.
22793 */
22794 #include <sys/types.h>
22795 #include <sys/stat.h>
22796 #include <fcntl.h>
22797 #include <unistd.h>
22798 #include <sys/time.h>
22799 #include <errno.h>
22800 #include <sys/mman.h>
22801
22802 #if SQLITE_ENABLE_LOCKING_STYLE
22803 # include <sys/ioctl.h>
22804 # if OS_VXWORKS
22805 #  include <semaphore.h>
22806 #  include <limits.h>
22807 # else
22808 #  include <sys/file.h>
22809 #  include <sys/param.h>
22810 # endif
22811 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
22812
22813 #if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
22814 # include <sys/mount.h>
22815 #endif
22816
22817 /*
22818 ** Allowed values of unixFile.fsFlags
22819 */
22820 #define SQLITE_FSFLAGS_IS_MSDOS     0x1
22821
22822 /*
22823 ** If we are to be thread-safe, include the pthreads header and define
22824 ** the SQLITE_UNIX_THREADS macro.
22825 */
22826 #if SQLITE_THREADSAFE
22827 # define SQLITE_UNIX_THREADS 1
22828 #endif
22829
22830 /*
22831 ** Default permissions when creating a new file
22832 */
22833 #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
22834 # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
22835 #endif
22836
22837 /*
22838  ** Default permissions when creating auto proxy dir
22839  */
22840 #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
22841 # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
22842 #endif
22843
22844 /*
22845 ** Maximum supported path-length.
22846 */
22847 #define MAX_PATHNAME 512
22848
22849 /*
22850 ** Only set the lastErrno if the error code is a real error and not 
22851 ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
22852 */
22853 #define IS_LOCK_ERROR(x)  ((x != SQLITE_OK) && (x != SQLITE_BUSY))
22854
22855 /* Forward references */
22856 typedef struct unixShm unixShm;               /* Connection shared memory */
22857 typedef struct unixShmNode unixShmNode;       /* Shared memory instance */
22858 typedef struct unixInodeInfo unixInodeInfo;   /* An i-node */
22859 typedef struct UnixUnusedFd UnixUnusedFd;     /* An unused file descriptor */
22860
22861 /*
22862 ** Sometimes, after a file handle is closed by SQLite, the file descriptor
22863 ** cannot be closed immediately. In these cases, instances of the following
22864 ** structure are used to store the file descriptor while waiting for an
22865 ** opportunity to either close or reuse it.
22866 */
22867 struct UnixUnusedFd {
22868   int fd;                   /* File descriptor to close */
22869   int flags;                /* Flags this file descriptor was opened with */
22870   UnixUnusedFd *pNext;      /* Next unused file descriptor on same file */
22871 };
22872
22873 /*
22874 ** The unixFile structure is subclass of sqlite3_file specific to the unix
22875 ** VFS implementations.
22876 */
22877 typedef struct unixFile unixFile;
22878 struct unixFile {
22879   sqlite3_io_methods const *pMethod;  /* Always the first entry */
22880   unixInodeInfo *pInode;              /* Info about locks on this inode */
22881   int h;                              /* The file descriptor */
22882   int dirfd;                          /* File descriptor for the directory */
22883   unsigned char eFileLock;            /* The type of lock held on this fd */
22884   int lastErrno;                      /* The unix errno from last I/O error */
22885   void *lockingContext;               /* Locking style specific state */
22886   UnixUnusedFd *pUnused;              /* Pre-allocated UnixUnusedFd */
22887   int fileFlags;                      /* Miscellanous flags */
22888   const char *zPath;                  /* Name of the file */
22889   unixShm *pShm;                      /* Shared memory segment information */
22890   int szChunk;                        /* Configured by FCNTL_CHUNK_SIZE */
22891 #if SQLITE_ENABLE_LOCKING_STYLE
22892   int openFlags;                      /* The flags specified at open() */
22893 #endif
22894 #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
22895   unsigned fsFlags;                   /* cached details from statfs() */
22896 #endif
22897 #if OS_VXWORKS
22898   int isDelete;                       /* Delete on close if true */
22899   struct vxworksFileId *pId;          /* Unique file ID */
22900 #endif
22901 #ifndef NDEBUG
22902   /* The next group of variables are used to track whether or not the
22903   ** transaction counter in bytes 24-27 of database files are updated
22904   ** whenever any part of the database changes.  An assertion fault will
22905   ** occur if a file is updated without also updating the transaction
22906   ** counter.  This test is made to avoid new problems similar to the
22907   ** one described by ticket #3584. 
22908   */
22909   unsigned char transCntrChng;   /* True if the transaction counter changed */
22910   unsigned char dbUpdate;        /* True if any part of database file changed */
22911   unsigned char inNormalWrite;   /* True if in a normal write operation */
22912 #endif
22913 #ifdef SQLITE_TEST
22914   /* In test mode, increase the size of this structure a bit so that 
22915   ** it is larger than the struct CrashFile defined in test6.c.
22916   */
22917   char aPadding[32];
22918 #endif
22919 };
22920
22921 /*
22922 ** The following macros define bits in unixFile.fileFlags
22923 */
22924 #define SQLITE_WHOLE_FILE_LOCKING  0x0001   /* Use whole-file locking */
22925
22926 /*
22927 ** Include code that is common to all os_*.c files
22928 */
22929 /************** Include os_common.h in the middle of os_unix.c ***************/
22930 /************** Begin file os_common.h ***************************************/
22931 /*
22932 ** 2004 May 22
22933 **
22934 ** The author disclaims copyright to this source code.  In place of
22935 ** a legal notice, here is a blessing:
22936 **
22937 **    May you do good and not evil.
22938 **    May you find forgiveness for yourself and forgive others.
22939 **    May you share freely, never taking more than you give.
22940 **
22941 ******************************************************************************
22942 **
22943 ** This file contains macros and a little bit of code that is common to
22944 ** all of the platform-specific files (os_*.c) and is #included into those
22945 ** files.
22946 **
22947 ** This file should be #included by the os_*.c files only.  It is not a
22948 ** general purpose header file.
22949 */
22950 #ifndef _OS_COMMON_H_
22951 #define _OS_COMMON_H_
22952
22953 /*
22954 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
22955 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
22956 ** switch.  The following code should catch this problem at compile-time.
22957 */
22958 #ifdef MEMORY_DEBUG
22959 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
22960 #endif
22961
22962 #ifdef SQLITE_DEBUG
22963 SQLITE_PRIVATE int sqlite3OSTrace = 0;
22964 #define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
22965 #else
22966 #define OSTRACE(X)
22967 #endif
22968
22969 /*
22970 ** Macros for performance tracing.  Normally turned off.  Only works
22971 ** on i486 hardware.
22972 */
22973 #ifdef SQLITE_PERFORMANCE_TRACE
22974
22975 /* 
22976 ** hwtime.h contains inline assembler code for implementing 
22977 ** high-performance timing routines.
22978 */
22979 /************** Include hwtime.h in the middle of os_common.h ****************/
22980 /************** Begin file hwtime.h ******************************************/
22981 /*
22982 ** 2008 May 27
22983 **
22984 ** The author disclaims copyright to this source code.  In place of
22985 ** a legal notice, here is a blessing:
22986 **
22987 **    May you do good and not evil.
22988 **    May you find forgiveness for yourself and forgive others.
22989 **    May you share freely, never taking more than you give.
22990 **
22991 ******************************************************************************
22992 **
22993 ** This file contains inline asm code for retrieving "high-performance"
22994 ** counters for x86 class CPUs.
22995 */
22996 #ifndef _HWTIME_H_
22997 #define _HWTIME_H_
22998
22999 /*
23000 ** The following routine only works on pentium-class (or newer) processors.
23001 ** It uses the RDTSC opcode to read the cycle count value out of the
23002 ** processor and returns that value.  This can be used for high-res
23003 ** profiling.
23004 */
23005 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
23006       (defined(i386) || defined(__i386__) || defined(_M_IX86))
23007
23008   #if defined(__GNUC__)
23009
23010   __inline__ sqlite_uint64 sqlite3Hwtime(void){
23011      unsigned int lo, hi;
23012      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
23013      return (sqlite_uint64)hi << 32 | lo;
23014   }
23015
23016   #elif defined(_MSC_VER)
23017
23018   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
23019      __asm {
23020         rdtsc
23021         ret       ; return value at EDX:EAX
23022      }
23023   }
23024
23025   #endif
23026
23027 #elif (defined(__GNUC__) && defined(__x86_64__))
23028
23029   __inline__ sqlite_uint64 sqlite3Hwtime(void){
23030       unsigned long val;
23031       __asm__ __volatile__ ("rdtsc" : "=A" (val));
23032       return val;
23033   }
23034  
23035 #elif (defined(__GNUC__) && defined(__ppc__))
23036
23037   __inline__ sqlite_uint64 sqlite3Hwtime(void){
23038       unsigned long long retval;
23039       unsigned long junk;
23040       __asm__ __volatile__ ("\n\
23041           1:      mftbu   %1\n\
23042                   mftb    %L0\n\
23043                   mftbu   %0\n\
23044                   cmpw    %0,%1\n\
23045                   bne     1b"
23046                   : "=r" (retval), "=r" (junk));
23047       return retval;
23048   }
23049
23050 #else
23051
23052   #error Need implementation of sqlite3Hwtime() for your platform.
23053
23054   /*
23055   ** To compile without implementing sqlite3Hwtime() for your platform,
23056   ** you can remove the above #error and use the following
23057   ** stub function.  You will lose timing support for many
23058   ** of the debugging and testing utilities, but it should at
23059   ** least compile and run.
23060   */
23061 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
23062
23063 #endif
23064
23065 #endif /* !defined(_HWTIME_H_) */
23066
23067 /************** End of hwtime.h **********************************************/
23068 /************** Continuing where we left off in os_common.h ******************/
23069
23070 static sqlite_uint64 g_start;
23071 static sqlite_uint64 g_elapsed;
23072 #define TIMER_START       g_start=sqlite3Hwtime()
23073 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
23074 #define TIMER_ELAPSED     g_elapsed
23075 #else
23076 #define TIMER_START
23077 #define TIMER_END
23078 #define TIMER_ELAPSED     ((sqlite_uint64)0)
23079 #endif
23080
23081 /*
23082 ** If we compile with the SQLITE_TEST macro set, then the following block
23083 ** of code will give us the ability to simulate a disk I/O error.  This
23084 ** is used for testing the I/O recovery logic.
23085 */
23086 #ifdef SQLITE_TEST
23087 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
23088 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
23089 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
23090 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
23091 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
23092 SQLITE_API int sqlite3_diskfull_pending = 0;
23093 SQLITE_API int sqlite3_diskfull = 0;
23094 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
23095 #define SimulateIOError(CODE)  \
23096   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
23097        || sqlite3_io_error_pending-- == 1 )  \
23098               { local_ioerr(); CODE; }
23099 static void local_ioerr(){
23100   IOTRACE(("IOERR\n"));
23101   sqlite3_io_error_hit++;
23102   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
23103 }
23104 #define SimulateDiskfullError(CODE) \
23105    if( sqlite3_diskfull_pending ){ \
23106      if( sqlite3_diskfull_pending == 1 ){ \
23107        local_ioerr(); \
23108        sqlite3_diskfull = 1; \
23109        sqlite3_io_error_hit = 1; \
23110        CODE; \
23111      }else{ \
23112        sqlite3_diskfull_pending--; \
23113      } \
23114    }
23115 #else
23116 #define SimulateIOErrorBenign(X)
23117 #define SimulateIOError(A)
23118 #define SimulateDiskfullError(A)
23119 #endif
23120
23121 /*
23122 ** When testing, keep a count of the number of open files.
23123 */
23124 #ifdef SQLITE_TEST
23125 SQLITE_API int sqlite3_open_file_count = 0;
23126 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
23127 #else
23128 #define OpenCounter(X)
23129 #endif
23130
23131 #endif /* !defined(_OS_COMMON_H_) */
23132
23133 /************** End of os_common.h *******************************************/
23134 /************** Continuing where we left off in os_unix.c ********************/
23135
23136 /*
23137 ** Define various macros that are missing from some systems.
23138 */
23139 #ifndef O_LARGEFILE
23140 # define O_LARGEFILE 0
23141 #endif
23142 #ifdef SQLITE_DISABLE_LFS
23143 # undef O_LARGEFILE
23144 # define O_LARGEFILE 0
23145 #endif
23146 #ifndef O_NOFOLLOW
23147 # define O_NOFOLLOW 0
23148 #endif
23149 #ifndef O_BINARY
23150 # define O_BINARY 0
23151 #endif
23152
23153 /*
23154 ** The DJGPP compiler environment looks mostly like Unix, but it
23155 ** lacks the fcntl() system call.  So redefine fcntl() to be something
23156 ** that always succeeds.  This means that locking does not occur under
23157 ** DJGPP.  But it is DOS - what did you expect?
23158 */
23159 #ifdef __DJGPP__
23160 # define fcntl(A,B,C) 0
23161 #endif
23162
23163 /*
23164 ** The threadid macro resolves to the thread-id or to 0.  Used for
23165 ** testing and debugging only.
23166 */
23167 #if SQLITE_THREADSAFE
23168 #define threadid pthread_self()
23169 #else
23170 #define threadid 0
23171 #endif
23172
23173
23174 /*
23175 ** Helper functions to obtain and relinquish the global mutex. The
23176 ** global mutex is used to protect the unixInodeInfo and
23177 ** vxworksFileId objects used by this file, all of which may be 
23178 ** shared by multiple threads.
23179 **
23180 ** Function unixMutexHeld() is used to assert() that the global mutex 
23181 ** is held when required. This function is only used as part of assert() 
23182 ** statements. e.g.
23183 **
23184 **   unixEnterMutex()
23185 **     assert( unixMutexHeld() );
23186 **   unixEnterLeave()
23187 */
23188 static void unixEnterMutex(void){
23189   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
23190 }
23191 static void unixLeaveMutex(void){
23192   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
23193 }
23194 #ifdef SQLITE_DEBUG
23195 static int unixMutexHeld(void) {
23196   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
23197 }
23198 #endif
23199
23200
23201 #ifdef SQLITE_DEBUG
23202 /*
23203 ** Helper function for printing out trace information from debugging
23204 ** binaries. This returns the string represetation of the supplied
23205 ** integer lock-type.
23206 */
23207 static const char *azFileLock(int eFileLock){
23208   switch( eFileLock ){
23209     case NO_LOCK: return "NONE";
23210     case SHARED_LOCK: return "SHARED";
23211     case RESERVED_LOCK: return "RESERVED";
23212     case PENDING_LOCK: return "PENDING";
23213     case EXCLUSIVE_LOCK: return "EXCLUSIVE";
23214   }
23215   return "ERROR";
23216 }
23217 #endif
23218
23219 #ifdef SQLITE_LOCK_TRACE
23220 /*
23221 ** Print out information about all locking operations.
23222 **
23223 ** This routine is used for troubleshooting locks on multithreaded
23224 ** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
23225 ** command-line option on the compiler.  This code is normally
23226 ** turned off.
23227 */
23228 static int lockTrace(int fd, int op, struct flock *p){
23229   char *zOpName, *zType;
23230   int s;
23231   int savedErrno;
23232   if( op==F_GETLK ){
23233     zOpName = "GETLK";
23234   }else if( op==F_SETLK ){
23235     zOpName = "SETLK";
23236   }else{
23237     s = fcntl(fd, op, p);
23238     sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
23239     return s;
23240   }
23241   if( p->l_type==F_RDLCK ){
23242     zType = "RDLCK";
23243   }else if( p->l_type==F_WRLCK ){
23244     zType = "WRLCK";
23245   }else if( p->l_type==F_UNLCK ){
23246     zType = "UNLCK";
23247   }else{
23248     assert( 0 );
23249   }
23250   assert( p->l_whence==SEEK_SET );
23251   s = fcntl(fd, op, p);
23252   savedErrno = errno;
23253   sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
23254      threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
23255      (int)p->l_pid, s);
23256   if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
23257     struct flock l2;
23258     l2 = *p;
23259     fcntl(fd, F_GETLK, &l2);
23260     if( l2.l_type==F_RDLCK ){
23261       zType = "RDLCK";
23262     }else if( l2.l_type==F_WRLCK ){
23263       zType = "WRLCK";
23264     }else if( l2.l_type==F_UNLCK ){
23265       zType = "UNLCK";
23266     }else{
23267       assert( 0 );
23268     }
23269     sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
23270        zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
23271   }
23272   errno = savedErrno;
23273   return s;
23274 }
23275 #define fcntl lockTrace
23276 #endif /* SQLITE_LOCK_TRACE */
23277
23278
23279
23280 /*
23281 ** This routine translates a standard POSIX errno code into something
23282 ** useful to the clients of the sqlite3 functions.  Specifically, it is
23283 ** intended to translate a variety of "try again" errors into SQLITE_BUSY
23284 ** and a variety of "please close the file descriptor NOW" errors into 
23285 ** SQLITE_IOERR
23286 ** 
23287 ** Errors during initialization of locks, or file system support for locks,
23288 ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
23289 */
23290 static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
23291   switch (posixError) {
23292   case 0: 
23293     return SQLITE_OK;
23294     
23295   case EAGAIN:
23296   case ETIMEDOUT:
23297   case EBUSY:
23298   case EINTR:
23299   case ENOLCK:  
23300     /* random NFS retry error, unless during file system support 
23301      * introspection, in which it actually means what it says */
23302     return SQLITE_BUSY;
23303     
23304   case EACCES: 
23305     /* EACCES is like EAGAIN during locking operations, but not any other time*/
23306     if( (sqliteIOErr == SQLITE_IOERR_LOCK) || 
23307         (sqliteIOErr == SQLITE_IOERR_UNLOCK) || 
23308         (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
23309         (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
23310       return SQLITE_BUSY;
23311     }
23312     /* else fall through */
23313   case EPERM: 
23314     return SQLITE_PERM;
23315     
23316   case EDEADLK:
23317     return SQLITE_IOERR_BLOCKED;
23318     
23319 #if EOPNOTSUPP!=ENOTSUP
23320   case EOPNOTSUPP: 
23321     /* something went terribly awry, unless during file system support 
23322      * introspection, in which it actually means what it says */
23323 #endif
23324 #ifdef ENOTSUP
23325   case ENOTSUP: 
23326     /* invalid fd, unless during file system support introspection, in which 
23327      * it actually means what it says */
23328 #endif
23329   case EIO:
23330   case EBADF:
23331   case EINVAL:
23332   case ENOTCONN:
23333   case ENODEV:
23334   case ENXIO:
23335   case ENOENT:
23336   case ESTALE:
23337   case ENOSYS:
23338     /* these should force the client to close the file and reconnect */
23339     
23340   default: 
23341     return sqliteIOErr;
23342   }
23343 }
23344
23345
23346
23347 /******************************************************************************
23348 ****************** Begin Unique File ID Utility Used By VxWorks ***************
23349 **
23350 ** On most versions of unix, we can get a unique ID for a file by concatenating
23351 ** the device number and the inode number.  But this does not work on VxWorks.
23352 ** On VxWorks, a unique file id must be based on the canonical filename.
23353 **
23354 ** A pointer to an instance of the following structure can be used as a
23355 ** unique file ID in VxWorks.  Each instance of this structure contains
23356 ** a copy of the canonical filename.  There is also a reference count.  
23357 ** The structure is reclaimed when the number of pointers to it drops to
23358 ** zero.
23359 **
23360 ** There are never very many files open at one time and lookups are not
23361 ** a performance-critical path, so it is sufficient to put these
23362 ** structures on a linked list.
23363 */
23364 struct vxworksFileId {
23365   struct vxworksFileId *pNext;  /* Next in a list of them all */
23366   int nRef;                     /* Number of references to this one */
23367   int nName;                    /* Length of the zCanonicalName[] string */
23368   char *zCanonicalName;         /* Canonical filename */
23369 };
23370
23371 #if OS_VXWORKS
23372 /* 
23373 ** All unique filenames are held on a linked list headed by this
23374 ** variable:
23375 */
23376 static struct vxworksFileId *vxworksFileList = 0;
23377
23378 /*
23379 ** Simplify a filename into its canonical form
23380 ** by making the following changes:
23381 **
23382 **  * removing any trailing and duplicate /
23383 **  * convert /./ into just /
23384 **  * convert /A/../ where A is any simple name into just /
23385 **
23386 ** Changes are made in-place.  Return the new name length.
23387 **
23388 ** The original filename is in z[0..n-1].  Return the number of
23389 ** characters in the simplified name.
23390 */
23391 static int vxworksSimplifyName(char *z, int n){
23392   int i, j;
23393   while( n>1 && z[n-1]=='/' ){ n--; }
23394   for(i=j=0; i<n; i++){
23395     if( z[i]=='/' ){
23396       if( z[i+1]=='/' ) continue;
23397       if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
23398         i += 1;
23399         continue;
23400       }
23401       if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
23402         while( j>0 && z[j-1]!='/' ){ j--; }
23403         if( j>0 ){ j--; }
23404         i += 2;
23405         continue;
23406       }
23407     }
23408     z[j++] = z[i];
23409   }
23410   z[j] = 0;
23411   return j;
23412 }
23413
23414 /*
23415 ** Find a unique file ID for the given absolute pathname.  Return
23416 ** a pointer to the vxworksFileId object.  This pointer is the unique
23417 ** file ID.
23418 **
23419 ** The nRef field of the vxworksFileId object is incremented before
23420 ** the object is returned.  A new vxworksFileId object is created
23421 ** and added to the global list if necessary.
23422 **
23423 ** If a memory allocation error occurs, return NULL.
23424 */
23425 static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
23426   struct vxworksFileId *pNew;         /* search key and new file ID */
23427   struct vxworksFileId *pCandidate;   /* For looping over existing file IDs */
23428   int n;                              /* Length of zAbsoluteName string */
23429
23430   assert( zAbsoluteName[0]=='/' );
23431   n = (int)strlen(zAbsoluteName);
23432   pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
23433   if( pNew==0 ) return 0;
23434   pNew->zCanonicalName = (char*)&pNew[1];
23435   memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
23436   n = vxworksSimplifyName(pNew->zCanonicalName, n);
23437
23438   /* Search for an existing entry that matching the canonical name.
23439   ** If found, increment the reference count and return a pointer to
23440   ** the existing file ID.
23441   */
23442   unixEnterMutex();
23443   for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
23444     if( pCandidate->nName==n 
23445      && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
23446     ){
23447        sqlite3_free(pNew);
23448        pCandidate->nRef++;
23449        unixLeaveMutex();
23450        return pCandidate;
23451     }
23452   }
23453
23454   /* No match was found.  We will make a new file ID */
23455   pNew->nRef = 1;
23456   pNew->nName = n;
23457   pNew->pNext = vxworksFileList;
23458   vxworksFileList = pNew;
23459   unixLeaveMutex();
23460   return pNew;
23461 }
23462
23463 /*
23464 ** Decrement the reference count on a vxworksFileId object.  Free
23465 ** the object when the reference count reaches zero.
23466 */
23467 static void vxworksReleaseFileId(struct vxworksFileId *pId){
23468   unixEnterMutex();
23469   assert( pId->nRef>0 );
23470   pId->nRef--;
23471   if( pId->nRef==0 ){
23472     struct vxworksFileId **pp;
23473     for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
23474     assert( *pp==pId );
23475     *pp = pId->pNext;
23476     sqlite3_free(pId);
23477   }
23478   unixLeaveMutex();
23479 }
23480 #endif /* OS_VXWORKS */
23481 /*************** End of Unique File ID Utility Used By VxWorks ****************
23482 ******************************************************************************/
23483
23484
23485 /******************************************************************************
23486 *************************** Posix Advisory Locking ****************************
23487 **
23488 ** POSIX advisory locks are broken by design.  ANSI STD 1003.1 (1996)
23489 ** section 6.5.2.2 lines 483 through 490 specify that when a process
23490 ** sets or clears a lock, that operation overrides any prior locks set
23491 ** by the same process.  It does not explicitly say so, but this implies
23492 ** that it overrides locks set by the same process using a different
23493 ** file descriptor.  Consider this test case:
23494 **
23495 **       int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
23496 **       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
23497 **
23498 ** Suppose ./file1 and ./file2 are really the same file (because
23499 ** one is a hard or symbolic link to the other) then if you set
23500 ** an exclusive lock on fd1, then try to get an exclusive lock
23501 ** on fd2, it works.  I would have expected the second lock to
23502 ** fail since there was already a lock on the file due to fd1.
23503 ** But not so.  Since both locks came from the same process, the
23504 ** second overrides the first, even though they were on different
23505 ** file descriptors opened on different file names.
23506 **
23507 ** This means that we cannot use POSIX locks to synchronize file access
23508 ** among competing threads of the same process.  POSIX locks will work fine
23509 ** to synchronize access for threads in separate processes, but not
23510 ** threads within the same process.
23511 **
23512 ** To work around the problem, SQLite has to manage file locks internally
23513 ** on its own.  Whenever a new database is opened, we have to find the
23514 ** specific inode of the database file (the inode is determined by the
23515 ** st_dev and st_ino fields of the stat structure that fstat() fills in)
23516 ** and check for locks already existing on that inode.  When locks are
23517 ** created or removed, we have to look at our own internal record of the
23518 ** locks to see if another thread has previously set a lock on that same
23519 ** inode.
23520 **
23521 ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
23522 ** For VxWorks, we have to use the alternative unique ID system based on
23523 ** canonical filename and implemented in the previous division.)
23524 **
23525 ** The sqlite3_file structure for POSIX is no longer just an integer file
23526 ** descriptor.  It is now a structure that holds the integer file
23527 ** descriptor and a pointer to a structure that describes the internal
23528 ** locks on the corresponding inode.  There is one locking structure
23529 ** per inode, so if the same inode is opened twice, both unixFile structures
23530 ** point to the same locking structure.  The locking structure keeps
23531 ** a reference count (so we will know when to delete it) and a "cnt"
23532 ** field that tells us its internal lock status.  cnt==0 means the
23533 ** file is unlocked.  cnt==-1 means the file has an exclusive lock.
23534 ** cnt>0 means there are cnt shared locks on the file.
23535 **
23536 ** Any attempt to lock or unlock a file first checks the locking
23537 ** structure.  The fcntl() system call is only invoked to set a 
23538 ** POSIX lock if the internal lock structure transitions between
23539 ** a locked and an unlocked state.
23540 **
23541 ** But wait:  there are yet more problems with POSIX advisory locks.
23542 **
23543 ** If you close a file descriptor that points to a file that has locks,
23544 ** all locks on that file that are owned by the current process are
23545 ** released.  To work around this problem, each unixInodeInfo object
23546 ** maintains a count of the number of pending locks on tha inode.
23547 ** When an attempt is made to close an unixFile, if there are
23548 ** other unixFile open on the same inode that are holding locks, the call
23549 ** to close() the file descriptor is deferred until all of the locks clear.
23550 ** The unixInodeInfo structure keeps a list of file descriptors that need to
23551 ** be closed and that list is walked (and cleared) when the last lock
23552 ** clears.
23553 **
23554 ** Yet another problem:  LinuxThreads do not play well with posix locks.
23555 **
23556 ** Many older versions of linux use the LinuxThreads library which is
23557 ** not posix compliant.  Under LinuxThreads, a lock created by thread
23558 ** A cannot be modified or overridden by a different thread B.
23559 ** Only thread A can modify the lock.  Locking behavior is correct
23560 ** if the appliation uses the newer Native Posix Thread Library (NPTL)
23561 ** on linux - with NPTL a lock created by thread A can override locks
23562 ** in thread B.  But there is no way to know at compile-time which
23563 ** threading library is being used.  So there is no way to know at
23564 ** compile-time whether or not thread A can override locks on thread B.
23565 ** One has to do a run-time check to discover the behavior of the
23566 ** current process.
23567 **
23568 ** SQLite used to support LinuxThreads.  But support for LinuxThreads
23569 ** was dropped beginning with version 3.7.0.  SQLite will still work with
23570 ** LinuxThreads provided that (1) there is no more than one connection 
23571 ** per database file in the same process and (2) database connections
23572 ** do not move across threads.
23573 */
23574
23575 /*
23576 ** An instance of the following structure serves as the key used
23577 ** to locate a particular unixInodeInfo object.
23578 */
23579 struct unixFileId {
23580   dev_t dev;                  /* Device number */
23581 #if OS_VXWORKS
23582   struct vxworksFileId *pId;  /* Unique file ID for vxworks. */
23583 #else
23584   ino_t ino;                  /* Inode number */
23585 #endif
23586 };
23587
23588 /*
23589 ** An instance of the following structure is allocated for each open
23590 ** inode.  Or, on LinuxThreads, there is one of these structures for
23591 ** each inode opened by each thread.
23592 **
23593 ** A single inode can have multiple file descriptors, so each unixFile
23594 ** structure contains a pointer to an instance of this object and this
23595 ** object keeps a count of the number of unixFile pointing to it.
23596 */
23597 struct unixInodeInfo {
23598   struct unixFileId fileId;       /* The lookup key */
23599   int nShared;                    /* Number of SHARED locks held */
23600   int eFileLock;                  /* One of SHARED_LOCK, RESERVED_LOCK etc. */
23601   int nRef;                       /* Number of pointers to this structure */
23602   unixShmNode *pShmNode;          /* Shared memory associated with this inode */
23603   int nLock;                      /* Number of outstanding file locks */
23604   UnixUnusedFd *pUnused;          /* Unused file descriptors to close */
23605   unixInodeInfo *pNext;           /* List of all unixInodeInfo objects */
23606   unixInodeInfo *pPrev;           /*    .... doubly linked */
23607 #if defined(SQLITE_ENABLE_LOCKING_STYLE)
23608   unsigned long long sharedByte;  /* for AFP simulated shared lock */
23609 #endif
23610 #if OS_VXWORKS
23611   sem_t *pSem;                    /* Named POSIX semaphore */
23612   char aSemName[MAX_PATHNAME+2];  /* Name of that semaphore */
23613 #endif
23614 };
23615
23616 /*
23617 ** A lists of all unixInodeInfo objects.
23618 */
23619 static unixInodeInfo *inodeList = 0;
23620
23621 /*
23622 ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
23623 ** If all such file descriptors are closed without error, the list is
23624 ** cleared and SQLITE_OK returned.
23625 **
23626 ** Otherwise, if an error occurs, then successfully closed file descriptor
23627 ** entries are removed from the list, and SQLITE_IOERR_CLOSE returned. 
23628 ** not deleted and SQLITE_IOERR_CLOSE returned.
23629 */ 
23630 static int closePendingFds(unixFile *pFile){
23631   int rc = SQLITE_OK;
23632   unixInodeInfo *pInode = pFile->pInode;
23633   UnixUnusedFd *pError = 0;
23634   UnixUnusedFd *p;
23635   UnixUnusedFd *pNext;
23636   for(p=pInode->pUnused; p; p=pNext){
23637     pNext = p->pNext;
23638     if( close(p->fd) ){
23639       pFile->lastErrno = errno;
23640       rc = SQLITE_IOERR_CLOSE;
23641       p->pNext = pError;
23642       pError = p;
23643     }else{
23644       sqlite3_free(p);
23645     }
23646   }
23647   pInode->pUnused = pError;
23648   return rc;
23649 }
23650
23651 /*
23652 ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
23653 **
23654 ** The mutex entered using the unixEnterMutex() function must be held
23655 ** when this function is called.
23656 */
23657 static void releaseInodeInfo(unixFile *pFile){
23658   unixInodeInfo *pInode = pFile->pInode;
23659   assert( unixMutexHeld() );
23660   if( pInode ){
23661     pInode->nRef--;
23662     if( pInode->nRef==0 ){
23663       assert( pInode->pShmNode==0 );
23664       closePendingFds(pFile);
23665       if( pInode->pPrev ){
23666         assert( pInode->pPrev->pNext==pInode );
23667         pInode->pPrev->pNext = pInode->pNext;
23668       }else{
23669         assert( inodeList==pInode );
23670         inodeList = pInode->pNext;
23671       }
23672       if( pInode->pNext ){
23673         assert( pInode->pNext->pPrev==pInode );
23674         pInode->pNext->pPrev = pInode->pPrev;
23675       }
23676       sqlite3_free(pInode);
23677     }
23678   }
23679 }
23680
23681 /*
23682 ** Given a file descriptor, locate the unixInodeInfo object that
23683 ** describes that file descriptor.  Create a new one if necessary.  The
23684 ** return value might be uninitialized if an error occurs.
23685 **
23686 ** The mutex entered using the unixEnterMutex() function must be held
23687 ** when this function is called.
23688 **
23689 ** Return an appropriate error code.
23690 */
23691 static int findInodeInfo(
23692   unixFile *pFile,               /* Unix file with file desc used in the key */
23693   unixInodeInfo **ppInode        /* Return the unixInodeInfo object here */
23694 ){
23695   int rc;                        /* System call return code */
23696   int fd;                        /* The file descriptor for pFile */
23697   struct unixFileId fileId;      /* Lookup key for the unixInodeInfo */
23698   struct stat statbuf;           /* Low-level file information */
23699   unixInodeInfo *pInode = 0;     /* Candidate unixInodeInfo object */
23700
23701   assert( unixMutexHeld() );
23702
23703   /* Get low-level information about the file that we can used to
23704   ** create a unique name for the file.
23705   */
23706   fd = pFile->h;
23707   rc = fstat(fd, &statbuf);
23708   if( rc!=0 ){
23709     pFile->lastErrno = errno;
23710 #ifdef EOVERFLOW
23711     if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
23712 #endif
23713     return SQLITE_IOERR;
23714   }
23715
23716 #ifdef __APPLE__
23717   /* On OS X on an msdos filesystem, the inode number is reported
23718   ** incorrectly for zero-size files.  See ticket #3260.  To work
23719   ** around this problem (we consider it a bug in OS X, not SQLite)
23720   ** we always increase the file size to 1 by writing a single byte
23721   ** prior to accessing the inode number.  The one byte written is
23722   ** an ASCII 'S' character which also happens to be the first byte
23723   ** in the header of every SQLite database.  In this way, if there
23724   ** is a race condition such that another thread has already populated
23725   ** the first page of the database, no damage is done.
23726   */
23727   if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
23728     rc = write(fd, "S", 1);
23729     if( rc!=1 ){
23730       pFile->lastErrno = errno;
23731       return SQLITE_IOERR;
23732     }
23733     rc = fstat(fd, &statbuf);
23734     if( rc!=0 ){
23735       pFile->lastErrno = errno;
23736       return SQLITE_IOERR;
23737     }
23738   }
23739 #endif
23740
23741   memset(&fileId, 0, sizeof(fileId));
23742   fileId.dev = statbuf.st_dev;
23743 #if OS_VXWORKS
23744   fileId.pId = pFile->pId;
23745 #else
23746   fileId.ino = statbuf.st_ino;
23747 #endif
23748   pInode = inodeList;
23749   while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
23750     pInode = pInode->pNext;
23751   }
23752   if( pInode==0 ){
23753     pInode = sqlite3_malloc( sizeof(*pInode) );
23754     if( pInode==0 ){
23755       return SQLITE_NOMEM;
23756     }
23757     memset(pInode, 0, sizeof(*pInode));
23758     memcpy(&pInode->fileId, &fileId, sizeof(fileId));
23759     pInode->nRef = 1;
23760     pInode->pNext = inodeList;
23761     pInode->pPrev = 0;
23762     if( inodeList ) inodeList->pPrev = pInode;
23763     inodeList = pInode;
23764   }else{
23765     pInode->nRef++;
23766   }
23767   *ppInode = pInode;
23768   return SQLITE_OK;
23769 }
23770
23771
23772 /*
23773 ** This routine checks if there is a RESERVED lock held on the specified
23774 ** file by this or any other process. If such a lock is held, set *pResOut
23775 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
23776 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
23777 */
23778 static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
23779   int rc = SQLITE_OK;
23780   int reserved = 0;
23781   unixFile *pFile = (unixFile*)id;
23782
23783   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
23784
23785   assert( pFile );
23786   unixEnterMutex(); /* Because pFile->pInode is shared across threads */
23787
23788   /* Check if a thread in this process holds such a lock */
23789   if( pFile->pInode->eFileLock>SHARED_LOCK ){
23790     reserved = 1;
23791   }
23792
23793   /* Otherwise see if some other process holds it.
23794   */
23795 #ifndef __DJGPP__
23796   if( !reserved ){
23797     struct flock lock;
23798     lock.l_whence = SEEK_SET;
23799     lock.l_start = RESERVED_BYTE;
23800     lock.l_len = 1;
23801     lock.l_type = F_WRLCK;
23802     if (-1 == fcntl(pFile->h, F_GETLK, &lock)) {
23803       int tErrno = errno;
23804       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
23805       pFile->lastErrno = tErrno;
23806     } else if( lock.l_type!=F_UNLCK ){
23807       reserved = 1;
23808     }
23809   }
23810 #endif
23811   
23812   unixLeaveMutex();
23813   OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
23814
23815   *pResOut = reserved;
23816   return rc;
23817 }
23818
23819 /*
23820 ** Lock the file with the lock specified by parameter eFileLock - one
23821 ** of the following:
23822 **
23823 **     (1) SHARED_LOCK
23824 **     (2) RESERVED_LOCK
23825 **     (3) PENDING_LOCK
23826 **     (4) EXCLUSIVE_LOCK
23827 **
23828 ** Sometimes when requesting one lock state, additional lock states
23829 ** are inserted in between.  The locking might fail on one of the later
23830 ** transitions leaving the lock state different from what it started but
23831 ** still short of its goal.  The following chart shows the allowed
23832 ** transitions and the inserted intermediate states:
23833 **
23834 **    UNLOCKED -> SHARED
23835 **    SHARED -> RESERVED
23836 **    SHARED -> (PENDING) -> EXCLUSIVE
23837 **    RESERVED -> (PENDING) -> EXCLUSIVE
23838 **    PENDING -> EXCLUSIVE
23839 **
23840 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
23841 ** routine to lower a locking level.
23842 */
23843 static int unixLock(sqlite3_file *id, int eFileLock){
23844   /* The following describes the implementation of the various locks and
23845   ** lock transitions in terms of the POSIX advisory shared and exclusive
23846   ** lock primitives (called read-locks and write-locks below, to avoid
23847   ** confusion with SQLite lock names). The algorithms are complicated
23848   ** slightly in order to be compatible with windows systems simultaneously
23849   ** accessing the same database file, in case that is ever required.
23850   **
23851   ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
23852   ** byte', each single bytes at well known offsets, and the 'shared byte
23853   ** range', a range of 510 bytes at a well known offset.
23854   **
23855   ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
23856   ** byte'.  If this is successful, a random byte from the 'shared byte
23857   ** range' is read-locked and the lock on the 'pending byte' released.
23858   **
23859   ** A process may only obtain a RESERVED lock after it has a SHARED lock.
23860   ** A RESERVED lock is implemented by grabbing a write-lock on the
23861   ** 'reserved byte'. 
23862   **
23863   ** A process may only obtain a PENDING lock after it has obtained a
23864   ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
23865   ** on the 'pending byte'. This ensures that no new SHARED locks can be
23866   ** obtained, but existing SHARED locks are allowed to persist. A process
23867   ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
23868   ** This property is used by the algorithm for rolling back a journal file
23869   ** after a crash.
23870   **
23871   ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
23872   ** implemented by obtaining a write-lock on the entire 'shared byte
23873   ** range'. Since all other locks require a read-lock on one of the bytes
23874   ** within this range, this ensures that no other locks are held on the
23875   ** database. 
23876   **
23877   ** The reason a single byte cannot be used instead of the 'shared byte
23878   ** range' is that some versions of windows do not support read-locks. By
23879   ** locking a random byte from a range, concurrent SHARED locks may exist
23880   ** even if the locking primitive used is always a write-lock.
23881   */
23882   int rc = SQLITE_OK;
23883   unixFile *pFile = (unixFile*)id;
23884   unixInodeInfo *pInode = pFile->pInode;
23885   struct flock lock;
23886   int s = 0;
23887   int tErrno = 0;
23888
23889   assert( pFile );
23890   OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
23891       azFileLock(eFileLock), azFileLock(pFile->eFileLock),
23892       azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
23893
23894   /* If there is already a lock of this type or more restrictive on the
23895   ** unixFile, do nothing. Don't use the end_lock: exit path, as
23896   ** unixEnterMutex() hasn't been called yet.
23897   */
23898   if( pFile->eFileLock>=eFileLock ){
23899     OSTRACE(("LOCK    %d %s ok (already held) (unix)\n", pFile->h,
23900             azFileLock(eFileLock)));
23901     return SQLITE_OK;
23902   }
23903
23904   /* Make sure the locking sequence is correct.
23905   **  (1) We never move from unlocked to anything higher than shared lock.
23906   **  (2) SQLite never explicitly requests a pendig lock.
23907   **  (3) A shared lock is always held when a reserve lock is requested.
23908   */
23909   assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
23910   assert( eFileLock!=PENDING_LOCK );
23911   assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
23912
23913   /* This mutex is needed because pFile->pInode is shared across threads
23914   */
23915   unixEnterMutex();
23916   pInode = pFile->pInode;
23917
23918   /* If some thread using this PID has a lock via a different unixFile*
23919   ** handle that precludes the requested lock, return BUSY.
23920   */
23921   if( (pFile->eFileLock!=pInode->eFileLock && 
23922           (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
23923   ){
23924     rc = SQLITE_BUSY;
23925     goto end_lock;
23926   }
23927
23928   /* If a SHARED lock is requested, and some thread using this PID already
23929   ** has a SHARED or RESERVED lock, then increment reference counts and
23930   ** return SQLITE_OK.
23931   */
23932   if( eFileLock==SHARED_LOCK && 
23933       (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
23934     assert( eFileLock==SHARED_LOCK );
23935     assert( pFile->eFileLock==0 );
23936     assert( pInode->nShared>0 );
23937     pFile->eFileLock = SHARED_LOCK;
23938     pInode->nShared++;
23939     pInode->nLock++;
23940     goto end_lock;
23941   }
23942
23943
23944   /* A PENDING lock is needed before acquiring a SHARED lock and before
23945   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
23946   ** be released.
23947   */
23948   lock.l_len = 1L;
23949   lock.l_whence = SEEK_SET;
23950   if( eFileLock==SHARED_LOCK 
23951       || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
23952   ){
23953     lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
23954     lock.l_start = PENDING_BYTE;
23955     s = fcntl(pFile->h, F_SETLK, &lock);
23956     if( s==(-1) ){
23957       tErrno = errno;
23958       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
23959       if( IS_LOCK_ERROR(rc) ){
23960         pFile->lastErrno = tErrno;
23961       }
23962       goto end_lock;
23963     }
23964   }
23965
23966
23967   /* If control gets to this point, then actually go ahead and make
23968   ** operating system calls for the specified lock.
23969   */
23970   if( eFileLock==SHARED_LOCK ){
23971     assert( pInode->nShared==0 );
23972     assert( pInode->eFileLock==0 );
23973
23974     /* Now get the read-lock */
23975     lock.l_start = SHARED_FIRST;
23976     lock.l_len = SHARED_SIZE;
23977     if( (s = fcntl(pFile->h, F_SETLK, &lock))==(-1) ){
23978       tErrno = errno;
23979     }
23980     /* Drop the temporary PENDING lock */
23981     lock.l_start = PENDING_BYTE;
23982     lock.l_len = 1L;
23983     lock.l_type = F_UNLCK;
23984     if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
23985       if( s != -1 ){
23986         /* This could happen with a network mount */
23987         tErrno = errno; 
23988         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK); 
23989         if( IS_LOCK_ERROR(rc) ){
23990           pFile->lastErrno = tErrno;
23991         }
23992         goto end_lock;
23993       }
23994     }
23995     if( s==(-1) ){
23996       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
23997       if( IS_LOCK_ERROR(rc) ){
23998         pFile->lastErrno = tErrno;
23999       }
24000     }else{
24001       pFile->eFileLock = SHARED_LOCK;
24002       pInode->nLock++;
24003       pInode->nShared = 1;
24004     }
24005   }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
24006     /* We are trying for an exclusive lock but another thread in this
24007     ** same process is still holding a shared lock. */
24008     rc = SQLITE_BUSY;
24009   }else{
24010     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
24011     ** assumed that there is a SHARED or greater lock on the file
24012     ** already.
24013     */
24014     assert( 0!=pFile->eFileLock );
24015     lock.l_type = F_WRLCK;
24016     switch( eFileLock ){
24017       case RESERVED_LOCK:
24018         lock.l_start = RESERVED_BYTE;
24019         break;
24020       case EXCLUSIVE_LOCK:
24021         lock.l_start = SHARED_FIRST;
24022         lock.l_len = SHARED_SIZE;
24023         break;
24024       default:
24025         assert(0);
24026     }
24027     s = fcntl(pFile->h, F_SETLK, &lock);
24028     if( s==(-1) ){
24029       tErrno = errno;
24030       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
24031       if( IS_LOCK_ERROR(rc) ){
24032         pFile->lastErrno = tErrno;
24033       }
24034     }
24035   }
24036   
24037
24038 #ifndef NDEBUG
24039   /* Set up the transaction-counter change checking flags when
24040   ** transitioning from a SHARED to a RESERVED lock.  The change
24041   ** from SHARED to RESERVED marks the beginning of a normal
24042   ** write operation (not a hot journal rollback).
24043   */
24044   if( rc==SQLITE_OK
24045    && pFile->eFileLock<=SHARED_LOCK
24046    && eFileLock==RESERVED_LOCK
24047   ){
24048     pFile->transCntrChng = 0;
24049     pFile->dbUpdate = 0;
24050     pFile->inNormalWrite = 1;
24051   }
24052 #endif
24053
24054
24055   if( rc==SQLITE_OK ){
24056     pFile->eFileLock = eFileLock;
24057     pInode->eFileLock = eFileLock;
24058   }else if( eFileLock==EXCLUSIVE_LOCK ){
24059     pFile->eFileLock = PENDING_LOCK;
24060     pInode->eFileLock = PENDING_LOCK;
24061   }
24062
24063 end_lock:
24064   unixLeaveMutex();
24065   OSTRACE(("LOCK    %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock), 
24066       rc==SQLITE_OK ? "ok" : "failed"));
24067   return rc;
24068 }
24069
24070 /*
24071 ** Add the file descriptor used by file handle pFile to the corresponding
24072 ** pUnused list.
24073 */
24074 static void setPendingFd(unixFile *pFile){
24075   unixInodeInfo *pInode = pFile->pInode;
24076   UnixUnusedFd *p = pFile->pUnused;
24077   p->pNext = pInode->pUnused;
24078   pInode->pUnused = p;
24079   pFile->h = -1;
24080   pFile->pUnused = 0;
24081 }
24082
24083 /*
24084 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
24085 ** must be either NO_LOCK or SHARED_LOCK.
24086 **
24087 ** If the locking level of the file descriptor is already at or below
24088 ** the requested locking level, this routine is a no-op.
24089 ** 
24090 ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
24091 ** the byte range is divided into 2 parts and the first part is unlocked then
24092 ** set to a read lock, then the other part is simply unlocked.  This works 
24093 ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to 
24094 ** remove the write lock on a region when a read lock is set.
24095 */
24096 static int _posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
24097   unixFile *pFile = (unixFile*)id;
24098   unixInodeInfo *pInode;
24099   struct flock lock;
24100   int rc = SQLITE_OK;
24101   int h;
24102   int tErrno;                      /* Error code from system call errors */
24103
24104   assert( pFile );
24105   OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
24106       pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
24107       getpid()));
24108
24109   assert( eFileLock<=SHARED_LOCK );
24110   if( pFile->eFileLock<=eFileLock ){
24111     return SQLITE_OK;
24112   }
24113   unixEnterMutex();
24114   h = pFile->h;
24115   pInode = pFile->pInode;
24116   assert( pInode->nShared!=0 );
24117   if( pFile->eFileLock>SHARED_LOCK ){
24118     assert( pInode->eFileLock==pFile->eFileLock );
24119     SimulateIOErrorBenign(1);
24120     SimulateIOError( h=(-1) )
24121     SimulateIOErrorBenign(0);
24122
24123 #ifndef NDEBUG
24124     /* When reducing a lock such that other processes can start
24125     ** reading the database file again, make sure that the
24126     ** transaction counter was updated if any part of the database
24127     ** file changed.  If the transaction counter is not updated,
24128     ** other connections to the same file might not realize that
24129     ** the file has changed and hence might not know to flush their
24130     ** cache.  The use of a stale cache can lead to database corruption.
24131     */
24132 #if 0
24133     assert( pFile->inNormalWrite==0
24134          || pFile->dbUpdate==0
24135          || pFile->transCntrChng==1 );
24136 #endif
24137     pFile->inNormalWrite = 0;
24138 #endif
24139
24140     /* downgrading to a shared lock on NFS involves clearing the write lock
24141     ** before establishing the readlock - to avoid a race condition we downgrade
24142     ** the lock in 2 blocks, so that part of the range will be covered by a 
24143     ** write lock until the rest is covered by a read lock:
24144     **  1:   [WWWWW]
24145     **  2:   [....W]
24146     **  3:   [RRRRW]
24147     **  4:   [RRRR.]
24148     */
24149     if( eFileLock==SHARED_LOCK ){
24150       if( handleNFSUnlock ){
24151         off_t divSize = SHARED_SIZE - 1;
24152         
24153         lock.l_type = F_UNLCK;
24154         lock.l_whence = SEEK_SET;
24155         lock.l_start = SHARED_FIRST;
24156         lock.l_len = divSize;
24157         if( fcntl(h, F_SETLK, &lock)==(-1) ){
24158           tErrno = errno;
24159           rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
24160           if( IS_LOCK_ERROR(rc) ){
24161             pFile->lastErrno = tErrno;
24162           }
24163           goto end_unlock;
24164         }
24165         lock.l_type = F_RDLCK;
24166         lock.l_whence = SEEK_SET;
24167         lock.l_start = SHARED_FIRST;
24168         lock.l_len = divSize;
24169         if( fcntl(h, F_SETLK, &lock)==(-1) ){
24170           tErrno = errno;
24171           rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
24172           if( IS_LOCK_ERROR(rc) ){
24173             pFile->lastErrno = tErrno;
24174           }
24175           goto end_unlock;
24176         }
24177         lock.l_type = F_UNLCK;
24178         lock.l_whence = SEEK_SET;
24179         lock.l_start = SHARED_FIRST+divSize;
24180         lock.l_len = SHARED_SIZE-divSize;
24181         if( fcntl(h, F_SETLK, &lock)==(-1) ){
24182           tErrno = errno;
24183           rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
24184           if( IS_LOCK_ERROR(rc) ){
24185             pFile->lastErrno = tErrno;
24186           }
24187           goto end_unlock;
24188         }
24189       }else{
24190         lock.l_type = F_RDLCK;
24191         lock.l_whence = SEEK_SET;
24192         lock.l_start = SHARED_FIRST;
24193         lock.l_len = SHARED_SIZE;
24194         if( fcntl(h, F_SETLK, &lock)==(-1) ){
24195           tErrno = errno;
24196           rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
24197           if( IS_LOCK_ERROR(rc) ){
24198             pFile->lastErrno = tErrno;
24199           }
24200           goto end_unlock;
24201         }
24202       }
24203     }
24204     lock.l_type = F_UNLCK;
24205     lock.l_whence = SEEK_SET;
24206     lock.l_start = PENDING_BYTE;
24207     lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
24208     if( fcntl(h, F_SETLK, &lock)!=(-1) ){
24209       pInode->eFileLock = SHARED_LOCK;
24210     }else{
24211       tErrno = errno;
24212       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
24213       if( IS_LOCK_ERROR(rc) ){
24214         pFile->lastErrno = tErrno;
24215       }
24216       goto end_unlock;
24217     }
24218   }
24219   if( eFileLock==NO_LOCK ){
24220     /* Decrement the shared lock counter.  Release the lock using an
24221     ** OS call only when all threads in this same process have released
24222     ** the lock.
24223     */
24224     pInode->nShared--;
24225     if( pInode->nShared==0 ){
24226       lock.l_type = F_UNLCK;
24227       lock.l_whence = SEEK_SET;
24228       lock.l_start = lock.l_len = 0L;
24229       SimulateIOErrorBenign(1);
24230       SimulateIOError( h=(-1) )
24231       SimulateIOErrorBenign(0);
24232       if( fcntl(h, F_SETLK, &lock)!=(-1) ){
24233         pInode->eFileLock = NO_LOCK;
24234       }else{
24235         tErrno = errno;
24236         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
24237         if( IS_LOCK_ERROR(rc) ){
24238           pFile->lastErrno = tErrno;
24239         }
24240         pInode->eFileLock = NO_LOCK;
24241         pFile->eFileLock = NO_LOCK;
24242       }
24243     }
24244
24245     /* Decrement the count of locks against this same file.  When the
24246     ** count reaches zero, close any other file descriptors whose close
24247     ** was deferred because of outstanding locks.
24248     */
24249     pInode->nLock--;
24250     assert( pInode->nLock>=0 );
24251     if( pInode->nLock==0 ){
24252       int rc2 = closePendingFds(pFile);
24253       if( rc==SQLITE_OK ){
24254         rc = rc2;
24255       }
24256     }
24257   }
24258         
24259 end_unlock:
24260   unixLeaveMutex();
24261   if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
24262   return rc;
24263 }
24264
24265 /*
24266 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
24267 ** must be either NO_LOCK or SHARED_LOCK.
24268 **
24269 ** If the locking level of the file descriptor is already at or below
24270 ** the requested locking level, this routine is a no-op.
24271 */
24272 static int unixUnlock(sqlite3_file *id, int eFileLock){
24273   return _posixUnlock(id, eFileLock, 0);
24274 }
24275
24276 /*
24277 ** This function performs the parts of the "close file" operation 
24278 ** common to all locking schemes. It closes the directory and file
24279 ** handles, if they are valid, and sets all fields of the unixFile
24280 ** structure to 0.
24281 **
24282 ** It is *not* necessary to hold the mutex when this routine is called,
24283 ** even on VxWorks.  A mutex will be acquired on VxWorks by the
24284 ** vxworksReleaseFileId() routine.
24285 */
24286 static int closeUnixFile(sqlite3_file *id){
24287   unixFile *pFile = (unixFile*)id;
24288   if( pFile ){
24289     if( pFile->dirfd>=0 ){
24290       int err = close(pFile->dirfd);
24291       if( err ){
24292         pFile->lastErrno = errno;
24293         return SQLITE_IOERR_DIR_CLOSE;
24294       }else{
24295         pFile->dirfd=-1;
24296       }
24297     }
24298     if( pFile->h>=0 ){
24299       int err = close(pFile->h);
24300       if( err ){
24301         pFile->lastErrno = errno;
24302         return SQLITE_IOERR_CLOSE;
24303       }
24304     }
24305 #if OS_VXWORKS
24306     if( pFile->pId ){
24307       if( pFile->isDelete ){
24308         unlink(pFile->pId->zCanonicalName);
24309       }
24310       vxworksReleaseFileId(pFile->pId);
24311       pFile->pId = 0;
24312     }
24313 #endif
24314     OSTRACE(("CLOSE   %-3d\n", pFile->h));
24315     OpenCounter(-1);
24316     sqlite3_free(pFile->pUnused);
24317     memset(pFile, 0, sizeof(unixFile));
24318   }
24319   return SQLITE_OK;
24320 }
24321
24322 /*
24323 ** Close a file.
24324 */
24325 static int unixClose(sqlite3_file *id){
24326   int rc = SQLITE_OK;
24327   if( id ){
24328     unixFile *pFile = (unixFile *)id;
24329     unixUnlock(id, NO_LOCK);
24330     unixEnterMutex();
24331     if( pFile->pInode && pFile->pInode->nLock ){
24332       /* If there are outstanding locks, do not actually close the file just
24333       ** yet because that would clear those locks.  Instead, add the file
24334       ** descriptor to pInode->pUnused list.  It will be automatically closed 
24335       ** when the last lock is cleared.
24336       */
24337       setPendingFd(pFile);
24338     }
24339     releaseInodeInfo(pFile);
24340     rc = closeUnixFile(id);
24341     unixLeaveMutex();
24342   }
24343   return rc;
24344 }
24345
24346 /************** End of the posix advisory lock implementation *****************
24347 ******************************************************************************/
24348
24349 /******************************************************************************
24350 ****************************** No-op Locking **********************************
24351 **
24352 ** Of the various locking implementations available, this is by far the
24353 ** simplest:  locking is ignored.  No attempt is made to lock the database
24354 ** file for reading or writing.
24355 **
24356 ** This locking mode is appropriate for use on read-only databases
24357 ** (ex: databases that are burned into CD-ROM, for example.)  It can
24358 ** also be used if the application employs some external mechanism to
24359 ** prevent simultaneous access of the same database by two or more
24360 ** database connections.  But there is a serious risk of database
24361 ** corruption if this locking mode is used in situations where multiple
24362 ** database connections are accessing the same database file at the same
24363 ** time and one or more of those connections are writing.
24364 */
24365
24366 static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
24367   UNUSED_PARAMETER(NotUsed);
24368   *pResOut = 0;
24369   return SQLITE_OK;
24370 }
24371 static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
24372   UNUSED_PARAMETER2(NotUsed, NotUsed2);
24373   return SQLITE_OK;
24374 }
24375 static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
24376   UNUSED_PARAMETER2(NotUsed, NotUsed2);
24377   return SQLITE_OK;
24378 }
24379
24380 /*
24381 ** Close the file.
24382 */
24383 static int nolockClose(sqlite3_file *id) {
24384   return closeUnixFile(id);
24385 }
24386
24387 /******************* End of the no-op lock implementation *********************
24388 ******************************************************************************/
24389
24390 /******************************************************************************
24391 ************************* Begin dot-file Locking ******************************
24392 **
24393 ** The dotfile locking implementation uses the existance of separate lock
24394 ** files in order to control access to the database.  This works on just
24395 ** about every filesystem imaginable.  But there are serious downsides:
24396 **
24397 **    (1)  There is zero concurrency.  A single reader blocks all other
24398 **         connections from reading or writing the database.
24399 **
24400 **    (2)  An application crash or power loss can leave stale lock files
24401 **         sitting around that need to be cleared manually.
24402 **
24403 ** Nevertheless, a dotlock is an appropriate locking mode for use if no
24404 ** other locking strategy is available.
24405 **
24406 ** Dotfile locking works by creating a file in the same directory as the
24407 ** database and with the same name but with a ".lock" extension added.
24408 ** The existance of a lock file implies an EXCLUSIVE lock.  All other lock
24409 ** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
24410 */
24411
24412 /*
24413 ** The file suffix added to the data base filename in order to create the
24414 ** lock file.
24415 */
24416 #define DOTLOCK_SUFFIX ".lock"
24417
24418 /*
24419 ** This routine checks if there is a RESERVED lock held on the specified
24420 ** file by this or any other process. If such a lock is held, set *pResOut
24421 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
24422 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
24423 **
24424 ** In dotfile locking, either a lock exists or it does not.  So in this
24425 ** variation of CheckReservedLock(), *pResOut is set to true if any lock
24426 ** is held on the file and false if the file is unlocked.
24427 */
24428 static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
24429   int rc = SQLITE_OK;
24430   int reserved = 0;
24431   unixFile *pFile = (unixFile*)id;
24432
24433   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
24434   
24435   assert( pFile );
24436
24437   /* Check if a thread in this process holds such a lock */
24438   if( pFile->eFileLock>SHARED_LOCK ){
24439     /* Either this connection or some other connection in the same process
24440     ** holds a lock on the file.  No need to check further. */
24441     reserved = 1;
24442   }else{
24443     /* The lock is held if and only if the lockfile exists */
24444     const char *zLockFile = (const char*)pFile->lockingContext;
24445     reserved = access(zLockFile, 0)==0;
24446   }
24447   OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
24448   *pResOut = reserved;
24449   return rc;
24450 }
24451
24452 /*
24453 ** Lock the file with the lock specified by parameter eFileLock - one
24454 ** of the following:
24455 **
24456 **     (1) SHARED_LOCK
24457 **     (2) RESERVED_LOCK
24458 **     (3) PENDING_LOCK
24459 **     (4) EXCLUSIVE_LOCK
24460 **
24461 ** Sometimes when requesting one lock state, additional lock states
24462 ** are inserted in between.  The locking might fail on one of the later
24463 ** transitions leaving the lock state different from what it started but
24464 ** still short of its goal.  The following chart shows the allowed
24465 ** transitions and the inserted intermediate states:
24466 **
24467 **    UNLOCKED -> SHARED
24468 **    SHARED -> RESERVED
24469 **    SHARED -> (PENDING) -> EXCLUSIVE
24470 **    RESERVED -> (PENDING) -> EXCLUSIVE
24471 **    PENDING -> EXCLUSIVE
24472 **
24473 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
24474 ** routine to lower a locking level.
24475 **
24476 ** With dotfile locking, we really only support state (4): EXCLUSIVE.
24477 ** But we track the other locking levels internally.
24478 */
24479 static int dotlockLock(sqlite3_file *id, int eFileLock) {
24480   unixFile *pFile = (unixFile*)id;
24481   int fd;
24482   char *zLockFile = (char *)pFile->lockingContext;
24483   int rc = SQLITE_OK;
24484
24485
24486   /* If we have any lock, then the lock file already exists.  All we have
24487   ** to do is adjust our internal record of the lock level.
24488   */
24489   if( pFile->eFileLock > NO_LOCK ){
24490     pFile->eFileLock = eFileLock;
24491 #if !OS_VXWORKS
24492     /* Always update the timestamp on the old file */
24493     utimes(zLockFile, NULL);
24494 #endif
24495     return SQLITE_OK;
24496   }
24497   
24498   /* grab an exclusive lock */
24499   fd = open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
24500   if( fd<0 ){
24501     /* failed to open/create the file, someone else may have stolen the lock */
24502     int tErrno = errno;
24503     if( EEXIST == tErrno ){
24504       rc = SQLITE_BUSY;
24505     } else {
24506       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
24507       if( IS_LOCK_ERROR(rc) ){
24508         pFile->lastErrno = tErrno;
24509       }
24510     }
24511     return rc;
24512   } 
24513   if( close(fd) ){
24514     pFile->lastErrno = errno;
24515     rc = SQLITE_IOERR_CLOSE;
24516   }
24517   
24518   /* got it, set the type and return ok */
24519   pFile->eFileLock = eFileLock;
24520   return rc;
24521 }
24522
24523 /*
24524 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
24525 ** must be either NO_LOCK or SHARED_LOCK.
24526 **
24527 ** If the locking level of the file descriptor is already at or below
24528 ** the requested locking level, this routine is a no-op.
24529 **
24530 ** When the locking level reaches NO_LOCK, delete the lock file.
24531 */
24532 static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
24533   unixFile *pFile = (unixFile*)id;
24534   char *zLockFile = (char *)pFile->lockingContext;
24535
24536   assert( pFile );
24537   OSTRACE(("UNLOCK  %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
24538            pFile->eFileLock, getpid()));
24539   assert( eFileLock<=SHARED_LOCK );
24540   
24541   /* no-op if possible */
24542   if( pFile->eFileLock==eFileLock ){
24543     return SQLITE_OK;
24544   }
24545
24546   /* To downgrade to shared, simply update our internal notion of the
24547   ** lock state.  No need to mess with the file on disk.
24548   */
24549   if( eFileLock==SHARED_LOCK ){
24550     pFile->eFileLock = SHARED_LOCK;
24551     return SQLITE_OK;
24552   }
24553   
24554   /* To fully unlock the database, delete the lock file */
24555   assert( eFileLock==NO_LOCK );
24556   if( unlink(zLockFile) ){
24557     int rc = 0;
24558     int tErrno = errno;
24559     if( ENOENT != tErrno ){
24560       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
24561     }
24562     if( IS_LOCK_ERROR(rc) ){
24563       pFile->lastErrno = tErrno;
24564     }
24565     return rc; 
24566   }
24567   pFile->eFileLock = NO_LOCK;
24568   return SQLITE_OK;
24569 }
24570
24571 /*
24572 ** Close a file.  Make sure the lock has been released before closing.
24573 */
24574 static int dotlockClose(sqlite3_file *id) {
24575   int rc;
24576   if( id ){
24577     unixFile *pFile = (unixFile*)id;
24578     dotlockUnlock(id, NO_LOCK);
24579     sqlite3_free(pFile->lockingContext);
24580   }
24581   rc = closeUnixFile(id);
24582   return rc;
24583 }
24584 /****************** End of the dot-file lock implementation *******************
24585 ******************************************************************************/
24586
24587 /******************************************************************************
24588 ************************** Begin flock Locking ********************************
24589 **
24590 ** Use the flock() system call to do file locking.
24591 **
24592 ** flock() locking is like dot-file locking in that the various
24593 ** fine-grain locking levels supported by SQLite are collapsed into
24594 ** a single exclusive lock.  In other words, SHARED, RESERVED, and
24595 ** PENDING locks are the same thing as an EXCLUSIVE lock.  SQLite
24596 ** still works when you do this, but concurrency is reduced since
24597 ** only a single process can be reading the database at a time.
24598 **
24599 ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
24600 ** compiling for VXWORKS.
24601 */
24602 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
24603
24604 /*
24605 ** This routine checks if there is a RESERVED lock held on the specified
24606 ** file by this or any other process. If such a lock is held, set *pResOut
24607 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
24608 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
24609 */
24610 static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
24611   int rc = SQLITE_OK;
24612   int reserved = 0;
24613   unixFile *pFile = (unixFile*)id;
24614   
24615   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
24616   
24617   assert( pFile );
24618   
24619   /* Check if a thread in this process holds such a lock */
24620   if( pFile->eFileLock>SHARED_LOCK ){
24621     reserved = 1;
24622   }
24623   
24624   /* Otherwise see if some other process holds it. */
24625   if( !reserved ){
24626     /* attempt to get the lock */
24627     int lrc = flock(pFile->h, LOCK_EX | LOCK_NB);
24628     if( !lrc ){
24629       /* got the lock, unlock it */
24630       lrc = flock(pFile->h, LOCK_UN);
24631       if ( lrc ) {
24632         int tErrno = errno;
24633         /* unlock failed with an error */
24634         lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK); 
24635         if( IS_LOCK_ERROR(lrc) ){
24636           pFile->lastErrno = tErrno;
24637           rc = lrc;
24638         }
24639       }
24640     } else {
24641       int tErrno = errno;
24642       reserved = 1;
24643       /* someone else might have it reserved */
24644       lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK); 
24645       if( IS_LOCK_ERROR(lrc) ){
24646         pFile->lastErrno = tErrno;
24647         rc = lrc;
24648       }
24649     }
24650   }
24651   OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
24652
24653 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
24654   if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
24655     rc = SQLITE_OK;
24656     reserved=1;
24657   }
24658 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
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 ** flock() only really support EXCLUSIVE locks.  We track intermediate
24685 ** lock states in the sqlite3_file structure, but all locks SHARED or
24686 ** above are really EXCLUSIVE locks and exclude all other processes from
24687 ** access the file.
24688 **
24689 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
24690 ** routine to lower a locking level.
24691 */
24692 static int flockLock(sqlite3_file *id, int eFileLock) {
24693   int rc = SQLITE_OK;
24694   unixFile *pFile = (unixFile*)id;
24695
24696   assert( pFile );
24697
24698   /* if we already have a lock, it is exclusive.  
24699   ** Just adjust level and punt on outta here. */
24700   if (pFile->eFileLock > NO_LOCK) {
24701     pFile->eFileLock = eFileLock;
24702     return SQLITE_OK;
24703   }
24704   
24705   /* grab an exclusive lock */
24706   
24707   if (flock(pFile->h, LOCK_EX | LOCK_NB)) {
24708     int tErrno = errno;
24709     /* didn't get, must be busy */
24710     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
24711     if( IS_LOCK_ERROR(rc) ){
24712       pFile->lastErrno = tErrno;
24713     }
24714   } else {
24715     /* got it, set the type and return ok */
24716     pFile->eFileLock = eFileLock;
24717   }
24718   OSTRACE(("LOCK    %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock), 
24719            rc==SQLITE_OK ? "ok" : "failed"));
24720 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
24721   if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
24722     rc = SQLITE_BUSY;
24723   }
24724 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
24725   return rc;
24726 }
24727
24728
24729 /*
24730 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
24731 ** must be either NO_LOCK or SHARED_LOCK.
24732 **
24733 ** If the locking level of the file descriptor is already at or below
24734 ** the requested locking level, this routine is a no-op.
24735 */
24736 static int flockUnlock(sqlite3_file *id, int eFileLock) {
24737   unixFile *pFile = (unixFile*)id;
24738   
24739   assert( pFile );
24740   OSTRACE(("UNLOCK  %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
24741            pFile->eFileLock, getpid()));
24742   assert( eFileLock<=SHARED_LOCK );
24743   
24744   /* no-op if possible */
24745   if( pFile->eFileLock==eFileLock ){
24746     return SQLITE_OK;
24747   }
24748   
24749   /* shared can just be set because we always have an exclusive */
24750   if (eFileLock==SHARED_LOCK) {
24751     pFile->eFileLock = eFileLock;
24752     return SQLITE_OK;
24753   }
24754   
24755   /* no, really, unlock. */
24756   int rc = flock(pFile->h, LOCK_UN);
24757   if (rc) {
24758     int r, tErrno = errno;
24759     r = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
24760     if( IS_LOCK_ERROR(r) ){
24761       pFile->lastErrno = tErrno;
24762     }
24763 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
24764     if( (r & SQLITE_IOERR) == SQLITE_IOERR ){
24765       r = SQLITE_BUSY;
24766     }
24767 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
24768     
24769     return r;
24770   } else {
24771     pFile->eFileLock = NO_LOCK;
24772     return SQLITE_OK;
24773   }
24774 }
24775
24776 /*
24777 ** Close a file.
24778 */
24779 static int flockClose(sqlite3_file *id) {
24780   if( id ){
24781     flockUnlock(id, NO_LOCK);
24782   }
24783   return closeUnixFile(id);
24784 }
24785
24786 #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
24787
24788 /******************* End of the flock lock implementation *********************
24789 ******************************************************************************/
24790
24791 /******************************************************************************
24792 ************************ Begin Named Semaphore Locking ************************
24793 **
24794 ** Named semaphore locking is only supported on VxWorks.
24795 **
24796 ** Semaphore locking is like dot-lock and flock in that it really only
24797 ** supports EXCLUSIVE locking.  Only a single process can read or write
24798 ** the database file at a time.  This reduces potential concurrency, but
24799 ** makes the lock implementation much easier.
24800 */
24801 #if OS_VXWORKS
24802
24803 /*
24804 ** This routine checks if there is a RESERVED lock held on the specified
24805 ** file by this or any other process. If such a lock is held, set *pResOut
24806 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
24807 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
24808 */
24809 static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
24810   int rc = SQLITE_OK;
24811   int reserved = 0;
24812   unixFile *pFile = (unixFile*)id;
24813
24814   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
24815   
24816   assert( pFile );
24817
24818   /* Check if a thread in this process holds such a lock */
24819   if( pFile->eFileLock>SHARED_LOCK ){
24820     reserved = 1;
24821   }
24822   
24823   /* Otherwise see if some other process holds it. */
24824   if( !reserved ){
24825     sem_t *pSem = pFile->pInode->pSem;
24826     struct stat statBuf;
24827
24828     if( sem_trywait(pSem)==-1 ){
24829       int tErrno = errno;
24830       if( EAGAIN != tErrno ){
24831         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
24832         pFile->lastErrno = tErrno;
24833       } else {
24834         /* someone else has the lock when we are in NO_LOCK */
24835         reserved = (pFile->eFileLock < SHARED_LOCK);
24836       }
24837     }else{
24838       /* we could have it if we want it */
24839       sem_post(pSem);
24840     }
24841   }
24842   OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
24843
24844   *pResOut = reserved;
24845   return rc;
24846 }
24847
24848 /*
24849 ** Lock the file with the lock specified by parameter eFileLock - one
24850 ** of the following:
24851 **
24852 **     (1) SHARED_LOCK
24853 **     (2) RESERVED_LOCK
24854 **     (3) PENDING_LOCK
24855 **     (4) EXCLUSIVE_LOCK
24856 **
24857 ** Sometimes when requesting one lock state, additional lock states
24858 ** are inserted in between.  The locking might fail on one of the later
24859 ** transitions leaving the lock state different from what it started but
24860 ** still short of its goal.  The following chart shows the allowed
24861 ** transitions and the inserted intermediate states:
24862 **
24863 **    UNLOCKED -> SHARED
24864 **    SHARED -> RESERVED
24865 **    SHARED -> (PENDING) -> EXCLUSIVE
24866 **    RESERVED -> (PENDING) -> EXCLUSIVE
24867 **    PENDING -> EXCLUSIVE
24868 **
24869 ** Semaphore locks only really support EXCLUSIVE locks.  We track intermediate
24870 ** lock states in the sqlite3_file structure, but all locks SHARED or
24871 ** above are really EXCLUSIVE locks and exclude all other processes from
24872 ** access the file.
24873 **
24874 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
24875 ** routine to lower a locking level.
24876 */
24877 static int semLock(sqlite3_file *id, int eFileLock) {
24878   unixFile *pFile = (unixFile*)id;
24879   int fd;
24880   sem_t *pSem = pFile->pInode->pSem;
24881   int rc = SQLITE_OK;
24882
24883   /* if we already have a lock, it is exclusive.  
24884   ** Just adjust level and punt on outta here. */
24885   if (pFile->eFileLock > NO_LOCK) {
24886     pFile->eFileLock = eFileLock;
24887     rc = SQLITE_OK;
24888     goto sem_end_lock;
24889   }
24890   
24891   /* lock semaphore now but bail out when already locked. */
24892   if( sem_trywait(pSem)==-1 ){
24893     rc = SQLITE_BUSY;
24894     goto sem_end_lock;
24895   }
24896
24897   /* got it, set the type and return ok */
24898   pFile->eFileLock = eFileLock;
24899
24900  sem_end_lock:
24901   return rc;
24902 }
24903
24904 /*
24905 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
24906 ** must be either NO_LOCK or SHARED_LOCK.
24907 **
24908 ** If the locking level of the file descriptor is already at or below
24909 ** the requested locking level, this routine is a no-op.
24910 */
24911 static int semUnlock(sqlite3_file *id, int eFileLock) {
24912   unixFile *pFile = (unixFile*)id;
24913   sem_t *pSem = pFile->pInode->pSem;
24914
24915   assert( pFile );
24916   assert( pSem );
24917   OSTRACE(("UNLOCK  %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
24918            pFile->eFileLock, getpid()));
24919   assert( eFileLock<=SHARED_LOCK );
24920   
24921   /* no-op if possible */
24922   if( pFile->eFileLock==eFileLock ){
24923     return SQLITE_OK;
24924   }
24925   
24926   /* shared can just be set because we always have an exclusive */
24927   if (eFileLock==SHARED_LOCK) {
24928     pFile->eFileLock = eFileLock;
24929     return SQLITE_OK;
24930   }
24931   
24932   /* no, really unlock. */
24933   if ( sem_post(pSem)==-1 ) {
24934     int rc, tErrno = errno;
24935     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
24936     if( IS_LOCK_ERROR(rc) ){
24937       pFile->lastErrno = tErrno;
24938     }
24939     return rc; 
24940   }
24941   pFile->eFileLock = NO_LOCK;
24942   return SQLITE_OK;
24943 }
24944
24945 /*
24946  ** Close a file.
24947  */
24948 static int semClose(sqlite3_file *id) {
24949   if( id ){
24950     unixFile *pFile = (unixFile*)id;
24951     semUnlock(id, NO_LOCK);
24952     assert( pFile );
24953     unixEnterMutex();
24954     releaseInodeInfo(pFile);
24955     unixLeaveMutex();
24956     closeUnixFile(id);
24957   }
24958   return SQLITE_OK;
24959 }
24960
24961 #endif /* OS_VXWORKS */
24962 /*
24963 ** Named semaphore locking is only available on VxWorks.
24964 **
24965 *************** End of the named semaphore lock implementation ****************
24966 ******************************************************************************/
24967
24968
24969 /******************************************************************************
24970 *************************** Begin AFP Locking *********************************
24971 **
24972 ** AFP is the Apple Filing Protocol.  AFP is a network filesystem found
24973 ** on Apple Macintosh computers - both OS9 and OSX.
24974 **
24975 ** Third-party implementations of AFP are available.  But this code here
24976 ** only works on OSX.
24977 */
24978
24979 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
24980 /*
24981 ** The afpLockingContext structure contains all afp lock specific state
24982 */
24983 typedef struct afpLockingContext afpLockingContext;
24984 struct afpLockingContext {
24985   int reserved;
24986   const char *dbPath;             /* Name of the open file */
24987 };
24988
24989 struct ByteRangeLockPB2
24990 {
24991   unsigned long long offset;        /* offset to first byte to lock */
24992   unsigned long long length;        /* nbr of bytes to lock */
24993   unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
24994   unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
24995   unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
24996   int fd;                           /* file desc to assoc this lock with */
24997 };
24998
24999 #define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
25000
25001 /*
25002 ** This is a utility for setting or clearing a bit-range lock on an
25003 ** AFP filesystem.
25004 ** 
25005 ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
25006 */
25007 static int afpSetLock(
25008   const char *path,              /* Name of the file to be locked or unlocked */
25009   unixFile *pFile,               /* Open file descriptor on path */
25010   unsigned long long offset,     /* First byte to be locked */
25011   unsigned long long length,     /* Number of bytes to lock */
25012   int setLockFlag                /* True to set lock.  False to clear lock */
25013 ){
25014   struct ByteRangeLockPB2 pb;
25015   int err;
25016   
25017   pb.unLockFlag = setLockFlag ? 0 : 1;
25018   pb.startEndFlag = 0;
25019   pb.offset = offset;
25020   pb.length = length; 
25021   pb.fd = pFile->h;
25022   
25023   OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n", 
25024     (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
25025     offset, length));
25026   err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
25027   if ( err==-1 ) {
25028     int rc;
25029     int tErrno = errno;
25030     OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
25031              path, tErrno, strerror(tErrno)));
25032 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
25033     rc = SQLITE_BUSY;
25034 #else
25035     rc = sqliteErrorFromPosixError(tErrno,
25036                     setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
25037 #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
25038     if( IS_LOCK_ERROR(rc) ){
25039       pFile->lastErrno = tErrno;
25040     }
25041     return rc;
25042   } else {
25043     return SQLITE_OK;
25044   }
25045 }
25046
25047 /*
25048 ** This routine checks if there is a RESERVED lock held on the specified
25049 ** file by this or any other process. If such a lock is held, set *pResOut
25050 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
25051 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
25052 */
25053 static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
25054   int rc = SQLITE_OK;
25055   int reserved = 0;
25056   unixFile *pFile = (unixFile*)id;
25057   
25058   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
25059   
25060   assert( pFile );
25061   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
25062   if( context->reserved ){
25063     *pResOut = 1;
25064     return SQLITE_OK;
25065   }
25066   unixEnterMutex(); /* Because pFile->pInode is shared across threads */
25067   
25068   /* Check if a thread in this process holds such a lock */
25069   if( pFile->pInode->eFileLock>SHARED_LOCK ){
25070     reserved = 1;
25071   }
25072   
25073   /* Otherwise see if some other process holds it.
25074    */
25075   if( !reserved ){
25076     /* lock the RESERVED byte */
25077     int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);  
25078     if( SQLITE_OK==lrc ){
25079       /* if we succeeded in taking the reserved lock, unlock it to restore
25080       ** the original state */
25081       lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
25082     } else {
25083       /* if we failed to get the lock then someone else must have it */
25084       reserved = 1;
25085     }
25086     if( IS_LOCK_ERROR(lrc) ){
25087       rc=lrc;
25088     }
25089   }
25090   
25091   unixLeaveMutex();
25092   OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
25093   
25094   *pResOut = reserved;
25095   return rc;
25096 }
25097
25098 /*
25099 ** Lock the file with the lock specified by parameter eFileLock - one
25100 ** of the following:
25101 **
25102 **     (1) SHARED_LOCK
25103 **     (2) RESERVED_LOCK
25104 **     (3) PENDING_LOCK
25105 **     (4) EXCLUSIVE_LOCK
25106 **
25107 ** Sometimes when requesting one lock state, additional lock states
25108 ** are inserted in between.  The locking might fail on one of the later
25109 ** transitions leaving the lock state different from what it started but
25110 ** still short of its goal.  The following chart shows the allowed
25111 ** transitions and the inserted intermediate states:
25112 **
25113 **    UNLOCKED -> SHARED
25114 **    SHARED -> RESERVED
25115 **    SHARED -> (PENDING) -> EXCLUSIVE
25116 **    RESERVED -> (PENDING) -> EXCLUSIVE
25117 **    PENDING -> EXCLUSIVE
25118 **
25119 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
25120 ** routine to lower a locking level.
25121 */
25122 static int afpLock(sqlite3_file *id, int eFileLock){
25123   int rc = SQLITE_OK;
25124   unixFile *pFile = (unixFile*)id;
25125   unixInodeInfo *pInode = pFile->pInode;
25126   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
25127   
25128   assert( pFile );
25129   OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
25130            azFileLock(eFileLock), azFileLock(pFile->eFileLock),
25131            azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
25132
25133   /* If there is already a lock of this type or more restrictive on the
25134   ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
25135   ** unixEnterMutex() hasn't been called yet.
25136   */
25137   if( pFile->eFileLock>=eFileLock ){
25138     OSTRACE(("LOCK    %d %s ok (already held) (afp)\n", pFile->h,
25139            azFileLock(eFileLock)));
25140     return SQLITE_OK;
25141   }
25142
25143   /* Make sure the locking sequence is correct
25144   **  (1) We never move from unlocked to anything higher than shared lock.
25145   **  (2) SQLite never explicitly requests a pendig lock.
25146   **  (3) A shared lock is always held when a reserve lock is requested.
25147   */
25148   assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
25149   assert( eFileLock!=PENDING_LOCK );
25150   assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
25151   
25152   /* This mutex is needed because pFile->pInode is shared across threads
25153   */
25154   unixEnterMutex();
25155   pInode = pFile->pInode;
25156
25157   /* If some thread using this PID has a lock via a different unixFile*
25158   ** handle that precludes the requested lock, return BUSY.
25159   */
25160   if( (pFile->eFileLock!=pInode->eFileLock && 
25161        (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
25162      ){
25163     rc = SQLITE_BUSY;
25164     goto afp_end_lock;
25165   }
25166   
25167   /* If a SHARED lock is requested, and some thread using this PID already
25168   ** has a SHARED or RESERVED lock, then increment reference counts and
25169   ** return SQLITE_OK.
25170   */
25171   if( eFileLock==SHARED_LOCK && 
25172      (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
25173     assert( eFileLock==SHARED_LOCK );
25174     assert( pFile->eFileLock==0 );
25175     assert( pInode->nShared>0 );
25176     pFile->eFileLock = SHARED_LOCK;
25177     pInode->nShared++;
25178     pInode->nLock++;
25179     goto afp_end_lock;
25180   }
25181     
25182   /* A PENDING lock is needed before acquiring a SHARED lock and before
25183   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
25184   ** be released.
25185   */
25186   if( eFileLock==SHARED_LOCK 
25187       || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
25188   ){
25189     int failed;
25190     failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
25191     if (failed) {
25192       rc = failed;
25193       goto afp_end_lock;
25194     }
25195   }
25196   
25197   /* If control gets to this point, then actually go ahead and make
25198   ** operating system calls for the specified lock.
25199   */
25200   if( eFileLock==SHARED_LOCK ){
25201     int lrc1, lrc2, lrc1Errno;
25202     long lk, mask;
25203     
25204     assert( pInode->nShared==0 );
25205     assert( pInode->eFileLock==0 );
25206         
25207     mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
25208     /* Now get the read-lock SHARED_LOCK */
25209     /* note that the quality of the randomness doesn't matter that much */
25210     lk = random(); 
25211     pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
25212     lrc1 = afpSetLock(context->dbPath, pFile, 
25213           SHARED_FIRST+pInode->sharedByte, 1, 1);
25214     if( IS_LOCK_ERROR(lrc1) ){
25215       lrc1Errno = pFile->lastErrno;
25216     }
25217     /* Drop the temporary PENDING lock */
25218     lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
25219     
25220     if( IS_LOCK_ERROR(lrc1) ) {
25221       pFile->lastErrno = lrc1Errno;
25222       rc = lrc1;
25223       goto afp_end_lock;
25224     } else if( IS_LOCK_ERROR(lrc2) ){
25225       rc = lrc2;
25226       goto afp_end_lock;
25227     } else if( lrc1 != SQLITE_OK ) {
25228       rc = lrc1;
25229     } else {
25230       pFile->eFileLock = SHARED_LOCK;
25231       pInode->nLock++;
25232       pInode->nShared = 1;
25233     }
25234   }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
25235     /* We are trying for an exclusive lock but another thread in this
25236      ** same process is still holding a shared lock. */
25237     rc = SQLITE_BUSY;
25238   }else{
25239     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
25240     ** assumed that there is a SHARED or greater lock on the file
25241     ** already.
25242     */
25243     int failed = 0;
25244     assert( 0!=pFile->eFileLock );
25245     if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
25246         /* Acquire a RESERVED lock */
25247         failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
25248       if( !failed ){
25249         context->reserved = 1;
25250       }
25251     }
25252     if (!failed && eFileLock == EXCLUSIVE_LOCK) {
25253       /* Acquire an EXCLUSIVE lock */
25254         
25255       /* Remove the shared lock before trying the range.  we'll need to 
25256       ** reestablish the shared lock if we can't get the  afpUnlock
25257       */
25258       if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
25259                          pInode->sharedByte, 1, 0)) ){
25260         int failed2 = SQLITE_OK;
25261         /* now attemmpt to get the exclusive lock range */
25262         failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST, 
25263                                SHARED_SIZE, 1);
25264         if( failed && (failed2 = afpSetLock(context->dbPath, pFile, 
25265                        SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
25266           /* Can't reestablish the shared lock.  Sqlite can't deal, this is
25267           ** a critical I/O error
25268           */
25269           rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 : 
25270                SQLITE_IOERR_LOCK;
25271           goto afp_end_lock;
25272         } 
25273       }else{
25274         rc = failed; 
25275       }
25276     }
25277     if( failed ){
25278       rc = failed;
25279     }
25280   }
25281   
25282   if( rc==SQLITE_OK ){
25283     pFile->eFileLock = eFileLock;
25284     pInode->eFileLock = eFileLock;
25285   }else if( eFileLock==EXCLUSIVE_LOCK ){
25286     pFile->eFileLock = PENDING_LOCK;
25287     pInode->eFileLock = PENDING_LOCK;
25288   }
25289   
25290 afp_end_lock:
25291   unixLeaveMutex();
25292   OSTRACE(("LOCK    %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock), 
25293          rc==SQLITE_OK ? "ok" : "failed"));
25294   return rc;
25295 }
25296
25297 /*
25298 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
25299 ** must be either NO_LOCK or SHARED_LOCK.
25300 **
25301 ** If the locking level of the file descriptor is already at or below
25302 ** the requested locking level, this routine is a no-op.
25303 */
25304 static int afpUnlock(sqlite3_file *id, int eFileLock) {
25305   int rc = SQLITE_OK;
25306   unixFile *pFile = (unixFile*)id;
25307   unixInodeInfo *pInode;
25308   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
25309   int skipShared = 0;
25310 #ifdef SQLITE_TEST
25311   int h = pFile->h;
25312 #endif
25313
25314   assert( pFile );
25315   OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
25316            pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
25317            getpid()));
25318
25319   assert( eFileLock<=SHARED_LOCK );
25320   if( pFile->eFileLock<=eFileLock ){
25321     return SQLITE_OK;
25322   }
25323   unixEnterMutex();
25324   pInode = pFile->pInode;
25325   assert( pInode->nShared!=0 );
25326   if( pFile->eFileLock>SHARED_LOCK ){
25327     assert( pInode->eFileLock==pFile->eFileLock );
25328     SimulateIOErrorBenign(1);
25329     SimulateIOError( h=(-1) )
25330     SimulateIOErrorBenign(0);
25331     
25332 #ifndef NDEBUG
25333     /* When reducing a lock such that other processes can start
25334     ** reading the database file again, make sure that the
25335     ** transaction counter was updated if any part of the database
25336     ** file changed.  If the transaction counter is not updated,
25337     ** other connections to the same file might not realize that
25338     ** the file has changed and hence might not know to flush their
25339     ** cache.  The use of a stale cache can lead to database corruption.
25340     */
25341     assert( pFile->inNormalWrite==0
25342            || pFile->dbUpdate==0
25343            || pFile->transCntrChng==1 );
25344     pFile->inNormalWrite = 0;
25345 #endif
25346     
25347     if( pFile->eFileLock==EXCLUSIVE_LOCK ){
25348       rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
25349       if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
25350         /* only re-establish the shared lock if necessary */
25351         int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
25352         rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
25353       } else {
25354         skipShared = 1;
25355       }
25356     }
25357     if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
25358       rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
25359     } 
25360     if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
25361       rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
25362       if( !rc ){ 
25363         context->reserved = 0; 
25364       }
25365     }
25366     if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
25367       pInode->eFileLock = SHARED_LOCK;
25368     }
25369   }
25370   if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
25371
25372     /* Decrement the shared lock counter.  Release the lock using an
25373     ** OS call only when all threads in this same process have released
25374     ** the lock.
25375     */
25376     unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
25377     pInode->nShared--;
25378     if( pInode->nShared==0 ){
25379       SimulateIOErrorBenign(1);
25380       SimulateIOError( h=(-1) )
25381       SimulateIOErrorBenign(0);
25382       if( !skipShared ){
25383         rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
25384       }
25385       if( !rc ){
25386         pInode->eFileLock = NO_LOCK;
25387         pFile->eFileLock = NO_LOCK;
25388       }
25389     }
25390     if( rc==SQLITE_OK ){
25391       pInode->nLock--;
25392       assert( pInode->nLock>=0 );
25393       if( pInode->nLock==0 ){
25394         rc = closePendingFds(pFile);
25395       }
25396     }
25397   }
25398   
25399   unixLeaveMutex();
25400   if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
25401   return rc;
25402 }
25403
25404 /*
25405 ** Close a file & cleanup AFP specific locking context 
25406 */
25407 static int afpClose(sqlite3_file *id) {
25408   int rc = SQLITE_OK;
25409   if( id ){
25410     unixFile *pFile = (unixFile*)id;
25411     afpUnlock(id, NO_LOCK);
25412     unixEnterMutex();
25413     if( pFile->pInode && pFile->pInode->nLock ){
25414       /* If there are outstanding locks, do not actually close the file just
25415       ** yet because that would clear those locks.  Instead, add the file
25416       ** descriptor to pInode->aPending.  It will be automatically closed when
25417       ** the last lock is cleared.
25418       */
25419       setPendingFd(pFile);
25420     }
25421     releaseInodeInfo(pFile);
25422     sqlite3_free(pFile->lockingContext);
25423     rc = closeUnixFile(id);
25424     unixLeaveMutex();
25425   }
25426   return rc;
25427 }
25428
25429 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
25430 /*
25431 ** The code above is the AFP lock implementation.  The code is specific
25432 ** to MacOSX and does not work on other unix platforms.  No alternative
25433 ** is available.  If you don't compile for a mac, then the "unix-afp"
25434 ** VFS is not available.
25435 **
25436 ********************* End of the AFP lock implementation **********************
25437 ******************************************************************************/
25438
25439 /******************************************************************************
25440 *************************** Begin NFS Locking ********************************/
25441
25442 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
25443 /*
25444  ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
25445  ** must be either NO_LOCK or SHARED_LOCK.
25446  **
25447  ** If the locking level of the file descriptor is already at or below
25448  ** the requested locking level, this routine is a no-op.
25449  */
25450 static int nfsUnlock(sqlite3_file *id, int eFileLock){
25451   return _posixUnlock(id, eFileLock, 1);
25452 }
25453
25454 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
25455 /*
25456 ** The code above is the NFS lock implementation.  The code is specific
25457 ** to MacOSX and does not work on other unix platforms.  No alternative
25458 ** is available.  
25459 **
25460 ********************* End of the NFS lock implementation **********************
25461 ******************************************************************************/
25462
25463 /******************************************************************************
25464 **************** Non-locking sqlite3_file methods *****************************
25465 **
25466 ** The next division contains implementations for all methods of the 
25467 ** sqlite3_file object other than the locking methods.  The locking
25468 ** methods were defined in divisions above (one locking method per
25469 ** division).  Those methods that are common to all locking modes
25470 ** are gather together into this division.
25471 */
25472
25473 /*
25474 ** Seek to the offset passed as the second argument, then read cnt 
25475 ** bytes into pBuf. Return the number of bytes actually read.
25476 **
25477 ** NB:  If you define USE_PREAD or USE_PREAD64, then it might also
25478 ** be necessary to define _XOPEN_SOURCE to be 500.  This varies from
25479 ** one system to another.  Since SQLite does not define USE_PREAD
25480 ** any any form by default, we will not attempt to define _XOPEN_SOURCE.
25481 ** See tickets #2741 and #2681.
25482 **
25483 ** To avoid stomping the errno value on a failed read the lastErrno value
25484 ** is set before returning.
25485 */
25486 static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
25487   int got;
25488 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
25489   i64 newOffset;
25490 #endif
25491   TIMER_START;
25492 #if defined(USE_PREAD)
25493   got = pread(id->h, pBuf, cnt, offset);
25494   SimulateIOError( got = -1 );
25495 #elif defined(USE_PREAD64)
25496   got = pread64(id->h, pBuf, cnt, offset);
25497   SimulateIOError( got = -1 );
25498 #else
25499   newOffset = lseek(id->h, offset, SEEK_SET);
25500   SimulateIOError( newOffset-- );
25501   if( newOffset!=offset ){
25502     if( newOffset == -1 ){
25503       ((unixFile*)id)->lastErrno = errno;
25504     }else{
25505       ((unixFile*)id)->lastErrno = 0;                   
25506     }
25507     return -1;
25508   }
25509   got = read(id->h, pBuf, cnt);
25510 #endif
25511   TIMER_END;
25512   if( got<0 ){
25513     ((unixFile*)id)->lastErrno = errno;
25514   }
25515   OSTRACE(("READ    %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
25516   return got;
25517 }
25518
25519 /*
25520 ** Read data from a file into a buffer.  Return SQLITE_OK if all
25521 ** bytes were read successfully and SQLITE_IOERR if anything goes
25522 ** wrong.
25523 */
25524 static int unixRead(
25525   sqlite3_file *id, 
25526   void *pBuf, 
25527   int amt,
25528   sqlite3_int64 offset
25529 ){
25530   unixFile *pFile = (unixFile *)id;
25531   int got;
25532   assert( id );
25533
25534   /* If this is a database file (not a journal, master-journal or temp
25535   ** file), the bytes in the locking range should never be read or written. */
25536 #if 0
25537   assert( pFile->pUnused==0
25538        || offset>=PENDING_BYTE+512
25539        || offset+amt<=PENDING_BYTE 
25540   );
25541 #endif
25542
25543   got = seekAndRead(pFile, offset, pBuf, amt);
25544   if( got==amt ){
25545     return SQLITE_OK;
25546   }else if( got<0 ){
25547     /* lastErrno set by seekAndRead */
25548     return SQLITE_IOERR_READ;
25549   }else{
25550     pFile->lastErrno = 0; /* not a system error */
25551     /* Unread parts of the buffer must be zero-filled */
25552     memset(&((char*)pBuf)[got], 0, amt-got);
25553     return SQLITE_IOERR_SHORT_READ;
25554   }
25555 }
25556
25557 /*
25558 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
25559 ** Return the number of bytes actually read.  Update the offset.
25560 **
25561 ** To avoid stomping the errno value on a failed write the lastErrno value
25562 ** is set before returning.
25563 */
25564 static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
25565   int got;
25566 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
25567   i64 newOffset;
25568 #endif
25569   TIMER_START;
25570 #if defined(USE_PREAD)
25571   got = pwrite(id->h, pBuf, cnt, offset);
25572 #elif defined(USE_PREAD64)
25573   got = pwrite64(id->h, pBuf, cnt, offset);
25574 #else
25575   newOffset = lseek(id->h, offset, SEEK_SET);
25576   if( newOffset!=offset ){
25577     if( newOffset == -1 ){
25578       ((unixFile*)id)->lastErrno = errno;
25579     }else{
25580       ((unixFile*)id)->lastErrno = 0;                   
25581     }
25582     return -1;
25583   }
25584   got = write(id->h, pBuf, cnt);
25585 #endif
25586   TIMER_END;
25587   if( got<0 ){
25588     ((unixFile*)id)->lastErrno = errno;
25589   }
25590
25591   OSTRACE(("WRITE   %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
25592   return got;
25593 }
25594
25595
25596 /*
25597 ** Write data from a buffer into a file.  Return SQLITE_OK on success
25598 ** or some other error code on failure.
25599 */
25600 static int unixWrite(
25601   sqlite3_file *id, 
25602   const void *pBuf, 
25603   int amt,
25604   sqlite3_int64 offset 
25605 ){
25606   unixFile *pFile = (unixFile*)id;
25607   int wrote = 0;
25608   assert( id );
25609   assert( amt>0 );
25610
25611   /* If this is a database file (not a journal, master-journal or temp
25612   ** file), the bytes in the locking range should never be read or written. */
25613 #if 0
25614   assert( pFile->pUnused==0
25615        || offset>=PENDING_BYTE+512
25616        || offset+amt<=PENDING_BYTE 
25617   );
25618 #endif
25619
25620 #ifndef NDEBUG
25621   /* If we are doing a normal write to a database file (as opposed to
25622   ** doing a hot-journal rollback or a write to some file other than a
25623   ** normal database file) then record the fact that the database
25624   ** has changed.  If the transaction counter is modified, record that
25625   ** fact too.
25626   */
25627   if( pFile->inNormalWrite ){
25628     pFile->dbUpdate = 1;  /* The database has been modified */
25629     if( offset<=24 && offset+amt>=27 ){
25630       int rc;
25631       char oldCntr[4];
25632       SimulateIOErrorBenign(1);
25633       rc = seekAndRead(pFile, 24, oldCntr, 4);
25634       SimulateIOErrorBenign(0);
25635       if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
25636         pFile->transCntrChng = 1;  /* The transaction counter has changed */
25637       }
25638     }
25639   }
25640 #endif
25641
25642   while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
25643     amt -= wrote;
25644     offset += wrote;
25645     pBuf = &((char*)pBuf)[wrote];
25646   }
25647   SimulateIOError(( wrote=(-1), amt=1 ));
25648   SimulateDiskfullError(( wrote=0, amt=1 ));
25649
25650   if( amt>0 ){
25651     if( wrote<0 ){
25652       /* lastErrno set by seekAndWrite */
25653       return SQLITE_IOERR_WRITE;
25654     }else{
25655       pFile->lastErrno = 0; /* not a system error */
25656       return SQLITE_FULL;
25657     }
25658   }
25659
25660   return SQLITE_OK;
25661 }
25662
25663 #ifdef SQLITE_TEST
25664 /*
25665 ** Count the number of fullsyncs and normal syncs.  This is used to test
25666 ** that syncs and fullsyncs are occurring at the right times.
25667 */
25668 SQLITE_API int sqlite3_sync_count = 0;
25669 SQLITE_API int sqlite3_fullsync_count = 0;
25670 #endif
25671
25672 /*
25673 ** We do not trust systems to provide a working fdatasync().  Some do.
25674 ** Others do no.  To be safe, we will stick with the (slower) fsync().
25675 ** If you know that your system does support fdatasync() correctly,
25676 ** then simply compile with -Dfdatasync=fdatasync
25677 */
25678 #if !defined(fdatasync) && !defined(__linux__)
25679 # define fdatasync fsync
25680 #endif
25681
25682 /*
25683 ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
25684 ** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
25685 ** only available on Mac OS X.  But that could change.
25686 */
25687 #ifdef F_FULLFSYNC
25688 # define HAVE_FULLFSYNC 1
25689 #else
25690 # define HAVE_FULLFSYNC 0
25691 #endif
25692
25693
25694 /*
25695 ** The fsync() system call does not work as advertised on many
25696 ** unix systems.  The following procedure is an attempt to make
25697 ** it work better.
25698 **
25699 ** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
25700 ** for testing when we want to run through the test suite quickly.
25701 ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
25702 ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
25703 ** or power failure will likely corrupt the database file.
25704 **
25705 ** SQLite sets the dataOnly flag if the size of the file is unchanged.
25706 ** The idea behind dataOnly is that it should only write the file content
25707 ** to disk, not the inode.  We only set dataOnly if the file size is 
25708 ** unchanged since the file size is part of the inode.  However, 
25709 ** Ted Ts'o tells us that fdatasync() will also write the inode if the
25710 ** file size has changed.  The only real difference between fdatasync()
25711 ** and fsync(), Ted tells us, is that fdatasync() will not flush the
25712 ** inode if the mtime or owner or other inode attributes have changed.
25713 ** We only care about the file size, not the other file attributes, so
25714 ** as far as SQLite is concerned, an fdatasync() is always adequate.
25715 ** So, we always use fdatasync() if it is available, regardless of
25716 ** the value of the dataOnly flag.
25717 */
25718 static int full_fsync(int fd, int fullSync, int dataOnly){
25719   int rc;
25720
25721   /* The following "ifdef/elif/else/" block has the same structure as
25722   ** the one below. It is replicated here solely to avoid cluttering 
25723   ** up the real code with the UNUSED_PARAMETER() macros.
25724   */
25725 #ifdef SQLITE_NO_SYNC
25726   UNUSED_PARAMETER(fd);
25727   UNUSED_PARAMETER(fullSync);
25728   UNUSED_PARAMETER(dataOnly);
25729 #elif HAVE_FULLFSYNC
25730   UNUSED_PARAMETER(dataOnly);
25731 #else
25732   UNUSED_PARAMETER(fullSync);
25733   UNUSED_PARAMETER(dataOnly);
25734 #endif
25735
25736   /* Record the number of times that we do a normal fsync() and 
25737   ** FULLSYNC.  This is used during testing to verify that this procedure
25738   ** gets called with the correct arguments.
25739   */
25740 #ifdef SQLITE_TEST
25741   if( fullSync ) sqlite3_fullsync_count++;
25742   sqlite3_sync_count++;
25743 #endif
25744
25745   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
25746   ** no-op
25747   */
25748 #ifdef SQLITE_NO_SYNC
25749   rc = SQLITE_OK;
25750 #elif HAVE_FULLFSYNC
25751   if( fullSync ){
25752     rc = fcntl(fd, F_FULLFSYNC, 0);
25753   }else{
25754     rc = 1;
25755   }
25756   /* If the FULLFSYNC failed, fall back to attempting an fsync().
25757   ** It shouldn't be possible for fullfsync to fail on the local 
25758   ** file system (on OSX), so failure indicates that FULLFSYNC
25759   ** isn't supported for this file system. So, attempt an fsync 
25760   ** and (for now) ignore the overhead of a superfluous fcntl call.  
25761   ** It'd be better to detect fullfsync support once and avoid 
25762   ** the fcntl call every time sync is called.
25763   */
25764   if( rc ) rc = fsync(fd);
25765
25766 #elif defined(__APPLE__)
25767   /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
25768   ** so currently we default to the macro that redefines fdatasync to fsync
25769   */
25770   rc = fsync(fd);
25771 #else 
25772   rc = fdatasync(fd);
25773 #if OS_VXWORKS
25774   if( rc==-1 && errno==ENOTSUP ){
25775     rc = fsync(fd);
25776   }
25777 #endif /* OS_VXWORKS */
25778 #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
25779
25780   if( OS_VXWORKS && rc!= -1 ){
25781     rc = 0;
25782   }
25783   return rc;
25784 }
25785
25786 /*
25787 ** Make sure all writes to a particular file are committed to disk.
25788 **
25789 ** If dataOnly==0 then both the file itself and its metadata (file
25790 ** size, access time, etc) are synced.  If dataOnly!=0 then only the
25791 ** file data is synced.
25792 **
25793 ** Under Unix, also make sure that the directory entry for the file
25794 ** has been created by fsync-ing the directory that contains the file.
25795 ** If we do not do this and we encounter a power failure, the directory
25796 ** entry for the journal might not exist after we reboot.  The next
25797 ** SQLite to access the file will not know that the journal exists (because
25798 ** the directory entry for the journal was never created) and the transaction
25799 ** will not roll back - possibly leading to database corruption.
25800 */
25801 static int unixSync(sqlite3_file *id, int flags){
25802   int rc;
25803   unixFile *pFile = (unixFile*)id;
25804
25805   int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
25806   int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
25807
25808   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
25809   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
25810       || (flags&0x0F)==SQLITE_SYNC_FULL
25811   );
25812
25813   /* Unix cannot, but some systems may return SQLITE_FULL from here. This
25814   ** line is to test that doing so does not cause any problems.
25815   */
25816   SimulateDiskfullError( return SQLITE_FULL );
25817
25818   assert( pFile );
25819   OSTRACE(("SYNC    %-3d\n", pFile->h));
25820   rc = full_fsync(pFile->h, isFullsync, isDataOnly);
25821   SimulateIOError( rc=1 );
25822   if( rc ){
25823     pFile->lastErrno = errno;
25824     return SQLITE_IOERR_FSYNC;
25825   }
25826   if( pFile->dirfd>=0 ){
25827     int err;
25828     OSTRACE(("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
25829             HAVE_FULLFSYNC, isFullsync));
25830 #ifndef SQLITE_DISABLE_DIRSYNC
25831     /* The directory sync is only attempted if full_fsync is
25832     ** turned off or unavailable.  If a full_fsync occurred above,
25833     ** then the directory sync is superfluous.
25834     */
25835     if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
25836        /*
25837        ** We have received multiple reports of fsync() returning
25838        ** errors when applied to directories on certain file systems.
25839        ** A failed directory sync is not a big deal.  So it seems
25840        ** better to ignore the error.  Ticket #1657
25841        */
25842        /* pFile->lastErrno = errno; */
25843        /* return SQLITE_IOERR; */
25844     }
25845 #endif
25846     err = close(pFile->dirfd); /* Only need to sync once, so close the */
25847     if( err==0 ){              /* directory when we are done */
25848       pFile->dirfd = -1;
25849     }else{
25850       pFile->lastErrno = errno;
25851       rc = SQLITE_IOERR_DIR_CLOSE;
25852     }
25853   }
25854   return rc;
25855 }
25856
25857 /*
25858 ** Truncate an open file to a specified size
25859 */
25860 static int unixTruncate(sqlite3_file *id, i64 nByte){
25861   unixFile *pFile = (unixFile *)id;
25862   int rc;
25863   assert( pFile );
25864   SimulateIOError( return SQLITE_IOERR_TRUNCATE );
25865
25866   /* If the user has configured a chunk-size for this file, truncate the
25867   ** file so that it consists of an integer number of chunks (i.e. the
25868   ** actual file size after the operation may be larger than the requested
25869   ** size).
25870   */
25871   if( pFile->szChunk ){
25872     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
25873   }
25874
25875   rc = ftruncate(pFile->h, (off_t)nByte);
25876   if( rc ){
25877     pFile->lastErrno = errno;
25878     return SQLITE_IOERR_TRUNCATE;
25879   }else{
25880 #ifndef NDEBUG
25881     /* If we are doing a normal write to a database file (as opposed to
25882     ** doing a hot-journal rollback or a write to some file other than a
25883     ** normal database file) and we truncate the file to zero length,
25884     ** that effectively updates the change counter.  This might happen
25885     ** when restoring a database using the backup API from a zero-length
25886     ** source.
25887     */
25888     if( pFile->inNormalWrite && nByte==0 ){
25889       pFile->transCntrChng = 1;
25890     }
25891 #endif
25892
25893     return SQLITE_OK;
25894   }
25895 }
25896
25897 /*
25898 ** Determine the current size of a file in bytes
25899 */
25900 static int unixFileSize(sqlite3_file *id, i64 *pSize){
25901   int rc;
25902   struct stat buf;
25903   assert( id );
25904   rc = fstat(((unixFile*)id)->h, &buf);
25905   SimulateIOError( rc=1 );
25906   if( rc!=0 ){
25907     ((unixFile*)id)->lastErrno = errno;
25908     return SQLITE_IOERR_FSTAT;
25909   }
25910   *pSize = buf.st_size;
25911
25912   /* When opening a zero-size database, the findInodeInfo() procedure
25913   ** writes a single byte into that file in order to work around a bug
25914   ** in the OS-X msdos filesystem.  In order to avoid problems with upper
25915   ** layers, we need to report this file size as zero even though it is
25916   ** really 1.   Ticket #3260.
25917   */
25918   if( *pSize==1 ) *pSize = 0;
25919
25920
25921   return SQLITE_OK;
25922 }
25923
25924 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
25925 /*
25926 ** Handler for proxy-locking file-control verbs.  Defined below in the
25927 ** proxying locking division.
25928 */
25929 static int proxyFileControl(sqlite3_file*,int,void*);
25930 #endif
25931
25932 /* 
25933 ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT 
25934 ** file-control operation.
25935 **
25936 ** If the user has configured a chunk-size for this file, it could be
25937 ** that the file needs to be extended at this point. Otherwise, the
25938 ** SQLITE_FCNTL_SIZE_HINT operation is a no-op for Unix.
25939 */
25940 static int fcntlSizeHint(unixFile *pFile, i64 nByte){
25941   if( pFile->szChunk ){
25942     i64 nSize;                    /* Required file size */
25943     struct stat buf;              /* Used to hold return values of fstat() */
25944    
25945     if( fstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
25946
25947     nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
25948     if( nSize>(i64)buf.st_size ){
25949 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
25950       if( posix_fallocate(pFile->h, buf.st_size, nSize-buf.st_size) ){
25951         return SQLITE_IOERR_WRITE;
25952       }
25953 #else
25954       /* If the OS does not have posix_fallocate(), fake it. First use
25955       ** ftruncate() to set the file size, then write a single byte to
25956       ** the last byte in each block within the extended region. This
25957       ** is the same technique used by glibc to implement posix_fallocate()
25958       ** on systems that do not have a real fallocate() system call.
25959       */
25960       int nBlk = buf.st_blksize;  /* File-system block size */
25961       i64 iWrite;                 /* Next offset to write to */
25962       int nWrite;                 /* Return value from seekAndWrite() */
25963
25964       if( ftruncate(pFile->h, nSize) ){
25965         pFile->lastErrno = errno;
25966         return SQLITE_IOERR_TRUNCATE;
25967       }
25968       iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
25969       do {
25970         nWrite = seekAndWrite(pFile, iWrite, "", 1);
25971         iWrite += nBlk;
25972       } while( nWrite==1 && iWrite<nSize );
25973       if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
25974 #endif
25975     }
25976   }
25977
25978   return SQLITE_OK;
25979 }
25980
25981 /*
25982 ** Information and control of an open file handle.
25983 */
25984 static int unixFileControl(sqlite3_file *id, int op, void *pArg){
25985   switch( op ){
25986     case SQLITE_FCNTL_LOCKSTATE: {
25987       *(int*)pArg = ((unixFile*)id)->eFileLock;
25988       return SQLITE_OK;
25989     }
25990     case SQLITE_LAST_ERRNO: {
25991       *(int*)pArg = ((unixFile*)id)->lastErrno;
25992       return SQLITE_OK;
25993     }
25994     case SQLITE_FCNTL_CHUNK_SIZE: {
25995       ((unixFile*)id)->szChunk = *(int *)pArg;
25996       return SQLITE_OK;
25997     }
25998     case SQLITE_FCNTL_SIZE_HINT: {
25999       return fcntlSizeHint((unixFile *)id, *(i64 *)pArg);
26000     }
26001 #ifndef NDEBUG
26002     /* The pager calls this method to signal that it has done
26003     ** a rollback and that the database is therefore unchanged and
26004     ** it hence it is OK for the transaction change counter to be
26005     ** unchanged.
26006     */
26007     case SQLITE_FCNTL_DB_UNCHANGED: {
26008       ((unixFile*)id)->dbUpdate = 0;
26009       return SQLITE_OK;
26010     }
26011 #endif
26012 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
26013     case SQLITE_SET_LOCKPROXYFILE:
26014     case SQLITE_GET_LOCKPROXYFILE: {
26015       return proxyFileControl(id,op,pArg);
26016     }
26017 #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
26018   }
26019   return SQLITE_ERROR;
26020 }
26021
26022 /*
26023 ** Return the sector size in bytes of the underlying block device for
26024 ** the specified file. This is almost always 512 bytes, but may be
26025 ** larger for some devices.
26026 **
26027 ** SQLite code assumes this function cannot fail. It also assumes that
26028 ** if two files are created in the same file-system directory (i.e.
26029 ** a database and its journal file) that the sector size will be the
26030 ** same for both.
26031 */
26032 static int unixSectorSize(sqlite3_file *NotUsed){
26033   UNUSED_PARAMETER(NotUsed);
26034   return SQLITE_DEFAULT_SECTOR_SIZE;
26035 }
26036
26037 /*
26038 ** Return the device characteristics for the file. This is always 0 for unix.
26039 */
26040 static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
26041   UNUSED_PARAMETER(NotUsed);
26042   return 0;
26043 }
26044
26045 #ifndef SQLITE_OMIT_WAL
26046
26047
26048 /*
26049 ** Object used to represent an shared memory buffer.  
26050 **
26051 ** When multiple threads all reference the same wal-index, each thread
26052 ** has its own unixShm object, but they all point to a single instance
26053 ** of this unixShmNode object.  In other words, each wal-index is opened
26054 ** only once per process.
26055 **
26056 ** Each unixShmNode object is connected to a single unixInodeInfo object.
26057 ** We could coalesce this object into unixInodeInfo, but that would mean
26058 ** every open file that does not use shared memory (in other words, most
26059 ** open files) would have to carry around this extra information.  So
26060 ** the unixInodeInfo object contains a pointer to this unixShmNode object
26061 ** and the unixShmNode object is created only when needed.
26062 **
26063 ** unixMutexHeld() must be true when creating or destroying
26064 ** this object or while reading or writing the following fields:
26065 **
26066 **      nRef
26067 **
26068 ** The following fields are read-only after the object is created:
26069 ** 
26070 **      fid
26071 **      zFilename
26072 **
26073 ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
26074 ** unixMutexHeld() is true when reading or writing any other field
26075 ** in this structure.
26076 */
26077 struct unixShmNode {
26078   unixInodeInfo *pInode;     /* unixInodeInfo that owns this SHM node */
26079   sqlite3_mutex *mutex;      /* Mutex to access this object */
26080   char *zFilename;           /* Name of the mmapped file */
26081   int h;                     /* Open file descriptor */
26082   int szRegion;              /* Size of shared-memory regions */
26083   int nRegion;               /* Size of array apRegion */
26084   char **apRegion;           /* Array of mapped shared-memory regions */
26085   int nRef;                  /* Number of unixShm objects pointing to this */
26086   unixShm *pFirst;           /* All unixShm objects pointing to this */
26087 #ifdef SQLITE_DEBUG
26088   u8 exclMask;               /* Mask of exclusive locks held */
26089   u8 sharedMask;             /* Mask of shared locks held */
26090   u8 nextShmId;              /* Next available unixShm.id value */
26091 #endif
26092 };
26093
26094 /*
26095 ** Structure used internally by this VFS to record the state of an
26096 ** open shared memory connection.
26097 **
26098 ** The following fields are initialized when this object is created and
26099 ** are read-only thereafter:
26100 **
26101 **    unixShm.pFile
26102 **    unixShm.id
26103 **
26104 ** All other fields are read/write.  The unixShm.pFile->mutex must be held
26105 ** while accessing any read/write fields.
26106 */
26107 struct unixShm {
26108   unixShmNode *pShmNode;     /* The underlying unixShmNode object */
26109   unixShm *pNext;            /* Next unixShm with the same unixShmNode */
26110   u8 hasMutex;               /* True if holding the unixShmNode mutex */
26111   u16 sharedMask;            /* Mask of shared locks held */
26112   u16 exclMask;              /* Mask of exclusive locks held */
26113 #ifdef SQLITE_DEBUG
26114   u8 id;                     /* Id of this connection within its unixShmNode */
26115 #endif
26116 };
26117
26118 /*
26119 ** Constants used for locking
26120 */
26121 #define UNIX_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)         /* first lock byte */
26122 #define UNIX_SHM_DMS    (UNIX_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
26123
26124 /*
26125 ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
26126 **
26127 ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
26128 ** otherwise.
26129 */
26130 static int unixShmSystemLock(
26131   unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
26132   int lockType,          /* F_UNLCK, F_RDLCK, or F_WRLCK */
26133   int ofst,              /* First byte of the locking range */
26134   int n                  /* Number of bytes to lock */
26135 ){
26136   struct flock f;       /* The posix advisory locking structure */
26137   int rc = SQLITE_OK;   /* Result code form fcntl() */
26138
26139   /* Access to the unixShmNode object is serialized by the caller */
26140   assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
26141
26142   /* Shared locks never span more than one byte */
26143   assert( n==1 || lockType!=F_RDLCK );
26144
26145   /* Locks are within range */
26146   assert( n>=1 && n<SQLITE_SHM_NLOCK );
26147
26148   /* Initialize the locking parameters */
26149   memset(&f, 0, sizeof(f));
26150   f.l_type = lockType;
26151   f.l_whence = SEEK_SET;
26152   f.l_start = ofst;
26153   f.l_len = n;
26154
26155   rc = fcntl(pShmNode->h, F_SETLK, &f);
26156   rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
26157
26158   /* Update the global lock state and do debug tracing */
26159 #ifdef SQLITE_DEBUG
26160   { u16 mask;
26161   OSTRACE(("SHM-LOCK "));
26162   mask = (1<<(ofst+n)) - (1<<ofst);
26163   if( rc==SQLITE_OK ){
26164     if( lockType==F_UNLCK ){
26165       OSTRACE(("unlock %d ok", ofst));
26166       pShmNode->exclMask &= ~mask;
26167       pShmNode->sharedMask &= ~mask;
26168     }else if( lockType==F_RDLCK ){
26169       OSTRACE(("read-lock %d ok", ofst));
26170       pShmNode->exclMask &= ~mask;
26171       pShmNode->sharedMask |= mask;
26172     }else{
26173       assert( lockType==F_WRLCK );
26174       OSTRACE(("write-lock %d ok", ofst));
26175       pShmNode->exclMask |= mask;
26176       pShmNode->sharedMask &= ~mask;
26177     }
26178   }else{
26179     if( lockType==F_UNLCK ){
26180       OSTRACE(("unlock %d failed", ofst));
26181     }else if( lockType==F_RDLCK ){
26182       OSTRACE(("read-lock failed"));
26183     }else{
26184       assert( lockType==F_WRLCK );
26185       OSTRACE(("write-lock %d failed", ofst));
26186     }
26187   }
26188   OSTRACE((" - afterwards %03x,%03x\n",
26189            pShmNode->sharedMask, pShmNode->exclMask));
26190   }
26191 #endif
26192
26193   return rc;        
26194 }
26195
26196
26197 /*
26198 ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
26199 **
26200 ** This is not a VFS shared-memory method; it is a utility function called
26201 ** by VFS shared-memory methods.
26202 */
26203 static void unixShmPurge(unixFile *pFd){
26204   unixShmNode *p = pFd->pInode->pShmNode;
26205   assert( unixMutexHeld() );
26206   if( p && p->nRef==0 ){
26207     int i;
26208     assert( p->pInode==pFd->pInode );
26209     if( p->mutex ) sqlite3_mutex_free(p->mutex);
26210     for(i=0; i<p->nRegion; i++){
26211       munmap(p->apRegion[i], p->szRegion);
26212     }
26213     sqlite3_free(p->apRegion);
26214     if( p->h>=0 ) close(p->h);
26215     p->pInode->pShmNode = 0;
26216     sqlite3_free(p);
26217   }
26218 }
26219
26220 /*
26221 ** Open a shared-memory area associated with open database file pDbFd.  
26222 ** This particular implementation uses mmapped files.
26223 **
26224 ** The file used to implement shared-memory is in the same directory
26225 ** as the open database file and has the same name as the open database
26226 ** file with the "-shm" suffix added.  For example, if the database file
26227 ** is "/home/user1/config.db" then the file that is created and mmapped
26228 ** for shared memory will be called "/home/user1/config.db-shm".  
26229 **
26230 ** Another approach to is to use files in /dev/shm or /dev/tmp or an
26231 ** some other tmpfs mount. But if a file in a different directory
26232 ** from the database file is used, then differing access permissions
26233 ** or a chroot() might cause two different processes on the same
26234 ** database to end up using different files for shared memory - 
26235 ** meaning that their memory would not really be shared - resulting
26236 ** in database corruption.  Nevertheless, this tmpfs file usage
26237 ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
26238 ** or the equivalent.  The use of the SQLITE_SHM_DIRECTORY compile-time
26239 ** option results in an incompatible build of SQLite;  builds of SQLite
26240 ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
26241 ** same database file at the same time, database corruption will likely
26242 ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
26243 ** "unsupported" and may go away in a future SQLite release.
26244 **
26245 ** When opening a new shared-memory file, if no other instances of that
26246 ** file are currently open, in this process or in other processes, then
26247 ** the file must be truncated to zero length or have its header cleared.
26248 */
26249 static int unixOpenSharedMemory(unixFile *pDbFd){
26250   struct unixShm *p = 0;          /* The connection to be opened */
26251   struct unixShmNode *pShmNode;   /* The underlying mmapped file */
26252   int rc;                         /* Result code */
26253   unixInodeInfo *pInode;          /* The inode of fd */
26254   char *zShmFilename;             /* Name of the file used for SHM */
26255   int nShmFilename;               /* Size of the SHM filename in bytes */
26256
26257   /* Allocate space for the new unixShm object. */
26258   p = sqlite3_malloc( sizeof(*p) );
26259   if( p==0 ) return SQLITE_NOMEM;
26260   memset(p, 0, sizeof(*p));
26261   assert( pDbFd->pShm==0 );
26262
26263   /* Check to see if a unixShmNode object already exists. Reuse an existing
26264   ** one if present. Create a new one if necessary.
26265   */
26266   unixEnterMutex();
26267   pInode = pDbFd->pInode;
26268   pShmNode = pInode->pShmNode;
26269   if( pShmNode==0 ){
26270     struct stat sStat;                 /* fstat() info for database file */
26271
26272     /* Call fstat() to figure out the permissions on the database file. If
26273     ** a new *-shm file is created, an attempt will be made to create it
26274     ** with the same permissions. The actual permissions the file is created
26275     ** with are subject to the current umask setting.
26276     */
26277     if( fstat(pDbFd->h, &sStat) ){
26278       rc = SQLITE_IOERR_FSTAT;
26279       goto shm_open_err;
26280     }
26281
26282 #ifdef SQLITE_SHM_DIRECTORY
26283     nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 30;
26284 #else
26285     nShmFilename = 5 + (int)strlen(pDbFd->zPath);
26286 #endif
26287     pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
26288     if( pShmNode==0 ){
26289       rc = SQLITE_NOMEM;
26290       goto shm_open_err;
26291     }
26292     memset(pShmNode, 0, sizeof(*pShmNode));
26293     zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
26294 #ifdef SQLITE_SHM_DIRECTORY
26295     sqlite3_snprintf(nShmFilename, zShmFilename, 
26296                      SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
26297                      (u32)sStat.st_ino, (u32)sStat.st_dev);
26298 #else
26299     sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
26300 #endif
26301     pShmNode->h = -1;
26302     pDbFd->pInode->pShmNode = pShmNode;
26303     pShmNode->pInode = pDbFd->pInode;
26304     pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
26305     if( pShmNode->mutex==0 ){
26306       rc = SQLITE_NOMEM;
26307       goto shm_open_err;
26308     }
26309
26310     pShmNode->h = open(zShmFilename, O_RDWR|O_CREAT, (sStat.st_mode & 0777));
26311     if( pShmNode->h<0 ){
26312       rc = SQLITE_CANTOPEN_BKPT;
26313       goto shm_open_err;
26314     }
26315
26316     /* Check to see if another process is holding the dead-man switch.
26317     ** If not, truncate the file to zero length. 
26318     */
26319     rc = SQLITE_OK;
26320     if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
26321       if( ftruncate(pShmNode->h, 0) ){
26322         rc = SQLITE_IOERR_SHMOPEN;
26323       }
26324     }
26325     if( rc==SQLITE_OK ){
26326       rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
26327     }
26328     if( rc ) goto shm_open_err;
26329   }
26330
26331   /* Make the new connection a child of the unixShmNode */
26332   p->pShmNode = pShmNode;
26333 #ifdef SQLITE_DEBUG
26334   p->id = pShmNode->nextShmId++;
26335 #endif
26336   pShmNode->nRef++;
26337   pDbFd->pShm = p;
26338   unixLeaveMutex();
26339
26340   /* The reference count on pShmNode has already been incremented under
26341   ** the cover of the unixEnterMutex() mutex and the pointer from the
26342   ** new (struct unixShm) object to the pShmNode has been set. All that is
26343   ** left to do is to link the new object into the linked list starting
26344   ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex 
26345   ** mutex.
26346   */
26347   sqlite3_mutex_enter(pShmNode->mutex);
26348   p->pNext = pShmNode->pFirst;
26349   pShmNode->pFirst = p;
26350   sqlite3_mutex_leave(pShmNode->mutex);
26351   return SQLITE_OK;
26352
26353   /* Jump here on any error */
26354 shm_open_err:
26355   unixShmPurge(pDbFd);       /* This call frees pShmNode if required */
26356   sqlite3_free(p);
26357   unixLeaveMutex();
26358   return rc;
26359 }
26360
26361 /*
26362 ** This function is called to obtain a pointer to region iRegion of the 
26363 ** shared-memory associated with the database file fd. Shared-memory regions 
26364 ** are numbered starting from zero. Each shared-memory region is szRegion 
26365 ** bytes in size.
26366 **
26367 ** If an error occurs, an error code is returned and *pp is set to NULL.
26368 **
26369 ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
26370 ** region has not been allocated (by any client, including one running in a
26371 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If 
26372 ** bExtend is non-zero and the requested shared-memory region has not yet 
26373 ** been allocated, it is allocated by this function.
26374 **
26375 ** If the shared-memory region has already been allocated or is allocated by
26376 ** this call as described above, then it is mapped into this processes 
26377 ** address space (if it is not already), *pp is set to point to the mapped 
26378 ** memory and SQLITE_OK returned.
26379 */
26380 static int unixShmMap(
26381   sqlite3_file *fd,               /* Handle open on database file */
26382   int iRegion,                    /* Region to retrieve */
26383   int szRegion,                   /* Size of regions */
26384   int bExtend,                    /* True to extend file if necessary */
26385   void volatile **pp              /* OUT: Mapped memory */
26386 ){
26387   unixFile *pDbFd = (unixFile*)fd;
26388   unixShm *p;
26389   unixShmNode *pShmNode;
26390   int rc = SQLITE_OK;
26391
26392   /* If the shared-memory file has not yet been opened, open it now. */
26393   if( pDbFd->pShm==0 ){
26394     rc = unixOpenSharedMemory(pDbFd);
26395     if( rc!=SQLITE_OK ) return rc;
26396   }
26397
26398   p = pDbFd->pShm;
26399   pShmNode = p->pShmNode;
26400   sqlite3_mutex_enter(pShmNode->mutex);
26401   assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
26402
26403   if( pShmNode->nRegion<=iRegion ){
26404     char **apNew;                      /* New apRegion[] array */
26405     int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
26406     struct stat sStat;                 /* Used by fstat() */
26407
26408     pShmNode->szRegion = szRegion;
26409
26410     /* The requested region is not mapped into this processes address space.
26411     ** Check to see if it has been allocated (i.e. if the wal-index file is
26412     ** large enough to contain the requested region).
26413     */
26414     if( fstat(pShmNode->h, &sStat) ){
26415       rc = SQLITE_IOERR_SHMSIZE;
26416       goto shmpage_out;
26417     }
26418
26419     if( sStat.st_size<nByte ){
26420       /* The requested memory region does not exist. If bExtend is set to
26421       ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
26422       **
26423       ** Alternatively, if bExtend is true, use ftruncate() to allocate
26424       ** the requested memory region.
26425       */
26426       if( !bExtend ) goto shmpage_out;
26427       if( ftruncate(pShmNode->h, nByte) ){
26428         rc = SQLITE_IOERR_SHMSIZE;
26429         goto shmpage_out;
26430       }
26431     }
26432
26433     /* Map the requested memory region into this processes address space. */
26434     apNew = (char **)sqlite3_realloc(
26435         pShmNode->apRegion, (iRegion+1)*sizeof(char *)
26436     );
26437     if( !apNew ){
26438       rc = SQLITE_IOERR_NOMEM;
26439       goto shmpage_out;
26440     }
26441     pShmNode->apRegion = apNew;
26442     while(pShmNode->nRegion<=iRegion){
26443       void *pMem = mmap(0, szRegion, PROT_READ|PROT_WRITE, 
26444           MAP_SHARED, pShmNode->h, pShmNode->nRegion*szRegion
26445       );
26446       if( pMem==MAP_FAILED ){
26447         rc = SQLITE_IOERR;
26448         goto shmpage_out;
26449       }
26450       pShmNode->apRegion[pShmNode->nRegion] = pMem;
26451       pShmNode->nRegion++;
26452     }
26453   }
26454
26455 shmpage_out:
26456   if( pShmNode->nRegion>iRegion ){
26457     *pp = pShmNode->apRegion[iRegion];
26458   }else{
26459     *pp = 0;
26460   }
26461   sqlite3_mutex_leave(pShmNode->mutex);
26462   return rc;
26463 }
26464
26465 /*
26466 ** Change the lock state for a shared-memory segment.
26467 **
26468 ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
26469 ** different here than in posix.  In xShmLock(), one can go from unlocked
26470 ** to shared and back or from unlocked to exclusive and back.  But one may
26471 ** not go from shared to exclusive or from exclusive to shared.
26472 */
26473 static int unixShmLock(
26474   sqlite3_file *fd,          /* Database file holding the shared memory */
26475   int ofst,                  /* First lock to acquire or release */
26476   int n,                     /* Number of locks to acquire or release */
26477   int flags                  /* What to do with the lock */
26478 ){
26479   unixFile *pDbFd = (unixFile*)fd;      /* Connection holding shared memory */
26480   unixShm *p = pDbFd->pShm;             /* The shared memory being locked */
26481   unixShm *pX;                          /* For looping over all siblings */
26482   unixShmNode *pShmNode = p->pShmNode;  /* The underlying file iNode */
26483   int rc = SQLITE_OK;                   /* Result code */
26484   u16 mask;                             /* Mask of locks to take or release */
26485
26486   assert( pShmNode==pDbFd->pInode->pShmNode );
26487   assert( pShmNode->pInode==pDbFd->pInode );
26488   assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
26489   assert( n>=1 );
26490   assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
26491        || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
26492        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
26493        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
26494   assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
26495
26496   mask = (1<<(ofst+n)) - (1<<ofst);
26497   assert( n>1 || mask==(1<<ofst) );
26498   sqlite3_mutex_enter(pShmNode->mutex);
26499   if( flags & SQLITE_SHM_UNLOCK ){
26500     u16 allMask = 0; /* Mask of locks held by siblings */
26501
26502     /* See if any siblings hold this same lock */
26503     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
26504       if( pX==p ) continue;
26505       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
26506       allMask |= pX->sharedMask;
26507     }
26508
26509     /* Unlock the system-level locks */
26510     if( (mask & allMask)==0 ){
26511       rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
26512     }else{
26513       rc = SQLITE_OK;
26514     }
26515
26516     /* Undo the local locks */
26517     if( rc==SQLITE_OK ){
26518       p->exclMask &= ~mask;
26519       p->sharedMask &= ~mask;
26520     } 
26521   }else if( flags & SQLITE_SHM_SHARED ){
26522     u16 allShared = 0;  /* Union of locks held by connections other than "p" */
26523
26524     /* Find out which shared locks are already held by sibling connections.
26525     ** If any sibling already holds an exclusive lock, go ahead and return
26526     ** SQLITE_BUSY.
26527     */
26528     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
26529       if( (pX->exclMask & mask)!=0 ){
26530         rc = SQLITE_BUSY;
26531         break;
26532       }
26533       allShared |= pX->sharedMask;
26534     }
26535
26536     /* Get shared locks at the system level, if necessary */
26537     if( rc==SQLITE_OK ){
26538       if( (allShared & mask)==0 ){
26539         rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
26540       }else{
26541         rc = SQLITE_OK;
26542       }
26543     }
26544
26545     /* Get the local shared locks */
26546     if( rc==SQLITE_OK ){
26547       p->sharedMask |= mask;
26548     }
26549   }else{
26550     /* Make sure no sibling connections hold locks that will block this
26551     ** lock.  If any do, return SQLITE_BUSY right away.
26552     */
26553     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
26554       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
26555         rc = SQLITE_BUSY;
26556         break;
26557       }
26558     }
26559   
26560     /* Get the exclusive locks at the system level.  Then if successful
26561     ** also mark the local connection as being locked.
26562     */
26563     if( rc==SQLITE_OK ){
26564       rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
26565       if( rc==SQLITE_OK ){
26566         assert( (p->sharedMask & mask)==0 );
26567         p->exclMask |= mask;
26568       }
26569     }
26570   }
26571   sqlite3_mutex_leave(pShmNode->mutex);
26572   OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
26573            p->id, getpid(), p->sharedMask, p->exclMask));
26574   return rc;
26575 }
26576
26577 /*
26578 ** Implement a memory barrier or memory fence on shared memory.  
26579 **
26580 ** All loads and stores begun before the barrier must complete before
26581 ** any load or store begun after the barrier.
26582 */
26583 static void unixShmBarrier(
26584   sqlite3_file *fd                /* Database file holding the shared memory */
26585 ){
26586   UNUSED_PARAMETER(fd);
26587   unixEnterMutex();
26588   unixLeaveMutex();
26589 }
26590
26591 /*
26592 ** Close a connection to shared-memory.  Delete the underlying 
26593 ** storage if deleteFlag is true.
26594 **
26595 ** If there is no shared memory associated with the connection then this
26596 ** routine is a harmless no-op.
26597 */
26598 static int unixShmUnmap(
26599   sqlite3_file *fd,               /* The underlying database file */
26600   int deleteFlag                  /* Delete shared-memory if true */
26601 ){
26602   unixShm *p;                     /* The connection to be closed */
26603   unixShmNode *pShmNode;          /* The underlying shared-memory file */
26604   unixShm **pp;                   /* For looping over sibling connections */
26605   unixFile *pDbFd;                /* The underlying database file */
26606
26607   pDbFd = (unixFile*)fd;
26608   p = pDbFd->pShm;
26609   if( p==0 ) return SQLITE_OK;
26610   pShmNode = p->pShmNode;
26611
26612   assert( pShmNode==pDbFd->pInode->pShmNode );
26613   assert( pShmNode->pInode==pDbFd->pInode );
26614
26615   /* Remove connection p from the set of connections associated
26616   ** with pShmNode */
26617   sqlite3_mutex_enter(pShmNode->mutex);
26618   for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
26619   *pp = p->pNext;
26620
26621   /* Free the connection p */
26622   sqlite3_free(p);
26623   pDbFd->pShm = 0;
26624   sqlite3_mutex_leave(pShmNode->mutex);
26625
26626   /* If pShmNode->nRef has reached 0, then close the underlying
26627   ** shared-memory file, too */
26628   unixEnterMutex();
26629   assert( pShmNode->nRef>0 );
26630   pShmNode->nRef--;
26631   if( pShmNode->nRef==0 ){
26632     if( deleteFlag ) unlink(pShmNode->zFilename);
26633     unixShmPurge(pDbFd);
26634   }
26635   unixLeaveMutex();
26636
26637   return SQLITE_OK;
26638 }
26639
26640
26641 #else
26642 # define unixShmMap     0
26643 # define unixShmLock    0
26644 # define unixShmBarrier 0
26645 # define unixShmUnmap   0
26646 #endif /* #ifndef SQLITE_OMIT_WAL */
26647
26648 /*
26649 ** Here ends the implementation of all sqlite3_file methods.
26650 **
26651 ********************** End sqlite3_file Methods *******************************
26652 ******************************************************************************/
26653
26654 /*
26655 ** This division contains definitions of sqlite3_io_methods objects that
26656 ** implement various file locking strategies.  It also contains definitions
26657 ** of "finder" functions.  A finder-function is used to locate the appropriate
26658 ** sqlite3_io_methods object for a particular database file.  The pAppData
26659 ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
26660 ** the correct finder-function for that VFS.
26661 **
26662 ** Most finder functions return a pointer to a fixed sqlite3_io_methods
26663 ** object.  The only interesting finder-function is autolockIoFinder, which
26664 ** looks at the filesystem type and tries to guess the best locking
26665 ** strategy from that.
26666 **
26667 ** For finder-funtion F, two objects are created:
26668 **
26669 **    (1) The real finder-function named "FImpt()".
26670 **
26671 **    (2) A constant pointer to this function named just "F".
26672 **
26673 **
26674 ** A pointer to the F pointer is used as the pAppData value for VFS
26675 ** objects.  We have to do this instead of letting pAppData point
26676 ** directly at the finder-function since C90 rules prevent a void*
26677 ** from be cast into a function pointer.
26678 **
26679 **
26680 ** Each instance of this macro generates two objects:
26681 **
26682 **   *  A constant sqlite3_io_methods object call METHOD that has locking
26683 **      methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
26684 **
26685 **   *  An I/O method finder function called FINDER that returns a pointer
26686 **      to the METHOD object in the previous bullet.
26687 */
26688 #define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK)      \
26689 static const sqlite3_io_methods METHOD = {                                   \
26690    VERSION,                    /* iVersion */                                \
26691    CLOSE,                      /* xClose */                                  \
26692    unixRead,                   /* xRead */                                   \
26693    unixWrite,                  /* xWrite */                                  \
26694    unixTruncate,               /* xTruncate */                               \
26695    unixSync,                   /* xSync */                                   \
26696    unixFileSize,               /* xFileSize */                               \
26697    LOCK,                       /* xLock */                                   \
26698    UNLOCK,                     /* xUnlock */                                 \
26699    CKLOCK,                     /* xCheckReservedLock */                      \
26700    unixFileControl,            /* xFileControl */                            \
26701    unixSectorSize,             /* xSectorSize */                             \
26702    unixDeviceCharacteristics,  /* xDeviceCapabilities */                     \
26703    unixShmMap,                 /* xShmMap */                                 \
26704    unixShmLock,                /* xShmLock */                                \
26705    unixShmBarrier,             /* xShmBarrier */                             \
26706    unixShmUnmap                /* xShmUnmap */                               \
26707 };                                                                           \
26708 static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){   \
26709   UNUSED_PARAMETER(z); UNUSED_PARAMETER(p);                                  \
26710   return &METHOD;                                                            \
26711 }                                                                            \
26712 static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p)    \
26713     = FINDER##Impl;
26714
26715 /*
26716 ** Here are all of the sqlite3_io_methods objects for each of the
26717 ** locking strategies.  Functions that return pointers to these methods
26718 ** are also created.
26719 */
26720 IOMETHODS(
26721   posixIoFinder,            /* Finder function name */
26722   posixIoMethods,           /* sqlite3_io_methods object name */
26723   2,                        /* shared memory is enabled */
26724   unixClose,                /* xClose method */
26725   unixLock,                 /* xLock method */
26726   unixUnlock,               /* xUnlock method */
26727   unixCheckReservedLock     /* xCheckReservedLock method */
26728 )
26729 IOMETHODS(
26730   nolockIoFinder,           /* Finder function name */
26731   nolockIoMethods,          /* sqlite3_io_methods object name */
26732   1,                        /* shared memory is disabled */
26733   nolockClose,              /* xClose method */
26734   nolockLock,               /* xLock method */
26735   nolockUnlock,             /* xUnlock method */
26736   nolockCheckReservedLock   /* xCheckReservedLock method */
26737 )
26738 IOMETHODS(
26739   dotlockIoFinder,          /* Finder function name */
26740   dotlockIoMethods,         /* sqlite3_io_methods object name */
26741   1,                        /* shared memory is disabled */
26742   dotlockClose,             /* xClose method */
26743   dotlockLock,              /* xLock method */
26744   dotlockUnlock,            /* xUnlock method */
26745   dotlockCheckReservedLock  /* xCheckReservedLock method */
26746 )
26747
26748 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
26749 IOMETHODS(
26750   flockIoFinder,            /* Finder function name */
26751   flockIoMethods,           /* sqlite3_io_methods object name */
26752   1,                        /* shared memory is disabled */
26753   flockClose,               /* xClose method */
26754   flockLock,                /* xLock method */
26755   flockUnlock,              /* xUnlock method */
26756   flockCheckReservedLock    /* xCheckReservedLock method */
26757 )
26758 #endif
26759
26760 #if OS_VXWORKS
26761 IOMETHODS(
26762   semIoFinder,              /* Finder function name */
26763   semIoMethods,             /* sqlite3_io_methods object name */
26764   1,                        /* shared memory is disabled */
26765   semClose,                 /* xClose method */
26766   semLock,                  /* xLock method */
26767   semUnlock,                /* xUnlock method */
26768   semCheckReservedLock      /* xCheckReservedLock method */
26769 )
26770 #endif
26771
26772 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
26773 IOMETHODS(
26774   afpIoFinder,              /* Finder function name */
26775   afpIoMethods,             /* sqlite3_io_methods object name */
26776   1,                        /* shared memory is disabled */
26777   afpClose,                 /* xClose method */
26778   afpLock,                  /* xLock method */
26779   afpUnlock,                /* xUnlock method */
26780   afpCheckReservedLock      /* xCheckReservedLock method */
26781 )
26782 #endif
26783
26784 /*
26785 ** The proxy locking method is a "super-method" in the sense that it
26786 ** opens secondary file descriptors for the conch and lock files and
26787 ** it uses proxy, dot-file, AFP, and flock() locking methods on those
26788 ** secondary files.  For this reason, the division that implements
26789 ** proxy locking is located much further down in the file.  But we need
26790 ** to go ahead and define the sqlite3_io_methods and finder function
26791 ** for proxy locking here.  So we forward declare the I/O methods.
26792 */
26793 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
26794 static int proxyClose(sqlite3_file*);
26795 static int proxyLock(sqlite3_file*, int);
26796 static int proxyUnlock(sqlite3_file*, int);
26797 static int proxyCheckReservedLock(sqlite3_file*, int*);
26798 IOMETHODS(
26799   proxyIoFinder,            /* Finder function name */
26800   proxyIoMethods,           /* sqlite3_io_methods object name */
26801   1,                        /* shared memory is disabled */
26802   proxyClose,               /* xClose method */
26803   proxyLock,                /* xLock method */
26804   proxyUnlock,              /* xUnlock method */
26805   proxyCheckReservedLock    /* xCheckReservedLock method */
26806 )
26807 #endif
26808
26809 /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
26810 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
26811 IOMETHODS(
26812   nfsIoFinder,               /* Finder function name */
26813   nfsIoMethods,              /* sqlite3_io_methods object name */
26814   1,                         /* shared memory is disabled */
26815   unixClose,                 /* xClose method */
26816   unixLock,                  /* xLock method */
26817   nfsUnlock,                 /* xUnlock method */
26818   unixCheckReservedLock      /* xCheckReservedLock method */
26819 )
26820 #endif
26821
26822 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
26823 /* 
26824 ** This "finder" function attempts to determine the best locking strategy 
26825 ** for the database file "filePath".  It then returns the sqlite3_io_methods
26826 ** object that implements that strategy.
26827 **
26828 ** This is for MacOSX only.
26829 */
26830 static const sqlite3_io_methods *autolockIoFinderImpl(
26831   const char *filePath,    /* name of the database file */
26832   unixFile *pNew           /* open file object for the database file */
26833 ){
26834   static const struct Mapping {
26835     const char *zFilesystem;              /* Filesystem type name */
26836     const sqlite3_io_methods *pMethods;   /* Appropriate locking method */
26837   } aMap[] = {
26838     { "hfs",    &posixIoMethods },
26839     { "ufs",    &posixIoMethods },
26840     { "afpfs",  &afpIoMethods },
26841     { "smbfs",  &afpIoMethods },
26842     { "webdav", &nolockIoMethods },
26843     { 0, 0 }
26844   };
26845   int i;
26846   struct statfs fsInfo;
26847   struct flock lockInfo;
26848
26849   if( !filePath ){
26850     /* If filePath==NULL that means we are dealing with a transient file
26851     ** that does not need to be locked. */
26852     return &nolockIoMethods;
26853   }
26854   if( statfs(filePath, &fsInfo) != -1 ){
26855     if( fsInfo.f_flags & MNT_RDONLY ){
26856       return &nolockIoMethods;
26857     }
26858     for(i=0; aMap[i].zFilesystem; i++){
26859       if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
26860         return aMap[i].pMethods;
26861       }
26862     }
26863   }
26864
26865   /* Default case. Handles, amongst others, "nfs".
26866   ** Test byte-range lock using fcntl(). If the call succeeds, 
26867   ** assume that the file-system supports POSIX style locks. 
26868   */
26869   lockInfo.l_len = 1;
26870   lockInfo.l_start = 0;
26871   lockInfo.l_whence = SEEK_SET;
26872   lockInfo.l_type = F_RDLCK;
26873   if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
26874     if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
26875       return &nfsIoMethods;
26876     } else {
26877       return &posixIoMethods;
26878     }
26879   }else{
26880     return &dotlockIoMethods;
26881   }
26882 }
26883 static const sqlite3_io_methods 
26884   *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
26885
26886 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
26887
26888 #if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
26889 /* 
26890 ** This "finder" function attempts to determine the best locking strategy 
26891 ** for the database file "filePath".  It then returns the sqlite3_io_methods
26892 ** object that implements that strategy.
26893 **
26894 ** This is for VXWorks only.
26895 */
26896 static const sqlite3_io_methods *autolockIoFinderImpl(
26897   const char *filePath,    /* name of the database file */
26898   unixFile *pNew           /* the open file object */
26899 ){
26900   struct flock lockInfo;
26901
26902   if( !filePath ){
26903     /* If filePath==NULL that means we are dealing with a transient file
26904     ** that does not need to be locked. */
26905     return &nolockIoMethods;
26906   }
26907
26908   /* Test if fcntl() is supported and use POSIX style locks.
26909   ** Otherwise fall back to the named semaphore method.
26910   */
26911   lockInfo.l_len = 1;
26912   lockInfo.l_start = 0;
26913   lockInfo.l_whence = SEEK_SET;
26914   lockInfo.l_type = F_RDLCK;
26915   if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
26916     return &posixIoMethods;
26917   }else{
26918     return &semIoMethods;
26919   }
26920 }
26921 static const sqlite3_io_methods 
26922   *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
26923
26924 #endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
26925
26926 /*
26927 ** An abstract type for a pointer to a IO method finder function:
26928 */
26929 typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
26930
26931
26932 /****************************************************************************
26933 **************************** sqlite3_vfs methods ****************************
26934 **
26935 ** This division contains the implementation of methods on the
26936 ** sqlite3_vfs object.
26937 */
26938
26939 /*
26940 ** Initialize the contents of the unixFile structure pointed to by pId.
26941 */
26942 static int fillInUnixFile(
26943   sqlite3_vfs *pVfs,      /* Pointer to vfs object */
26944   int h,                  /* Open file descriptor of file being opened */
26945   int dirfd,              /* Directory file descriptor */
26946   sqlite3_file *pId,      /* Write to the unixFile structure here */
26947   const char *zFilename,  /* Name of the file being opened */
26948   int noLock,             /* Omit locking if true */
26949   int isDelete            /* Delete on close if true */
26950 ){
26951   const sqlite3_io_methods *pLockingStyle;
26952   unixFile *pNew = (unixFile *)pId;
26953   int rc = SQLITE_OK;
26954
26955   assert( pNew->pInode==NULL );
26956
26957   /* Parameter isDelete is only used on vxworks. Express this explicitly 
26958   ** here to prevent compiler warnings about unused parameters.
26959   */
26960   UNUSED_PARAMETER(isDelete);
26961
26962   /* Usually the path zFilename should not be a relative pathname. The
26963   ** exception is when opening the proxy "conch" file in builds that
26964   ** include the special Apple locking styles.
26965   */
26966 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
26967   assert( zFilename==0 || zFilename[0]=='/' 
26968     || pVfs->pAppData==(void*)&autolockIoFinder );
26969 #else
26970   assert( zFilename==0 || zFilename[0]=='/' );
26971 #endif
26972
26973   OSTRACE(("OPEN    %-3d %s\n", h, zFilename));
26974   pNew->h = h;
26975   pNew->dirfd = dirfd;
26976   pNew->fileFlags = 0;
26977   pNew->zPath = zFilename;
26978
26979 #if OS_VXWORKS
26980   pNew->pId = vxworksFindFileId(zFilename);
26981   if( pNew->pId==0 ){
26982     noLock = 1;
26983     rc = SQLITE_NOMEM;
26984   }
26985 #endif
26986
26987   if( noLock ){
26988     pLockingStyle = &nolockIoMethods;
26989   }else{
26990     pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
26991 #if SQLITE_ENABLE_LOCKING_STYLE
26992     /* Cache zFilename in the locking context (AFP and dotlock override) for
26993     ** proxyLock activation is possible (remote proxy is based on db name)
26994     ** zFilename remains valid until file is closed, to support */
26995     pNew->lockingContext = (void*)zFilename;
26996 #endif
26997   }
26998
26999   if( pLockingStyle == &posixIoMethods
27000 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
27001     || pLockingStyle == &nfsIoMethods
27002 #endif
27003   ){
27004     unixEnterMutex();
27005     rc = findInodeInfo(pNew, &pNew->pInode);
27006     if( rc!=SQLITE_OK ){
27007       /* If an error occured in findInodeInfo(), close the file descriptor
27008       ** immediately, before releasing the mutex. findInodeInfo() may fail
27009       ** in two scenarios:
27010       **
27011       **   (a) A call to fstat() failed.
27012       **   (b) A malloc failed.
27013       **
27014       ** Scenario (b) may only occur if the process is holding no other
27015       ** file descriptors open on the same file. If there were other file
27016       ** descriptors on this file, then no malloc would be required by
27017       ** findInodeInfo(). If this is the case, it is quite safe to close
27018       ** handle h - as it is guaranteed that no posix locks will be released
27019       ** by doing so.
27020       **
27021       ** If scenario (a) caused the error then things are not so safe. The
27022       ** implicit assumption here is that if fstat() fails, things are in
27023       ** such bad shape that dropping a lock or two doesn't matter much.
27024       */
27025       close(h);
27026       h = -1;
27027     }
27028     unixLeaveMutex();
27029   }
27030
27031 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
27032   else if( pLockingStyle == &afpIoMethods ){
27033     /* AFP locking uses the file path so it needs to be included in
27034     ** the afpLockingContext.
27035     */
27036     afpLockingContext *pCtx;
27037     pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
27038     if( pCtx==0 ){
27039       rc = SQLITE_NOMEM;
27040     }else{
27041       /* NB: zFilename exists and remains valid until the file is closed
27042       ** according to requirement F11141.  So we do not need to make a
27043       ** copy of the filename. */
27044       pCtx->dbPath = zFilename;
27045       pCtx->reserved = 0;
27046       srandomdev();
27047       unixEnterMutex();
27048       rc = findInodeInfo(pNew, &pNew->pInode);
27049       if( rc!=SQLITE_OK ){
27050         sqlite3_free(pNew->lockingContext);
27051         close(h);
27052         h = -1;
27053       }
27054       unixLeaveMutex();        
27055     }
27056   }
27057 #endif
27058
27059   else if( pLockingStyle == &dotlockIoMethods ){
27060     /* Dotfile locking uses the file path so it needs to be included in
27061     ** the dotlockLockingContext 
27062     */
27063     char *zLockFile;
27064     int nFilename;
27065     nFilename = (int)strlen(zFilename) + 6;
27066     zLockFile = (char *)sqlite3_malloc(nFilename);
27067     if( zLockFile==0 ){
27068       rc = SQLITE_NOMEM;
27069     }else{
27070       sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
27071     }
27072     pNew->lockingContext = zLockFile;
27073   }
27074
27075 #if OS_VXWORKS
27076   else if( pLockingStyle == &semIoMethods ){
27077     /* Named semaphore locking uses the file path so it needs to be
27078     ** included in the semLockingContext
27079     */
27080     unixEnterMutex();
27081     rc = findInodeInfo(pNew, &pNew->pInode);
27082     if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
27083       char *zSemName = pNew->pInode->aSemName;
27084       int n;
27085       sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
27086                        pNew->pId->zCanonicalName);
27087       for( n=1; zSemName[n]; n++ )
27088         if( zSemName[n]=='/' ) zSemName[n] = '_';
27089       pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
27090       if( pNew->pInode->pSem == SEM_FAILED ){
27091         rc = SQLITE_NOMEM;
27092         pNew->pInode->aSemName[0] = '\0';
27093       }
27094     }
27095     unixLeaveMutex();
27096   }
27097 #endif
27098   
27099   pNew->lastErrno = 0;
27100 #if OS_VXWORKS
27101   if( rc!=SQLITE_OK ){
27102     if( h>=0 ) close(h);
27103     h = -1;
27104     unlink(zFilename);
27105     isDelete = 0;
27106   }
27107   pNew->isDelete = isDelete;
27108 #endif
27109   if( rc!=SQLITE_OK ){
27110     if( dirfd>=0 ) close(dirfd); /* silent leak if fail, already in error */
27111     if( h>=0 ) close(h);
27112   }else{
27113     pNew->pMethod = pLockingStyle;
27114     OpenCounter(+1);
27115   }
27116   return rc;
27117 }
27118
27119 /*
27120 ** Open a file descriptor to the directory containing file zFilename.
27121 ** If successful, *pFd is set to the opened file descriptor and
27122 ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
27123 ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
27124 ** value.
27125 **
27126 ** If SQLITE_OK is returned, the caller is responsible for closing
27127 ** the file descriptor *pFd using close().
27128 */
27129 static int openDirectory(const char *zFilename, int *pFd){
27130   int ii;
27131   int fd = -1;
27132   char zDirname[MAX_PATHNAME+1];
27133
27134   sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
27135   for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
27136   if( ii>0 ){
27137     zDirname[ii] = '\0';
27138     fd = open(zDirname, O_RDONLY|O_BINARY, 0);
27139     if( fd>=0 ){
27140 #ifdef FD_CLOEXEC
27141       fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
27142 #endif
27143       OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
27144     }
27145   }
27146   *pFd = fd;
27147   return (fd>=0?SQLITE_OK:SQLITE_CANTOPEN_BKPT);
27148 }
27149
27150 /*
27151 ** Return the name of a directory in which to put temporary files.
27152 ** If no suitable temporary file directory can be found, return NULL.
27153 */
27154 static const char *unixTempFileDir(void){
27155   static const char *azDirs[] = {
27156      0,
27157      0,
27158      "/var/tmp",
27159      "/usr/tmp",
27160      "/tmp",
27161      0        /* List terminator */
27162   };
27163   unsigned int i;
27164   struct stat buf;
27165   const char *zDir = 0;
27166
27167   azDirs[0] = sqlite3_temp_directory;
27168   if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
27169   for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
27170     if( zDir==0 ) continue;
27171     if( stat(zDir, &buf) ) continue;
27172     if( !S_ISDIR(buf.st_mode) ) continue;
27173     if( access(zDir, 07) ) continue;
27174     break;
27175   }
27176   return zDir;
27177 }
27178
27179 /*
27180 ** Create a temporary file name in zBuf.  zBuf must be allocated
27181 ** by the calling process and must be big enough to hold at least
27182 ** pVfs->mxPathname bytes.
27183 */
27184 static int unixGetTempname(int nBuf, char *zBuf){
27185   static const unsigned char zChars[] =
27186     "abcdefghijklmnopqrstuvwxyz"
27187     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
27188     "0123456789";
27189   unsigned int i, j;
27190   const char *zDir;
27191
27192   /* It's odd to simulate an io-error here, but really this is just
27193   ** using the io-error infrastructure to test that SQLite handles this
27194   ** function failing. 
27195   */
27196   SimulateIOError( return SQLITE_IOERR );
27197
27198   zDir = unixTempFileDir();
27199   if( zDir==0 ) zDir = ".";
27200
27201   /* Check that the output buffer is large enough for the temporary file 
27202   ** name. If it is not, return SQLITE_ERROR.
27203   */
27204   if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
27205     return SQLITE_ERROR;
27206   }
27207
27208   do{
27209     sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
27210     j = (int)strlen(zBuf);
27211     sqlite3_randomness(15, &zBuf[j]);
27212     for(i=0; i<15; i++, j++){
27213       zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
27214     }
27215     zBuf[j] = 0;
27216   }while( access(zBuf,0)==0 );
27217   return SQLITE_OK;
27218 }
27219
27220 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
27221 /*
27222 ** Routine to transform a unixFile into a proxy-locking unixFile.
27223 ** Implementation in the proxy-lock division, but used by unixOpen()
27224 ** if SQLITE_PREFER_PROXY_LOCKING is defined.
27225 */
27226 static int proxyTransformUnixFile(unixFile*, const char*);
27227 #endif
27228
27229 /*
27230 ** Search for an unused file descriptor that was opened on the database 
27231 ** file (not a journal or master-journal file) identified by pathname
27232 ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
27233 ** argument to this function.
27234 **
27235 ** Such a file descriptor may exist if a database connection was closed
27236 ** but the associated file descriptor could not be closed because some
27237 ** other file descriptor open on the same file is holding a file-lock.
27238 ** Refer to comments in the unixClose() function and the lengthy comment
27239 ** describing "Posix Advisory Locking" at the start of this file for 
27240 ** further details. Also, ticket #4018.
27241 **
27242 ** If a suitable file descriptor is found, then it is returned. If no
27243 ** such file descriptor is located, -1 is returned.
27244 */
27245 static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
27246   UnixUnusedFd *pUnused = 0;
27247
27248   /* Do not search for an unused file descriptor on vxworks. Not because
27249   ** vxworks would not benefit from the change (it might, we're not sure),
27250   ** but because no way to test it is currently available. It is better 
27251   ** not to risk breaking vxworks support for the sake of such an obscure 
27252   ** feature.  */
27253 #if !OS_VXWORKS
27254   struct stat sStat;                   /* Results of stat() call */
27255
27256   /* A stat() call may fail for various reasons. If this happens, it is
27257   ** almost certain that an open() call on the same path will also fail.
27258   ** For this reason, if an error occurs in the stat() call here, it is
27259   ** ignored and -1 is returned. The caller will try to open a new file
27260   ** descriptor on the same path, fail, and return an error to SQLite.
27261   **
27262   ** Even if a subsequent open() call does succeed, the consequences of
27263   ** not searching for a resusable file descriptor are not dire.  */
27264   if( 0==stat(zPath, &sStat) ){
27265     unixInodeInfo *pInode;
27266
27267     unixEnterMutex();
27268     pInode = inodeList;
27269     while( pInode && (pInode->fileId.dev!=sStat.st_dev
27270                      || pInode->fileId.ino!=sStat.st_ino) ){
27271        pInode = pInode->pNext;
27272     }
27273     if( pInode ){
27274       UnixUnusedFd **pp;
27275       for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
27276       pUnused = *pp;
27277       if( pUnused ){
27278         *pp = pUnused->pNext;
27279       }
27280     }
27281     unixLeaveMutex();
27282   }
27283 #endif    /* if !OS_VXWORKS */
27284   return pUnused;
27285 }
27286
27287 /*
27288 ** This function is called by unixOpen() to determine the unix permissions
27289 ** to create new files with. If no error occurs, then SQLITE_OK is returned
27290 ** and a value suitable for passing as the third argument to open(2) is
27291 ** written to *pMode. If an IO error occurs, an SQLite error code is 
27292 ** returned and the value of *pMode is not modified.
27293 **
27294 ** If the file being opened is a temporary file, it is always created with
27295 ** the octal permissions 0600 (read/writable by owner only). If the file
27296 ** is a database or master journal file, it is created with the permissions 
27297 ** mask SQLITE_DEFAULT_FILE_PERMISSIONS.
27298 **
27299 ** Finally, if the file being opened is a WAL or regular journal file, then 
27300 ** this function queries the file-system for the permissions on the 
27301 ** corresponding database file and sets *pMode to this value. Whenever 
27302 ** possible, WAL and journal files are created using the same permissions 
27303 ** as the associated database file.
27304 */
27305 static int findCreateFileMode(
27306   const char *zPath,              /* Path of file (possibly) being created */
27307   int flags,                      /* Flags passed as 4th argument to xOpen() */
27308   mode_t *pMode                   /* OUT: Permissions to open file with */
27309 ){
27310   int rc = SQLITE_OK;             /* Return Code */
27311   if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
27312     char zDb[MAX_PATHNAME+1];     /* Database file path */
27313     int nDb;                      /* Number of valid bytes in zDb */
27314     struct stat sStat;            /* Output of stat() on database file */
27315
27316     nDb = sqlite3Strlen30(zPath) - ((flags & SQLITE_OPEN_WAL) ? 4 : 8);
27317     memcpy(zDb, zPath, nDb);
27318     zDb[nDb] = '\0';
27319     if( 0==stat(zDb, &sStat) ){
27320       *pMode = sStat.st_mode & 0777;
27321     }else{
27322       rc = SQLITE_IOERR_FSTAT;
27323     }
27324   }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
27325     *pMode = 0600;
27326   }else{
27327     *pMode = SQLITE_DEFAULT_FILE_PERMISSIONS;
27328   }
27329   return rc;
27330 }
27331
27332 /*
27333 ** Open the file zPath.
27334 ** 
27335 ** Previously, the SQLite OS layer used three functions in place of this
27336 ** one:
27337 **
27338 **     sqlite3OsOpenReadWrite();
27339 **     sqlite3OsOpenReadOnly();
27340 **     sqlite3OsOpenExclusive();
27341 **
27342 ** These calls correspond to the following combinations of flags:
27343 **
27344 **     ReadWrite() ->     (READWRITE | CREATE)
27345 **     ReadOnly()  ->     (READONLY) 
27346 **     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
27347 **
27348 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
27349 ** true, the file was configured to be automatically deleted when the
27350 ** file handle closed. To achieve the same effect using this new 
27351 ** interface, add the DELETEONCLOSE flag to those specified above for 
27352 ** OpenExclusive().
27353 */
27354 static int unixOpen(
27355   sqlite3_vfs *pVfs,           /* The VFS for which this is the xOpen method */
27356   const char *zPath,           /* Pathname of file to be opened */
27357   sqlite3_file *pFile,         /* The file descriptor to be filled in */
27358   int flags,                   /* Input flags to control the opening */
27359   int *pOutFlags               /* Output flags returned to SQLite core */
27360 ){
27361   unixFile *p = (unixFile *)pFile;
27362   int fd = -1;                   /* File descriptor returned by open() */
27363   int dirfd = -1;                /* Directory file descriptor */
27364   int openFlags = 0;             /* Flags to pass to open() */
27365   int eType = flags&0xFFFFFF00;  /* Type of file to open */
27366   int noLock;                    /* True to omit locking primitives */
27367   int rc = SQLITE_OK;            /* Function Return Code */
27368
27369   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
27370   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
27371   int isCreate     = (flags & SQLITE_OPEN_CREATE);
27372   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
27373   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
27374 #if SQLITE_ENABLE_LOCKING_STYLE
27375   int isAutoProxy  = (flags & SQLITE_OPEN_AUTOPROXY);
27376 #endif
27377
27378   /* If creating a master or main-file journal, this function will open
27379   ** a file-descriptor on the directory too. The first time unixSync()
27380   ** is called the directory file descriptor will be fsync()ed and close()d.
27381   */
27382   int isOpenDirectory = (isCreate && (
27383         eType==SQLITE_OPEN_MASTER_JOURNAL 
27384      || eType==SQLITE_OPEN_MAIN_JOURNAL 
27385      || eType==SQLITE_OPEN_WAL
27386   ));
27387
27388   /* If argument zPath is a NULL pointer, this function is required to open
27389   ** a temporary file. Use this buffer to store the file name in.
27390   */
27391   char zTmpname[MAX_PATHNAME+1];
27392   const char *zName = zPath;
27393
27394   /* Check the following statements are true: 
27395   **
27396   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and 
27397   **   (b) if CREATE is set, then READWRITE must also be set, and
27398   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
27399   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
27400   */
27401   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
27402   assert(isCreate==0 || isReadWrite);
27403   assert(isExclusive==0 || isCreate);
27404   assert(isDelete==0 || isCreate);
27405
27406   /* The main DB, main journal, WAL file and master journal are never 
27407   ** automatically deleted. Nor are they ever temporary files.  */
27408   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
27409   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
27410   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
27411   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
27412
27413   /* Assert that the upper layer has set one of the "file-type" flags. */
27414   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB 
27415        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL 
27416        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL 
27417        || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
27418   );
27419
27420   memset(p, 0, sizeof(unixFile));
27421
27422   if( eType==SQLITE_OPEN_MAIN_DB ){
27423     UnixUnusedFd *pUnused;
27424     pUnused = findReusableFd(zName, flags);
27425     if( pUnused ){
27426       fd = pUnused->fd;
27427     }else{
27428       pUnused = sqlite3_malloc(sizeof(*pUnused));
27429       if( !pUnused ){
27430         return SQLITE_NOMEM;
27431       }
27432     }
27433     p->pUnused = pUnused;
27434   }else if( !zName ){
27435     /* If zName is NULL, the upper layer is requesting a temp file. */
27436     assert(isDelete && !isOpenDirectory);
27437     rc = unixGetTempname(MAX_PATHNAME+1, zTmpname);
27438     if( rc!=SQLITE_OK ){
27439       return rc;
27440     }
27441     zName = zTmpname;
27442   }
27443
27444   /* Determine the value of the flags parameter passed to POSIX function
27445   ** open(). These must be calculated even if open() is not called, as
27446   ** they may be stored as part of the file handle and used by the 
27447   ** 'conch file' locking functions later on.  */
27448   if( isReadonly )  openFlags |= O_RDONLY;
27449   if( isReadWrite ) openFlags |= O_RDWR;
27450   if( isCreate )    openFlags |= O_CREAT;
27451   if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
27452   openFlags |= (O_LARGEFILE|O_BINARY);
27453
27454   if( fd<0 ){
27455     mode_t openMode;              /* Permissions to create file with */
27456     rc = findCreateFileMode(zName, flags, &openMode);
27457     if( rc!=SQLITE_OK ){
27458       assert( !p->pUnused );
27459       assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
27460       return rc;
27461     }
27462     fd = open(zName, openFlags, openMode);
27463     OSTRACE(("OPENX   %-3d %s 0%o\n", fd, zName, openFlags));
27464     if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
27465       /* Failed to open the file for read/write access. Try read-only. */
27466       flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
27467       openFlags &= ~(O_RDWR|O_CREAT);
27468       flags |= SQLITE_OPEN_READONLY;
27469       openFlags |= O_RDONLY;
27470       fd = open(zName, openFlags, openMode);
27471     }
27472     if( fd<0 ){
27473       rc = SQLITE_CANTOPEN_BKPT;
27474       goto open_finished;
27475     }
27476   }
27477   assert( fd>=0 );
27478   if( pOutFlags ){
27479     *pOutFlags = flags;
27480   }
27481
27482   if( p->pUnused ){
27483     p->pUnused->fd = fd;
27484     p->pUnused->flags = flags;
27485   }
27486
27487   if( isDelete ){
27488 #if OS_VXWORKS
27489     zPath = zName;
27490 #else
27491     unlink(zName);
27492 #endif
27493   }
27494 #if SQLITE_ENABLE_LOCKING_STYLE
27495   else{
27496     p->openFlags = openFlags;
27497   }
27498 #endif
27499
27500   if( isOpenDirectory ){
27501     rc = openDirectory(zPath, &dirfd);
27502     if( rc!=SQLITE_OK ){
27503       /* It is safe to close fd at this point, because it is guaranteed not
27504       ** to be open on a database file. If it were open on a database file,
27505       ** it would not be safe to close as this would release any locks held
27506       ** on the file by this process.  */
27507       assert( eType!=SQLITE_OPEN_MAIN_DB );
27508       close(fd);             /* silently leak if fail, already in error */
27509       goto open_finished;
27510     }
27511   }
27512
27513 #ifdef FD_CLOEXEC
27514   fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
27515 #endif
27516
27517   noLock = eType!=SQLITE_OPEN_MAIN_DB;
27518
27519   
27520 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
27521   struct statfs fsInfo;
27522   if( fstatfs(fd, &fsInfo) == -1 ){
27523     ((unixFile*)pFile)->lastErrno = errno;
27524     if( dirfd>=0 ) close(dirfd); /* silently leak if fail, in error */
27525     close(fd); /* silently leak if fail, in error */
27526     return SQLITE_IOERR_ACCESS;
27527   }
27528   if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
27529     ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
27530   }
27531 #endif
27532   
27533 #if SQLITE_ENABLE_LOCKING_STYLE
27534 #if SQLITE_PREFER_PROXY_LOCKING
27535   isAutoProxy = 1;
27536 #endif
27537   if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
27538     char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
27539     int useProxy = 0;
27540
27541     /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means 
27542     ** never use proxy, NULL means use proxy for non-local files only.  */
27543     if( envforce!=NULL ){
27544       useProxy = atoi(envforce)>0;
27545     }else{
27546       struct statfs fsInfo;
27547       if( statfs(zPath, &fsInfo) == -1 ){
27548         /* In theory, the close(fd) call is sub-optimal. If the file opened
27549         ** with fd is a database file, and there are other connections open
27550         ** on that file that are currently holding advisory locks on it,
27551         ** then the call to close() will cancel those locks. In practice,
27552         ** we're assuming that statfs() doesn't fail very often. At least
27553         ** not while other file descriptors opened by the same process on
27554         ** the same file are working.  */
27555         p->lastErrno = errno;
27556         if( dirfd>=0 ){
27557           close(dirfd); /* silently leak if fail, in error */
27558         }
27559         close(fd); /* silently leak if fail, in error */
27560         rc = SQLITE_IOERR_ACCESS;
27561         goto open_finished;
27562       }
27563       useProxy = !(fsInfo.f_flags&MNT_LOCAL);
27564     }
27565     if( useProxy ){
27566       rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
27567       if( rc==SQLITE_OK ){
27568         rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
27569         if( rc!=SQLITE_OK ){
27570           /* Use unixClose to clean up the resources added in fillInUnixFile 
27571           ** and clear all the structure's references.  Specifically, 
27572           ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op 
27573           */
27574           unixClose(pFile);
27575           return rc;
27576         }
27577       }
27578       goto open_finished;
27579     }
27580   }
27581 #endif
27582   
27583   rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
27584 open_finished:
27585   if( rc!=SQLITE_OK ){
27586     sqlite3_free(p->pUnused);
27587   }
27588   return rc;
27589 }
27590
27591
27592 /*
27593 ** Delete the file at zPath. If the dirSync argument is true, fsync()
27594 ** the directory after deleting the file.
27595 */
27596 static int unixDelete(
27597   sqlite3_vfs *NotUsed,     /* VFS containing this as the xDelete method */
27598   const char *zPath,        /* Name of file to be deleted */
27599   int dirSync               /* If true, fsync() directory after deleting file */
27600 ){
27601   int rc = SQLITE_OK;
27602   UNUSED_PARAMETER(NotUsed);
27603   SimulateIOError(return SQLITE_IOERR_DELETE);
27604   if( unlink(zPath)==(-1) && errno!=ENOENT ){
27605     return SQLITE_IOERR_DELETE;
27606   }
27607 #ifndef SQLITE_DISABLE_DIRSYNC
27608   if( dirSync ){
27609     int fd;
27610     rc = openDirectory(zPath, &fd);
27611     if( rc==SQLITE_OK ){
27612 #if OS_VXWORKS
27613       if( fsync(fd)==-1 )
27614 #else
27615       if( fsync(fd) )
27616 #endif
27617       {
27618         rc = SQLITE_IOERR_DIR_FSYNC;
27619       }
27620       if( close(fd)&&!rc ){
27621         rc = SQLITE_IOERR_DIR_CLOSE;
27622       }
27623     }
27624   }
27625 #endif
27626   return rc;
27627 }
27628
27629 /*
27630 ** Test the existance of or access permissions of file zPath. The
27631 ** test performed depends on the value of flags:
27632 **
27633 **     SQLITE_ACCESS_EXISTS: Return 1 if the file exists
27634 **     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
27635 **     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
27636 **
27637 ** Otherwise return 0.
27638 */
27639 static int unixAccess(
27640   sqlite3_vfs *NotUsed,   /* The VFS containing this xAccess method */
27641   const char *zPath,      /* Path of the file to examine */
27642   int flags,              /* What do we want to learn about the zPath file? */
27643   int *pResOut            /* Write result boolean here */
27644 ){
27645   int amode = 0;
27646   UNUSED_PARAMETER(NotUsed);
27647   SimulateIOError( return SQLITE_IOERR_ACCESS; );
27648   switch( flags ){
27649     case SQLITE_ACCESS_EXISTS:
27650       amode = F_OK;
27651       break;
27652     case SQLITE_ACCESS_READWRITE:
27653       amode = W_OK|R_OK;
27654       break;
27655     case SQLITE_ACCESS_READ:
27656       amode = R_OK;
27657       break;
27658
27659     default:
27660       assert(!"Invalid flags argument");
27661   }
27662   *pResOut = (access(zPath, amode)==0);
27663   if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
27664     struct stat buf;
27665     if( 0==stat(zPath, &buf) && buf.st_size==0 ){
27666       *pResOut = 0;
27667     }
27668   }
27669   return SQLITE_OK;
27670 }
27671
27672
27673 /*
27674 ** Turn a relative pathname into a full pathname. The relative path
27675 ** is stored as a nul-terminated string in the buffer pointed to by
27676 ** zPath. 
27677 **
27678 ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes 
27679 ** (in this case, MAX_PATHNAME bytes). The full-path is written to
27680 ** this buffer before returning.
27681 */
27682 static int unixFullPathname(
27683   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
27684   const char *zPath,            /* Possibly relative input path */
27685   int nOut,                     /* Size of output buffer in bytes */
27686   char *zOut                    /* Output buffer */
27687 ){
27688
27689   /* It's odd to simulate an io-error here, but really this is just
27690   ** using the io-error infrastructure to test that SQLite handles this
27691   ** function failing. This function could fail if, for example, the
27692   ** current working directory has been unlinked.
27693   */
27694   SimulateIOError( return SQLITE_ERROR );
27695
27696   assert( pVfs->mxPathname==MAX_PATHNAME );
27697   UNUSED_PARAMETER(pVfs);
27698
27699   zOut[nOut-1] = '\0';
27700   if( zPath[0]=='/' ){
27701     sqlite3_snprintf(nOut, zOut, "%s", zPath);
27702   }else{
27703     int nCwd;
27704     if( getcwd(zOut, nOut-1)==0 ){
27705       return SQLITE_CANTOPEN_BKPT;
27706     }
27707     nCwd = (int)strlen(zOut);
27708     sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
27709   }
27710   return SQLITE_OK;
27711 }
27712
27713
27714 #ifndef SQLITE_OMIT_LOAD_EXTENSION
27715 /*
27716 ** Interfaces for opening a shared library, finding entry points
27717 ** within the shared library, and closing the shared library.
27718 */
27719 #include <dlfcn.h>
27720 static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
27721   UNUSED_PARAMETER(NotUsed);
27722   return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
27723 }
27724
27725 /*
27726 ** SQLite calls this function immediately after a call to unixDlSym() or
27727 ** unixDlOpen() fails (returns a null pointer). If a more detailed error
27728 ** message is available, it is written to zBufOut. If no error message
27729 ** is available, zBufOut is left unmodified and SQLite uses a default
27730 ** error message.
27731 */
27732 static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
27733   char *zErr;
27734   UNUSED_PARAMETER(NotUsed);
27735   unixEnterMutex();
27736   zErr = dlerror();
27737   if( zErr ){
27738     sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
27739   }
27740   unixLeaveMutex();
27741 }
27742 static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
27743   /* 
27744   ** GCC with -pedantic-errors says that C90 does not allow a void* to be
27745   ** cast into a pointer to a function.  And yet the library dlsym() routine
27746   ** returns a void* which is really a pointer to a function.  So how do we
27747   ** use dlsym() with -pedantic-errors?
27748   **
27749   ** Variable x below is defined to be a pointer to a function taking
27750   ** parameters void* and const char* and returning a pointer to a function.
27751   ** We initialize x by assigning it a pointer to the dlsym() function.
27752   ** (That assignment requires a cast.)  Then we call the function that
27753   ** x points to.  
27754   **
27755   ** This work-around is unlikely to work correctly on any system where
27756   ** you really cannot cast a function pointer into void*.  But then, on the
27757   ** other hand, dlsym() will not work on such a system either, so we have
27758   ** not really lost anything.
27759   */
27760   void (*(*x)(void*,const char*))(void);
27761   UNUSED_PARAMETER(NotUsed);
27762   x = (void(*(*)(void*,const char*))(void))dlsym;
27763   return (*x)(p, zSym);
27764 }
27765 static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
27766   UNUSED_PARAMETER(NotUsed);
27767   dlclose(pHandle);
27768 }
27769 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
27770   #define unixDlOpen  0
27771   #define unixDlError 0
27772   #define unixDlSym   0
27773   #define unixDlClose 0
27774 #endif
27775
27776 /*
27777 ** Write nBuf bytes of random data to the supplied buffer zBuf.
27778 */
27779 static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
27780   UNUSED_PARAMETER(NotUsed);
27781   assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
27782
27783   /* We have to initialize zBuf to prevent valgrind from reporting
27784   ** errors.  The reports issued by valgrind are incorrect - we would
27785   ** prefer that the randomness be increased by making use of the
27786   ** uninitialized space in zBuf - but valgrind errors tend to worry
27787   ** some users.  Rather than argue, it seems easier just to initialize
27788   ** the whole array and silence valgrind, even if that means less randomness
27789   ** in the random seed.
27790   **
27791   ** When testing, initializing zBuf[] to zero is all we do.  That means
27792   ** that we always use the same random number sequence.  This makes the
27793   ** tests repeatable.
27794   */
27795   memset(zBuf, 0, nBuf);
27796 #if !defined(SQLITE_TEST)
27797   {
27798     int pid, fd;
27799     fd = open("/dev/urandom", O_RDONLY);
27800     if( fd<0 ){
27801       time_t t;
27802       time(&t);
27803       memcpy(zBuf, &t, sizeof(t));
27804       pid = getpid();
27805       memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
27806       assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
27807       nBuf = sizeof(t) + sizeof(pid);
27808     }else{
27809       nBuf = read(fd, zBuf, nBuf);
27810       close(fd);
27811     }
27812   }
27813 #endif
27814   return nBuf;
27815 }
27816
27817
27818 /*
27819 ** Sleep for a little while.  Return the amount of time slept.
27820 ** The argument is the number of microseconds we want to sleep.
27821 ** The return value is the number of microseconds of sleep actually
27822 ** requested from the underlying operating system, a number which
27823 ** might be greater than or equal to the argument, but not less
27824 ** than the argument.
27825 */
27826 static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
27827 #if OS_VXWORKS
27828   struct timespec sp;
27829
27830   sp.tv_sec = microseconds / 1000000;
27831   sp.tv_nsec = (microseconds % 1000000) * 1000;
27832   nanosleep(&sp, NULL);
27833   UNUSED_PARAMETER(NotUsed);
27834   return microseconds;
27835 #elif defined(HAVE_USLEEP) && HAVE_USLEEP
27836   usleep(microseconds);
27837   UNUSED_PARAMETER(NotUsed);
27838   return microseconds;
27839 #else
27840   int seconds = (microseconds+999999)/1000000;
27841   sleep(seconds);
27842   UNUSED_PARAMETER(NotUsed);
27843   return seconds*1000000;
27844 #endif
27845 }
27846
27847 /*
27848 ** The following variable, if set to a non-zero value, is interpreted as
27849 ** the number of seconds since 1970 and is used to set the result of
27850 ** sqlite3OsCurrentTime() during testing.
27851 */
27852 #ifdef SQLITE_TEST
27853 SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
27854 #endif
27855
27856 /*
27857 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
27858 ** the current time and date as a Julian Day number times 86_400_000.  In
27859 ** other words, write into *piNow the number of milliseconds since the Julian
27860 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
27861 ** proleptic Gregorian calendar.
27862 **
27863 ** On success, return 0.  Return 1 if the time and date cannot be found.
27864 */
27865 static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
27866   static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
27867 #if defined(NO_GETTOD)
27868   time_t t;
27869   time(&t);
27870   *piNow = ((sqlite3_int64)i)*1000 + unixEpoch;
27871 #elif OS_VXWORKS
27872   struct timespec sNow;
27873   clock_gettime(CLOCK_REALTIME, &sNow);
27874   *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
27875 #else
27876   struct timeval sNow;
27877   gettimeofday(&sNow, 0);
27878   *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
27879 #endif
27880
27881 #ifdef SQLITE_TEST
27882   if( sqlite3_current_time ){
27883     *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
27884   }
27885 #endif
27886   UNUSED_PARAMETER(NotUsed);
27887   return 0;
27888 }
27889
27890 /*
27891 ** Find the current time (in Universal Coordinated Time).  Write the
27892 ** current time and date as a Julian Day number into *prNow and
27893 ** return 0.  Return 1 if the time and date cannot be found.
27894 */
27895 static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
27896   sqlite3_int64 i;
27897   UNUSED_PARAMETER(NotUsed);
27898   unixCurrentTimeInt64(0, &i);
27899   *prNow = i/86400000.0;
27900   return 0;
27901 }
27902
27903 /*
27904 ** We added the xGetLastError() method with the intention of providing
27905 ** better low-level error messages when operating-system problems come up
27906 ** during SQLite operation.  But so far, none of that has been implemented
27907 ** in the core.  So this routine is never called.  For now, it is merely
27908 ** a place-holder.
27909 */
27910 static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
27911   UNUSED_PARAMETER(NotUsed);
27912   UNUSED_PARAMETER(NotUsed2);
27913   UNUSED_PARAMETER(NotUsed3);
27914   return 0;
27915 }
27916
27917
27918 /*
27919 ************************ End of sqlite3_vfs methods ***************************
27920 ******************************************************************************/
27921
27922 /******************************************************************************
27923 ************************** Begin Proxy Locking ********************************
27924 **
27925 ** Proxy locking is a "uber-locking-method" in this sense:  It uses the
27926 ** other locking methods on secondary lock files.  Proxy locking is a
27927 ** meta-layer over top of the primitive locking implemented above.  For
27928 ** this reason, the division that implements of proxy locking is deferred
27929 ** until late in the file (here) after all of the other I/O methods have
27930 ** been defined - so that the primitive locking methods are available
27931 ** as services to help with the implementation of proxy locking.
27932 **
27933 ****
27934 **
27935 ** The default locking schemes in SQLite use byte-range locks on the
27936 ** database file to coordinate safe, concurrent access by multiple readers
27937 ** and writers [http://sqlite.org/lockingv3.html].  The five file locking
27938 ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
27939 ** as POSIX read & write locks over fixed set of locations (via fsctl),
27940 ** on AFP and SMB only exclusive byte-range locks are available via fsctl
27941 ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
27942 ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
27943 ** address in the shared range is taken for a SHARED lock, the entire
27944 ** shared range is taken for an EXCLUSIVE lock):
27945 **
27946 **      PENDING_BYTE        0x40000000                  
27947 **      RESERVED_BYTE       0x40000001
27948 **      SHARED_RANGE        0x40000002 -> 0x40000200
27949 **
27950 ** This works well on the local file system, but shows a nearly 100x
27951 ** slowdown in read performance on AFP because the AFP client disables
27952 ** the read cache when byte-range locks are present.  Enabling the read
27953 ** cache exposes a cache coherency problem that is present on all OS X
27954 ** supported network file systems.  NFS and AFP both observe the
27955 ** close-to-open semantics for ensuring cache coherency
27956 ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
27957 ** address the requirements for concurrent database access by multiple
27958 ** readers and writers
27959 ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
27960 **
27961 ** To address the performance and cache coherency issues, proxy file locking
27962 ** changes the way database access is controlled by limiting access to a
27963 ** single host at a time and moving file locks off of the database file
27964 ** and onto a proxy file on the local file system.  
27965 **
27966 **
27967 ** Using proxy locks
27968 ** -----------------
27969 **
27970 ** C APIs
27971 **
27972 **  sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
27973 **                       <proxy_path> | ":auto:");
27974 **  sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
27975 **
27976 **
27977 ** SQL pragmas
27978 **
27979 **  PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
27980 **  PRAGMA [database.]lock_proxy_file
27981 **
27982 ** Specifying ":auto:" means that if there is a conch file with a matching
27983 ** host ID in it, the proxy path in the conch file will be used, otherwise
27984 ** a proxy path based on the user's temp dir
27985 ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
27986 ** actual proxy file name is generated from the name and path of the
27987 ** database file.  For example:
27988 **
27989 **       For database path "/Users/me/foo.db" 
27990 **       The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
27991 **
27992 ** Once a lock proxy is configured for a database connection, it can not
27993 ** be removed, however it may be switched to a different proxy path via
27994 ** the above APIs (assuming the conch file is not being held by another
27995 ** connection or process). 
27996 **
27997 **
27998 ** How proxy locking works
27999 ** -----------------------
28000 **
28001 ** Proxy file locking relies primarily on two new supporting files: 
28002 **
28003 **   *  conch file to limit access to the database file to a single host
28004 **      at a time
28005 **
28006 **   *  proxy file to act as a proxy for the advisory locks normally
28007 **      taken on the database
28008 **
28009 ** The conch file - to use a proxy file, sqlite must first "hold the conch"
28010 ** by taking an sqlite-style shared lock on the conch file, reading the
28011 ** contents and comparing the host's unique host ID (see below) and lock
28012 ** proxy path against the values stored in the conch.  The conch file is
28013 ** stored in the same directory as the database file and the file name
28014 ** is patterned after the database file name as ".<databasename>-conch".
28015 ** If the conch file does not exist, or it's contents do not match the
28016 ** host ID and/or proxy path, then the lock is escalated to an exclusive
28017 ** lock and the conch file contents is updated with the host ID and proxy
28018 ** path and the lock is downgraded to a shared lock again.  If the conch
28019 ** is held by another process (with a shared lock), the exclusive lock
28020 ** will fail and SQLITE_BUSY is returned.
28021 **
28022 ** The proxy file - a single-byte file used for all advisory file locks
28023 ** normally taken on the database file.   This allows for safe sharing
28024 ** of the database file for multiple readers and writers on the same
28025 ** host (the conch ensures that they all use the same local lock file).
28026 **
28027 ** Requesting the lock proxy does not immediately take the conch, it is
28028 ** only taken when the first request to lock database file is made.  
28029 ** This matches the semantics of the traditional locking behavior, where
28030 ** opening a connection to a database file does not take a lock on it.
28031 ** The shared lock and an open file descriptor are maintained until 
28032 ** the connection to the database is closed. 
28033 **
28034 ** The proxy file and the lock file are never deleted so they only need
28035 ** to be created the first time they are used.
28036 **
28037 ** Configuration options
28038 ** ---------------------
28039 **
28040 **  SQLITE_PREFER_PROXY_LOCKING
28041 **
28042 **       Database files accessed on non-local file systems are
28043 **       automatically configured for proxy locking, lock files are
28044 **       named automatically using the same logic as
28045 **       PRAGMA lock_proxy_file=":auto:"
28046 **    
28047 **  SQLITE_PROXY_DEBUG
28048 **
28049 **       Enables the logging of error messages during host id file
28050 **       retrieval and creation
28051 **
28052 **  LOCKPROXYDIR
28053 **
28054 **       Overrides the default directory used for lock proxy files that
28055 **       are named automatically via the ":auto:" setting
28056 **
28057 **  SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
28058 **
28059 **       Permissions to use when creating a directory for storing the
28060 **       lock proxy files, only used when LOCKPROXYDIR is not set.
28061 **    
28062 **    
28063 ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
28064 ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
28065 ** force proxy locking to be used for every database file opened, and 0
28066 ** will force automatic proxy locking to be disabled for all database
28067 ** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
28068 ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
28069 */
28070
28071 /*
28072 ** Proxy locking is only available on MacOSX 
28073 */
28074 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28075
28076 /*
28077 ** The proxyLockingContext has the path and file structures for the remote 
28078 ** and local proxy files in it
28079 */
28080 typedef struct proxyLockingContext proxyLockingContext;
28081 struct proxyLockingContext {
28082   unixFile *conchFile;         /* Open conch file */
28083   char *conchFilePath;         /* Name of the conch file */
28084   unixFile *lockProxy;         /* Open proxy lock file */
28085   char *lockProxyPath;         /* Name of the proxy lock file */
28086   char *dbPath;                /* Name of the open file */
28087   int conchHeld;               /* 1 if the conch is held, -1 if lockless */
28088   void *oldLockingContext;     /* Original lockingcontext to restore on close */
28089   sqlite3_io_methods const *pOldMethod;     /* Original I/O methods for close */
28090 };
28091
28092 /* 
28093 ** The proxy lock file path for the database at dbPath is written into lPath, 
28094 ** which must point to valid, writable memory large enough for a maxLen length
28095 ** file path. 
28096 */
28097 static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
28098   int len;
28099   int dbLen;
28100   int i;
28101
28102 #ifdef LOCKPROXYDIR
28103   len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
28104 #else
28105 # ifdef _CS_DARWIN_USER_TEMP_DIR
28106   {
28107     if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
28108       OSTRACE(("GETLOCKPATH  failed %s errno=%d pid=%d\n",
28109                lPath, errno, getpid()));
28110       return SQLITE_IOERR_LOCK;
28111     }
28112     len = strlcat(lPath, "sqliteplocks", maxLen);    
28113   }
28114 # else
28115   len = strlcpy(lPath, "/tmp/", maxLen);
28116 # endif
28117 #endif
28118
28119   if( lPath[len-1]!='/' ){
28120     len = strlcat(lPath, "/", maxLen);
28121   }
28122   
28123   /* transform the db path to a unique cache name */
28124   dbLen = (int)strlen(dbPath);
28125   for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
28126     char c = dbPath[i];
28127     lPath[i+len] = (c=='/')?'_':c;
28128   }
28129   lPath[i+len]='\0';
28130   strlcat(lPath, ":auto:", maxLen);
28131   OSTRACE(("GETLOCKPATH  proxy lock path=%s pid=%d\n", lPath, getpid()));
28132   return SQLITE_OK;
28133 }
28134
28135 /* 
28136  ** Creates the lock file and any missing directories in lockPath
28137  */
28138 static int proxyCreateLockPath(const char *lockPath){
28139   int i, len;
28140   char buf[MAXPATHLEN];
28141   int start = 0;
28142   
28143   assert(lockPath!=NULL);
28144   /* try to create all the intermediate directories */
28145   len = (int)strlen(lockPath);
28146   buf[0] = lockPath[0];
28147   for( i=1; i<len; i++ ){
28148     if( lockPath[i] == '/' && (i - start > 0) ){
28149       /* only mkdir if leaf dir != "." or "/" or ".." */
28150       if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/') 
28151          || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
28152         buf[i]='\0';
28153         if( mkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
28154           int err=errno;
28155           if( err!=EEXIST ) {
28156             OSTRACE(("CREATELOCKPATH  FAILED creating %s, "
28157                      "'%s' proxy lock path=%s pid=%d\n",
28158                      buf, strerror(err), lockPath, getpid()));
28159             return err;
28160           }
28161         }
28162       }
28163       start=i+1;
28164     }
28165     buf[i] = lockPath[i];
28166   }
28167   OSTRACE(("CREATELOCKPATH  proxy lock path=%s pid=%d\n", lockPath, getpid()));
28168   return 0;
28169 }
28170
28171 /*
28172 ** Create a new VFS file descriptor (stored in memory obtained from
28173 ** sqlite3_malloc) and open the file named "path" in the file descriptor.
28174 **
28175 ** The caller is responsible not only for closing the file descriptor
28176 ** but also for freeing the memory associated with the file descriptor.
28177 */
28178 static int proxyCreateUnixFile(
28179     const char *path,        /* path for the new unixFile */
28180     unixFile **ppFile,       /* unixFile created and returned by ref */
28181     int islockfile           /* if non zero missing dirs will be created */
28182 ) {
28183   int fd = -1;
28184   int dirfd = -1;
28185   unixFile *pNew;
28186   int rc = SQLITE_OK;
28187   int openFlags = O_RDWR | O_CREAT;
28188   sqlite3_vfs dummyVfs;
28189   int terrno = 0;
28190   UnixUnusedFd *pUnused = NULL;
28191
28192   /* 1. first try to open/create the file
28193   ** 2. if that fails, and this is a lock file (not-conch), try creating
28194   ** the parent directories and then try again.
28195   ** 3. if that fails, try to open the file read-only
28196   ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
28197   */
28198   pUnused = findReusableFd(path, openFlags);
28199   if( pUnused ){
28200     fd = pUnused->fd;
28201   }else{
28202     pUnused = sqlite3_malloc(sizeof(*pUnused));
28203     if( !pUnused ){
28204       return SQLITE_NOMEM;
28205     }
28206   }
28207   if( fd<0 ){
28208     fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
28209     terrno = errno;
28210     if( fd<0 && errno==ENOENT && islockfile ){
28211       if( proxyCreateLockPath(path) == SQLITE_OK ){
28212         fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
28213       }
28214     }
28215   }
28216   if( fd<0 ){
28217     openFlags = O_RDONLY;
28218     fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
28219     terrno = errno;
28220   }
28221   if( fd<0 ){
28222     if( islockfile ){
28223       return SQLITE_BUSY;
28224     }
28225     switch (terrno) {
28226       case EACCES:
28227         return SQLITE_PERM;
28228       case EIO: 
28229         return SQLITE_IOERR_LOCK; /* even though it is the conch */
28230       default:
28231         return SQLITE_CANTOPEN_BKPT;
28232     }
28233   }
28234   
28235   pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
28236   if( pNew==NULL ){
28237     rc = SQLITE_NOMEM;
28238     goto end_create_proxy;
28239   }
28240   memset(pNew, 0, sizeof(unixFile));
28241   pNew->openFlags = openFlags;
28242   dummyVfs.pAppData = (void*)&autolockIoFinder;
28243   pUnused->fd = fd;
28244   pUnused->flags = openFlags;
28245   pNew->pUnused = pUnused;
28246   
28247   rc = fillInUnixFile(&dummyVfs, fd, dirfd, (sqlite3_file*)pNew, path, 0, 0);
28248   if( rc==SQLITE_OK ){
28249     *ppFile = pNew;
28250     return SQLITE_OK;
28251   }
28252 end_create_proxy:    
28253   close(fd); /* silently leak fd if error, we're already in error */
28254   sqlite3_free(pNew);
28255   sqlite3_free(pUnused);
28256   return rc;
28257 }
28258
28259 #ifdef SQLITE_TEST
28260 /* simulate multiple hosts by creating unique hostid file paths */
28261 SQLITE_API int sqlite3_hostid_num = 0;
28262 #endif
28263
28264 #define PROXY_HOSTIDLEN    16  /* conch file host id length */
28265
28266 /* Not always defined in the headers as it ought to be */
28267 extern int gethostuuid(uuid_t id, const struct timespec *wait);
28268
28269 /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN 
28270 ** bytes of writable memory.
28271 */
28272 static int proxyGetHostID(unsigned char *pHostID, int *pError){
28273   struct timespec timeout = {1, 0}; /* 1 sec timeout */
28274   
28275   assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
28276   memset(pHostID, 0, PROXY_HOSTIDLEN);
28277 #if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
28278                && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
28279   if( gethostuuid(pHostID, &timeout) ){
28280     int err = errno;
28281     if( pError ){
28282       *pError = err;
28283     }
28284     return SQLITE_IOERR;
28285   }
28286 #endif
28287 #ifdef SQLITE_TEST
28288   /* simulate multiple hosts by creating unique hostid file paths */
28289   if( sqlite3_hostid_num != 0){
28290     pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
28291   }
28292 #endif
28293   
28294   return SQLITE_OK;
28295 }
28296
28297 /* The conch file contains the header, host id and lock file path
28298  */
28299 #define PROXY_CONCHVERSION 2   /* 1-byte header, 16-byte host id, path */
28300 #define PROXY_HEADERLEN    1   /* conch file header length */
28301 #define PROXY_PATHINDEX    (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
28302 #define PROXY_MAXCONCHLEN  (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
28303
28304 /* 
28305 ** Takes an open conch file, copies the contents to a new path and then moves 
28306 ** it back.  The newly created file's file descriptor is assigned to the
28307 ** conch file structure and finally the original conch file descriptor is 
28308 ** closed.  Returns zero if successful.
28309 */
28310 static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
28311   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
28312   unixFile *conchFile = pCtx->conchFile;
28313   char tPath[MAXPATHLEN];
28314   char buf[PROXY_MAXCONCHLEN];
28315   char *cPath = pCtx->conchFilePath;
28316   size_t readLen = 0;
28317   size_t pathLen = 0;
28318   char errmsg[64] = "";
28319   int fd = -1;
28320   int rc = -1;
28321   UNUSED_PARAMETER(myHostID);
28322
28323   /* create a new path by replace the trailing '-conch' with '-break' */
28324   pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
28325   if( pathLen>MAXPATHLEN || pathLen<6 || 
28326      (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
28327     sprintf(errmsg, "path error (len %d)", (int)pathLen);
28328     goto end_breaklock;
28329   }
28330   /* read the conch content */
28331   readLen = pread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
28332   if( readLen<PROXY_PATHINDEX ){
28333     sprintf(errmsg, "read error (len %d)", (int)readLen);
28334     goto end_breaklock;
28335   }
28336   /* write it out to the temporary break file */
28337   fd = open(tPath, (O_RDWR|O_CREAT|O_EXCL), SQLITE_DEFAULT_FILE_PERMISSIONS);
28338   if( fd<0 ){
28339     sprintf(errmsg, "create failed (%d)", errno);
28340     goto end_breaklock;
28341   }
28342   if( pwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
28343     sprintf(errmsg, "write failed (%d)", errno);
28344     goto end_breaklock;
28345   }
28346   if( rename(tPath, cPath) ){
28347     sprintf(errmsg, "rename failed (%d)", errno);
28348     goto end_breaklock;
28349   }
28350   rc = 0;
28351   fprintf(stderr, "broke stale lock on %s\n", cPath);
28352   close(conchFile->h);
28353   conchFile->h = fd;
28354   conchFile->openFlags = O_RDWR | O_CREAT;
28355
28356 end_breaklock:
28357   if( rc ){
28358     if( fd>=0 ){
28359       unlink(tPath);
28360       close(fd);
28361     }
28362     fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
28363   }
28364   return rc;
28365 }
28366
28367 /* Take the requested lock on the conch file and break a stale lock if the 
28368 ** host id matches.
28369 */
28370 static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
28371   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
28372   unixFile *conchFile = pCtx->conchFile;
28373   int rc = SQLITE_OK;
28374   int nTries = 0;
28375   struct timespec conchModTime;
28376   
28377   do {
28378     rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
28379     nTries ++;
28380     if( rc==SQLITE_BUSY ){
28381       /* If the lock failed (busy):
28382        * 1st try: get the mod time of the conch, wait 0.5s and try again. 
28383        * 2nd try: fail if the mod time changed or host id is different, wait 
28384        *           10 sec and try again
28385        * 3rd try: break the lock unless the mod time has changed.
28386        */
28387       struct stat buf;
28388       if( fstat(conchFile->h, &buf) ){
28389         pFile->lastErrno = errno;
28390         return SQLITE_IOERR_LOCK;
28391       }
28392       
28393       if( nTries==1 ){
28394         conchModTime = buf.st_mtimespec;
28395         usleep(500000); /* wait 0.5 sec and try the lock again*/
28396         continue;  
28397       }
28398
28399       assert( nTries>1 );
28400       if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec || 
28401          conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
28402         return SQLITE_BUSY;
28403       }
28404       
28405       if( nTries==2 ){  
28406         char tBuf[PROXY_MAXCONCHLEN];
28407         int len = pread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
28408         if( len<0 ){
28409           pFile->lastErrno = errno;
28410           return SQLITE_IOERR_LOCK;
28411         }
28412         if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
28413           /* don't break the lock if the host id doesn't match */
28414           if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
28415             return SQLITE_BUSY;
28416           }
28417         }else{
28418           /* don't break the lock on short read or a version mismatch */
28419           return SQLITE_BUSY;
28420         }
28421         usleep(10000000); /* wait 10 sec and try the lock again */
28422         continue; 
28423       }
28424       
28425       assert( nTries==3 );
28426       if( 0==proxyBreakConchLock(pFile, myHostID) ){
28427         rc = SQLITE_OK;
28428         if( lockType==EXCLUSIVE_LOCK ){
28429           rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);          
28430         }
28431         if( !rc ){
28432           rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
28433         }
28434       }
28435     }
28436   } while( rc==SQLITE_BUSY && nTries<3 );
28437   
28438   return rc;
28439 }
28440
28441 /* Takes the conch by taking a shared lock and read the contents conch, if 
28442 ** lockPath is non-NULL, the host ID and lock file path must match.  A NULL 
28443 ** lockPath means that the lockPath in the conch file will be used if the 
28444 ** host IDs match, or a new lock path will be generated automatically 
28445 ** and written to the conch file.
28446 */
28447 static int proxyTakeConch(unixFile *pFile){
28448   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
28449   
28450   if( pCtx->conchHeld!=0 ){
28451     return SQLITE_OK;
28452   }else{
28453     unixFile *conchFile = pCtx->conchFile;
28454     uuid_t myHostID;
28455     int pError = 0;
28456     char readBuf[PROXY_MAXCONCHLEN];
28457     char lockPath[MAXPATHLEN];
28458     char *tempLockPath = NULL;
28459     int rc = SQLITE_OK;
28460     int createConch = 0;
28461     int hostIdMatch = 0;
28462     int readLen = 0;
28463     int tryOldLockPath = 0;
28464     int forceNewLockPath = 0;
28465     
28466     OSTRACE(("TAKECONCH  %d for %s pid=%d\n", conchFile->h,
28467              (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
28468
28469     rc = proxyGetHostID(myHostID, &pError);
28470     if( (rc&0xff)==SQLITE_IOERR ){
28471       pFile->lastErrno = pError;
28472       goto end_takeconch;
28473     }
28474     rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
28475     if( rc!=SQLITE_OK ){
28476       goto end_takeconch;
28477     }
28478     /* read the existing conch file */
28479     readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
28480     if( readLen<0 ){
28481       /* I/O error: lastErrno set by seekAndRead */
28482       pFile->lastErrno = conchFile->lastErrno;
28483       rc = SQLITE_IOERR_READ;
28484       goto end_takeconch;
28485     }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) || 
28486              readBuf[0]!=(char)PROXY_CONCHVERSION ){
28487       /* a short read or version format mismatch means we need to create a new 
28488       ** conch file. 
28489       */
28490       createConch = 1;
28491     }
28492     /* if the host id matches and the lock path already exists in the conch
28493     ** we'll try to use the path there, if we can't open that path, we'll 
28494     ** retry with a new auto-generated path 
28495     */
28496     do { /* in case we need to try again for an :auto: named lock file */
28497
28498       if( !createConch && !forceNewLockPath ){
28499         hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID, 
28500                                   PROXY_HOSTIDLEN);
28501         /* if the conch has data compare the contents */
28502         if( !pCtx->lockProxyPath ){
28503           /* for auto-named local lock file, just check the host ID and we'll
28504            ** use the local lock file path that's already in there
28505            */
28506           if( hostIdMatch ){
28507             size_t pathLen = (readLen - PROXY_PATHINDEX);
28508             
28509             if( pathLen>=MAXPATHLEN ){
28510               pathLen=MAXPATHLEN-1;
28511             }
28512             memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
28513             lockPath[pathLen] = 0;
28514             tempLockPath = lockPath;
28515             tryOldLockPath = 1;
28516             /* create a copy of the lock path if the conch is taken */
28517             goto end_takeconch;
28518           }
28519         }else if( hostIdMatch
28520                && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
28521                            readLen-PROXY_PATHINDEX)
28522         ){
28523           /* conch host and lock path match */
28524           goto end_takeconch; 
28525         }
28526       }
28527       
28528       /* if the conch isn't writable and doesn't match, we can't take it */
28529       if( (conchFile->openFlags&O_RDWR) == 0 ){
28530         rc = SQLITE_BUSY;
28531         goto end_takeconch;
28532       }
28533       
28534       /* either the conch didn't match or we need to create a new one */
28535       if( !pCtx->lockProxyPath ){
28536         proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
28537         tempLockPath = lockPath;
28538         /* create a copy of the lock path _only_ if the conch is taken */
28539       }
28540       
28541       /* update conch with host and path (this will fail if other process
28542       ** has a shared lock already), if the host id matches, use the big
28543       ** stick.
28544       */
28545       futimes(conchFile->h, NULL);
28546       if( hostIdMatch && !createConch ){
28547         if( conchFile->pInode && conchFile->pInode->nShared>1 ){
28548           /* We are trying for an exclusive lock but another thread in this
28549            ** same process is still holding a shared lock. */
28550           rc = SQLITE_BUSY;
28551         } else {          
28552           rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
28553         }
28554       }else{
28555         rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
28556       }
28557       if( rc==SQLITE_OK ){
28558         char writeBuffer[PROXY_MAXCONCHLEN];
28559         int writeSize = 0;
28560         
28561         writeBuffer[0] = (char)PROXY_CONCHVERSION;
28562         memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
28563         if( pCtx->lockProxyPath!=NULL ){
28564           strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
28565         }else{
28566           strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
28567         }
28568         writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
28569         ftruncate(conchFile->h, writeSize);
28570         rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
28571         fsync(conchFile->h);
28572         /* If we created a new conch file (not just updated the contents of a 
28573          ** valid conch file), try to match the permissions of the database 
28574          */
28575         if( rc==SQLITE_OK && createConch ){
28576           struct stat buf;
28577           int err = fstat(pFile->h, &buf);
28578           if( err==0 ){
28579             mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
28580                                         S_IROTH|S_IWOTH);
28581             /* try to match the database file R/W permissions, ignore failure */
28582 #ifndef SQLITE_PROXY_DEBUG
28583             fchmod(conchFile->h, cmode);
28584 #else
28585             if( fchmod(conchFile->h, cmode)!=0 ){
28586               int code = errno;
28587               fprintf(stderr, "fchmod %o FAILED with %d %s\n",
28588                       cmode, code, strerror(code));
28589             } else {
28590               fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
28591             }
28592           }else{
28593             int code = errno;
28594             fprintf(stderr, "STAT FAILED[%d] with %d %s\n", 
28595                     err, code, strerror(code));
28596 #endif
28597           }
28598         }
28599       }
28600       conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
28601       
28602     end_takeconch:
28603       OSTRACE(("TRANSPROXY: CLOSE  %d\n", pFile->h));
28604       if( rc==SQLITE_OK && pFile->openFlags ){
28605         if( pFile->h>=0 ){
28606 #ifdef STRICT_CLOSE_ERROR
28607           if( close(pFile->h) ){
28608             pFile->lastErrno = errno;
28609             return SQLITE_IOERR_CLOSE;
28610           }
28611 #else
28612           close(pFile->h); /* silently leak fd if fail */
28613 #endif
28614         }
28615         pFile->h = -1;
28616         int fd = open(pCtx->dbPath, pFile->openFlags,
28617                       SQLITE_DEFAULT_FILE_PERMISSIONS);
28618         OSTRACE(("TRANSPROXY: OPEN  %d\n", fd));
28619         if( fd>=0 ){
28620           pFile->h = fd;
28621         }else{
28622           rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
28623            during locking */
28624         }
28625       }
28626       if( rc==SQLITE_OK && !pCtx->lockProxy ){
28627         char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
28628         rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
28629         if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
28630           /* we couldn't create the proxy lock file with the old lock file path
28631            ** so try again via auto-naming 
28632            */
28633           forceNewLockPath = 1;
28634           tryOldLockPath = 0;
28635           continue; /* go back to the do {} while start point, try again */
28636         }
28637       }
28638       if( rc==SQLITE_OK ){
28639         /* Need to make a copy of path if we extracted the value
28640          ** from the conch file or the path was allocated on the stack
28641          */
28642         if( tempLockPath ){
28643           pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
28644           if( !pCtx->lockProxyPath ){
28645             rc = SQLITE_NOMEM;
28646           }
28647         }
28648       }
28649       if( rc==SQLITE_OK ){
28650         pCtx->conchHeld = 1;
28651         
28652         if( pCtx->lockProxy->pMethod == &afpIoMethods ){
28653           afpLockingContext *afpCtx;
28654           afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
28655           afpCtx->dbPath = pCtx->lockProxyPath;
28656         }
28657       } else {
28658         conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
28659       }
28660       OSTRACE(("TAKECONCH  %d %s\n", conchFile->h,
28661                rc==SQLITE_OK?"ok":"failed"));
28662       return rc;
28663     } while (1); /* in case we need to retry the :auto: lock file - 
28664                  ** we should never get here except via the 'continue' call. */
28665   }
28666 }
28667
28668 /*
28669 ** If pFile holds a lock on a conch file, then release that lock.
28670 */
28671 static int proxyReleaseConch(unixFile *pFile){
28672   int rc = SQLITE_OK;         /* Subroutine return code */
28673   proxyLockingContext *pCtx;  /* The locking context for the proxy lock */
28674   unixFile *conchFile;        /* Name of the conch file */
28675
28676   pCtx = (proxyLockingContext *)pFile->lockingContext;
28677   conchFile = pCtx->conchFile;
28678   OSTRACE(("RELEASECONCH  %d for %s pid=%d\n", conchFile->h,
28679            (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), 
28680            getpid()));
28681   if( pCtx->conchHeld>0 ){
28682     rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
28683   }
28684   pCtx->conchHeld = 0;
28685   OSTRACE(("RELEASECONCH  %d %s\n", conchFile->h,
28686            (rc==SQLITE_OK ? "ok" : "failed")));
28687   return rc;
28688 }
28689
28690 /*
28691 ** Given the name of a database file, compute the name of its conch file.
28692 ** Store the conch filename in memory obtained from sqlite3_malloc().
28693 ** Make *pConchPath point to the new name.  Return SQLITE_OK on success
28694 ** or SQLITE_NOMEM if unable to obtain memory.
28695 **
28696 ** The caller is responsible for ensuring that the allocated memory
28697 ** space is eventually freed.
28698 **
28699 ** *pConchPath is set to NULL if a memory allocation error occurs.
28700 */
28701 static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
28702   int i;                        /* Loop counter */
28703   int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
28704   char *conchPath;              /* buffer in which to construct conch name */
28705
28706   /* Allocate space for the conch filename and initialize the name to
28707   ** the name of the original database file. */  
28708   *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
28709   if( conchPath==0 ){
28710     return SQLITE_NOMEM;
28711   }
28712   memcpy(conchPath, dbPath, len+1);
28713   
28714   /* now insert a "." before the last / character */
28715   for( i=(len-1); i>=0; i-- ){
28716     if( conchPath[i]=='/' ){
28717       i++;
28718       break;
28719     }
28720   }
28721   conchPath[i]='.';
28722   while ( i<len ){
28723     conchPath[i+1]=dbPath[i];
28724     i++;
28725   }
28726
28727   /* append the "-conch" suffix to the file */
28728   memcpy(&conchPath[i+1], "-conch", 7);
28729   assert( (int)strlen(conchPath) == len+7 );
28730
28731   return SQLITE_OK;
28732 }
28733
28734
28735 /* Takes a fully configured proxy locking-style unix file and switches
28736 ** the local lock file path 
28737 */
28738 static int switchLockProxyPath(unixFile *pFile, const char *path) {
28739   proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
28740   char *oldPath = pCtx->lockProxyPath;
28741   int rc = SQLITE_OK;
28742
28743   if( pFile->eFileLock!=NO_LOCK ){
28744     return SQLITE_BUSY;
28745   }  
28746
28747   /* nothing to do if the path is NULL, :auto: or matches the existing path */
28748   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
28749     (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
28750     return SQLITE_OK;
28751   }else{
28752     unixFile *lockProxy = pCtx->lockProxy;
28753     pCtx->lockProxy=NULL;
28754     pCtx->conchHeld = 0;
28755     if( lockProxy!=NULL ){
28756       rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
28757       if( rc ) return rc;
28758       sqlite3_free(lockProxy);
28759     }
28760     sqlite3_free(oldPath);
28761     pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
28762   }
28763   
28764   return rc;
28765 }
28766
28767 /*
28768 ** pFile is a file that has been opened by a prior xOpen call.  dbPath
28769 ** is a string buffer at least MAXPATHLEN+1 characters in size.
28770 **
28771 ** This routine find the filename associated with pFile and writes it
28772 ** int dbPath.
28773 */
28774 static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
28775 #if defined(__APPLE__)
28776   if( pFile->pMethod == &afpIoMethods ){
28777     /* afp style keeps a reference to the db path in the filePath field 
28778     ** of the struct */
28779     assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
28780     strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
28781   } else
28782 #endif
28783   if( pFile->pMethod == &dotlockIoMethods ){
28784     /* dot lock style uses the locking context to store the dot lock
28785     ** file path */
28786     int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
28787     memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
28788   }else{
28789     /* all other styles use the locking context to store the db file path */
28790     assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
28791     strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
28792   }
28793   return SQLITE_OK;
28794 }
28795
28796 /*
28797 ** Takes an already filled in unix file and alters it so all file locking 
28798 ** will be performed on the local proxy lock file.  The following fields
28799 ** are preserved in the locking context so that they can be restored and 
28800 ** the unix structure properly cleaned up at close time:
28801 **  ->lockingContext
28802 **  ->pMethod
28803 */
28804 static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
28805   proxyLockingContext *pCtx;
28806   char dbPath[MAXPATHLEN+1];       /* Name of the database file */
28807   char *lockPath=NULL;
28808   int rc = SQLITE_OK;
28809   
28810   if( pFile->eFileLock!=NO_LOCK ){
28811     return SQLITE_BUSY;
28812   }
28813   proxyGetDbPathForUnixFile(pFile, dbPath);
28814   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
28815     lockPath=NULL;
28816   }else{
28817     lockPath=(char *)path;
28818   }
28819   
28820   OSTRACE(("TRANSPROXY  %d for %s pid=%d\n", pFile->h,
28821            (lockPath ? lockPath : ":auto:"), getpid()));
28822
28823   pCtx = sqlite3_malloc( sizeof(*pCtx) );
28824   if( pCtx==0 ){
28825     return SQLITE_NOMEM;
28826   }
28827   memset(pCtx, 0, sizeof(*pCtx));
28828
28829   rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
28830   if( rc==SQLITE_OK ){
28831     rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
28832     if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
28833       /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
28834       ** (c) the file system is read-only, then enable no-locking access.
28835       ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
28836       ** that openFlags will have only one of O_RDONLY or O_RDWR.
28837       */
28838       struct statfs fsInfo;
28839       struct stat conchInfo;
28840       int goLockless = 0;
28841
28842       if( stat(pCtx->conchFilePath, &conchInfo) == -1 ) {
28843         int err = errno;
28844         if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
28845           goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
28846         }
28847       }
28848       if( goLockless ){
28849         pCtx->conchHeld = -1; /* read only FS/ lockless */
28850         rc = SQLITE_OK;
28851       }
28852     }
28853   }  
28854   if( rc==SQLITE_OK && lockPath ){
28855     pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
28856   }
28857
28858   if( rc==SQLITE_OK ){
28859     pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
28860     if( pCtx->dbPath==NULL ){
28861       rc = SQLITE_NOMEM;
28862     }
28863   }
28864   if( rc==SQLITE_OK ){
28865     /* all memory is allocated, proxys are created and assigned, 
28866     ** switch the locking context and pMethod then return.
28867     */
28868     pCtx->oldLockingContext = pFile->lockingContext;
28869     pFile->lockingContext = pCtx;
28870     pCtx->pOldMethod = pFile->pMethod;
28871     pFile->pMethod = &proxyIoMethods;
28872   }else{
28873     if( pCtx->conchFile ){ 
28874       pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
28875       sqlite3_free(pCtx->conchFile);
28876     }
28877     sqlite3DbFree(0, pCtx->lockProxyPath);
28878     sqlite3_free(pCtx->conchFilePath); 
28879     sqlite3_free(pCtx);
28880   }
28881   OSTRACE(("TRANSPROXY  %d %s\n", pFile->h,
28882            (rc==SQLITE_OK ? "ok" : "failed")));
28883   return rc;
28884 }
28885
28886
28887 /*
28888 ** This routine handles sqlite3_file_control() calls that are specific
28889 ** to proxy locking.
28890 */
28891 static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
28892   switch( op ){
28893     case SQLITE_GET_LOCKPROXYFILE: {
28894       unixFile *pFile = (unixFile*)id;
28895       if( pFile->pMethod == &proxyIoMethods ){
28896         proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
28897         proxyTakeConch(pFile);
28898         if( pCtx->lockProxyPath ){
28899           *(const char **)pArg = pCtx->lockProxyPath;
28900         }else{
28901           *(const char **)pArg = ":auto: (not held)";
28902         }
28903       } else {
28904         *(const char **)pArg = NULL;
28905       }
28906       return SQLITE_OK;
28907     }
28908     case SQLITE_SET_LOCKPROXYFILE: {
28909       unixFile *pFile = (unixFile*)id;
28910       int rc = SQLITE_OK;
28911       int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
28912       if( pArg==NULL || (const char *)pArg==0 ){
28913         if( isProxyStyle ){
28914           /* turn off proxy locking - not supported */
28915           rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
28916         }else{
28917           /* turn off proxy locking - already off - NOOP */
28918           rc = SQLITE_OK;
28919         }
28920       }else{
28921         const char *proxyPath = (const char *)pArg;
28922         if( isProxyStyle ){
28923           proxyLockingContext *pCtx = 
28924             (proxyLockingContext*)pFile->lockingContext;
28925           if( !strcmp(pArg, ":auto:") 
28926            || (pCtx->lockProxyPath &&
28927                !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
28928           ){
28929             rc = SQLITE_OK;
28930           }else{
28931             rc = switchLockProxyPath(pFile, proxyPath);
28932           }
28933         }else{
28934           /* turn on proxy file locking */
28935           rc = proxyTransformUnixFile(pFile, proxyPath);
28936         }
28937       }
28938       return rc;
28939     }
28940     default: {
28941       assert( 0 );  /* The call assures that only valid opcodes are sent */
28942     }
28943   }
28944   /*NOTREACHED*/
28945   return SQLITE_ERROR;
28946 }
28947
28948 /*
28949 ** Within this division (the proxying locking implementation) the procedures
28950 ** above this point are all utilities.  The lock-related methods of the
28951 ** proxy-locking sqlite3_io_method object follow.
28952 */
28953
28954
28955 /*
28956 ** This routine checks if there is a RESERVED lock held on the specified
28957 ** file by this or any other process. If such a lock is held, set *pResOut
28958 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
28959 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
28960 */
28961 static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
28962   unixFile *pFile = (unixFile*)id;
28963   int rc = proxyTakeConch(pFile);
28964   if( rc==SQLITE_OK ){
28965     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
28966     if( pCtx->conchHeld>0 ){
28967       unixFile *proxy = pCtx->lockProxy;
28968       return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
28969     }else{ /* conchHeld < 0 is lockless */
28970       pResOut=0;
28971     }
28972   }
28973   return rc;
28974 }
28975
28976 /*
28977 ** Lock the file with the lock specified by parameter eFileLock - one
28978 ** of the following:
28979 **
28980 **     (1) SHARED_LOCK
28981 **     (2) RESERVED_LOCK
28982 **     (3) PENDING_LOCK
28983 **     (4) EXCLUSIVE_LOCK
28984 **
28985 ** Sometimes when requesting one lock state, additional lock states
28986 ** are inserted in between.  The locking might fail on one of the later
28987 ** transitions leaving the lock state different from what it started but
28988 ** still short of its goal.  The following chart shows the allowed
28989 ** transitions and the inserted intermediate states:
28990 **
28991 **    UNLOCKED -> SHARED
28992 **    SHARED -> RESERVED
28993 **    SHARED -> (PENDING) -> EXCLUSIVE
28994 **    RESERVED -> (PENDING) -> EXCLUSIVE
28995 **    PENDING -> EXCLUSIVE
28996 **
28997 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
28998 ** routine to lower a locking level.
28999 */
29000 static int proxyLock(sqlite3_file *id, int eFileLock) {
29001   unixFile *pFile = (unixFile*)id;
29002   int rc = proxyTakeConch(pFile);
29003   if( rc==SQLITE_OK ){
29004     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
29005     if( pCtx->conchHeld>0 ){
29006       unixFile *proxy = pCtx->lockProxy;
29007       rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
29008       pFile->eFileLock = proxy->eFileLock;
29009     }else{
29010       /* conchHeld < 0 is lockless */
29011     }
29012   }
29013   return rc;
29014 }
29015
29016
29017 /*
29018 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
29019 ** must be either NO_LOCK or SHARED_LOCK.
29020 **
29021 ** If the locking level of the file descriptor is already at or below
29022 ** the requested locking level, this routine is a no-op.
29023 */
29024 static int proxyUnlock(sqlite3_file *id, int eFileLock) {
29025   unixFile *pFile = (unixFile*)id;
29026   int rc = proxyTakeConch(pFile);
29027   if( rc==SQLITE_OK ){
29028     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
29029     if( pCtx->conchHeld>0 ){
29030       unixFile *proxy = pCtx->lockProxy;
29031       rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
29032       pFile->eFileLock = proxy->eFileLock;
29033     }else{
29034       /* conchHeld < 0 is lockless */
29035     }
29036   }
29037   return rc;
29038 }
29039
29040 /*
29041 ** Close a file that uses proxy locks.
29042 */
29043 static int proxyClose(sqlite3_file *id) {
29044   if( id ){
29045     unixFile *pFile = (unixFile*)id;
29046     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
29047     unixFile *lockProxy = pCtx->lockProxy;
29048     unixFile *conchFile = pCtx->conchFile;
29049     int rc = SQLITE_OK;
29050     
29051     if( lockProxy ){
29052       rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
29053       if( rc ) return rc;
29054       rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
29055       if( rc ) return rc;
29056       sqlite3_free(lockProxy);
29057       pCtx->lockProxy = 0;
29058     }
29059     if( conchFile ){
29060       if( pCtx->conchHeld ){
29061         rc = proxyReleaseConch(pFile);
29062         if( rc ) return rc;
29063       }
29064       rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
29065       if( rc ) return rc;
29066       sqlite3_free(conchFile);
29067     }
29068     sqlite3DbFree(0, pCtx->lockProxyPath);
29069     sqlite3_free(pCtx->conchFilePath);
29070     sqlite3DbFree(0, pCtx->dbPath);
29071     /* restore the original locking context and pMethod then close it */
29072     pFile->lockingContext = pCtx->oldLockingContext;
29073     pFile->pMethod = pCtx->pOldMethod;
29074     sqlite3_free(pCtx);
29075     return pFile->pMethod->xClose(id);
29076   }
29077   return SQLITE_OK;
29078 }
29079
29080
29081
29082 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
29083 /*
29084 ** The proxy locking style is intended for use with AFP filesystems.
29085 ** And since AFP is only supported on MacOSX, the proxy locking is also
29086 ** restricted to MacOSX.
29087 ** 
29088 **
29089 ******************* End of the proxy lock implementation **********************
29090 ******************************************************************************/
29091
29092 /*
29093 ** Initialize the operating system interface.
29094 **
29095 ** This routine registers all VFS implementations for unix-like operating
29096 ** systems.  This routine, and the sqlite3_os_end() routine that follows,
29097 ** should be the only routines in this file that are visible from other
29098 ** files.
29099 **
29100 ** This routine is called once during SQLite initialization and by a
29101 ** single thread.  The memory allocation and mutex subsystems have not
29102 ** necessarily been initialized when this routine is called, and so they
29103 ** should not be used.
29104 */
29105 SQLITE_API int sqlite3_os_init(void){ 
29106   /* 
29107   ** The following macro defines an initializer for an sqlite3_vfs object.
29108   ** The name of the VFS is NAME.  The pAppData is a pointer to a pointer
29109   ** to the "finder" function.  (pAppData is a pointer to a pointer because
29110   ** silly C90 rules prohibit a void* from being cast to a function pointer
29111   ** and so we have to go through the intermediate pointer to avoid problems
29112   ** when compiling with -pedantic-errors on GCC.)
29113   **
29114   ** The FINDER parameter to this macro is the name of the pointer to the
29115   ** finder-function.  The finder-function returns a pointer to the
29116   ** sqlite_io_methods object that implements the desired locking
29117   ** behaviors.  See the division above that contains the IOMETHODS
29118   ** macro for addition information on finder-functions.
29119   **
29120   ** Most finders simply return a pointer to a fixed sqlite3_io_methods
29121   ** object.  But the "autolockIoFinder" available on MacOSX does a little
29122   ** more than that; it looks at the filesystem type that hosts the 
29123   ** database file and tries to choose an locking method appropriate for
29124   ** that filesystem time.
29125   */
29126   #define UNIXVFS(VFSNAME, FINDER) {                        \
29127     2,                    /* iVersion */                    \
29128     sizeof(unixFile),     /* szOsFile */                    \
29129     MAX_PATHNAME,         /* mxPathname */                  \
29130     0,                    /* pNext */                       \
29131     VFSNAME,              /* zName */                       \
29132     (void*)&FINDER,       /* pAppData */                    \
29133     unixOpen,             /* xOpen */                       \
29134     unixDelete,           /* xDelete */                     \
29135     unixAccess,           /* xAccess */                     \
29136     unixFullPathname,     /* xFullPathname */               \
29137     unixDlOpen,           /* xDlOpen */                     \
29138     unixDlError,          /* xDlError */                    \
29139     unixDlSym,            /* xDlSym */                      \
29140     unixDlClose,          /* xDlClose */                    \
29141     unixRandomness,       /* xRandomness */                 \
29142     unixSleep,            /* xSleep */                      \
29143     unixCurrentTime,      /* xCurrentTime */                \
29144     unixGetLastError,     /* xGetLastError */               \
29145     unixCurrentTimeInt64, /* xCurrentTimeInt64 */           \
29146   }
29147
29148   /*
29149   ** All default VFSes for unix are contained in the following array.
29150   **
29151   ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
29152   ** by the SQLite core when the VFS is registered.  So the following
29153   ** array cannot be const.
29154   */
29155   static sqlite3_vfs aVfs[] = {
29156 #if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
29157     UNIXVFS("unix",          autolockIoFinder ),
29158 #else
29159     UNIXVFS("unix",          posixIoFinder ),
29160 #endif
29161     UNIXVFS("unix-none",     nolockIoFinder ),
29162     UNIXVFS("unix-dotfile",  dotlockIoFinder ),
29163 #if OS_VXWORKS
29164     UNIXVFS("unix-namedsem", semIoFinder ),
29165 #endif
29166 #if SQLITE_ENABLE_LOCKING_STYLE
29167     UNIXVFS("unix-posix",    posixIoFinder ),
29168 #if !OS_VXWORKS
29169     UNIXVFS("unix-flock",    flockIoFinder ),
29170 #endif
29171 #endif
29172 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
29173     UNIXVFS("unix-afp",      afpIoFinder ),
29174     UNIXVFS("unix-nfs",      nfsIoFinder ),
29175     UNIXVFS("unix-proxy",    proxyIoFinder ),
29176 #endif
29177   };
29178   unsigned int i;          /* Loop counter */
29179
29180   /* Register all VFSes defined in the aVfs[] array */
29181   for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
29182     sqlite3_vfs_register(&aVfs[i], i==0);
29183   }
29184   return SQLITE_OK; 
29185 }
29186
29187 /*
29188 ** Shutdown the operating system interface.
29189 **
29190 ** Some operating systems might need to do some cleanup in this routine,
29191 ** to release dynamically allocated objects.  But not on unix.
29192 ** This routine is a no-op for unix.
29193 */
29194 SQLITE_API int sqlite3_os_end(void){ 
29195   return SQLITE_OK; 
29196 }
29197  
29198 #endif /* SQLITE_OS_UNIX */
29199
29200 /************** End of os_unix.c *********************************************/
29201 /************** Begin file os_win.c ******************************************/
29202 /*
29203 ** 2004 May 22
29204 **
29205 ** The author disclaims copyright to this source code.  In place of
29206 ** a legal notice, here is a blessing:
29207 **
29208 **    May you do good and not evil.
29209 **    May you find forgiveness for yourself and forgive others.
29210 **    May you share freely, never taking more than you give.
29211 **
29212 ******************************************************************************
29213 **
29214 ** This file contains code that is specific to windows.
29215 */
29216 #if SQLITE_OS_WIN               /* This file is used for windows only */
29217
29218
29219 /*
29220 ** A Note About Memory Allocation:
29221 **
29222 ** This driver uses malloc()/free() directly rather than going through
29223 ** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
29224 ** are designed for use on embedded systems where memory is scarce and
29225 ** malloc failures happen frequently.  Win32 does not typically run on
29226 ** embedded systems, and when it does the developers normally have bigger
29227 ** problems to worry about than running out of memory.  So there is not
29228 ** a compelling need to use the wrappers.
29229 **
29230 ** But there is a good reason to not use the wrappers.  If we use the
29231 ** wrappers then we will get simulated malloc() failures within this
29232 ** driver.  And that causes all kinds of problems for our tests.  We
29233 ** could enhance SQLite to deal with simulated malloc failures within
29234 ** the OS driver, but the code to deal with those failure would not
29235 ** be exercised on Linux (which does not need to malloc() in the driver)
29236 ** and so we would have difficulty writing coverage tests for that
29237 ** code.  Better to leave the code out, we think.
29238 **
29239 ** The point of this discussion is as follows:  When creating a new
29240 ** OS layer for an embedded system, if you use this file as an example,
29241 ** avoid the use of malloc()/free().  Those routines work ok on windows
29242 ** desktops but not so well in embedded systems.
29243 */
29244
29245 #include <winbase.h>
29246
29247 #ifdef __CYGWIN__
29248 # include <sys/cygwin.h>
29249 #endif
29250
29251 /*
29252 ** Macros used to determine whether or not to use threads.
29253 */
29254 #if defined(THREADSAFE) && THREADSAFE
29255 # define SQLITE_W32_THREADS 1
29256 #endif
29257
29258 /*
29259 ** Include code that is common to all os_*.c files
29260 */
29261 /************** Include os_common.h in the middle of os_win.c ****************/
29262 /************** Begin file os_common.h ***************************************/
29263 /*
29264 ** 2004 May 22
29265 **
29266 ** The author disclaims copyright to this source code.  In place of
29267 ** a legal notice, here is a blessing:
29268 **
29269 **    May you do good and not evil.
29270 **    May you find forgiveness for yourself and forgive others.
29271 **    May you share freely, never taking more than you give.
29272 **
29273 ******************************************************************************
29274 **
29275 ** This file contains macros and a little bit of code that is common to
29276 ** all of the platform-specific files (os_*.c) and is #included into those
29277 ** files.
29278 **
29279 ** This file should be #included by the os_*.c files only.  It is not a
29280 ** general purpose header file.
29281 */
29282 #ifndef _OS_COMMON_H_
29283 #define _OS_COMMON_H_
29284
29285 /*
29286 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
29287 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
29288 ** switch.  The following code should catch this problem at compile-time.
29289 */
29290 #ifdef MEMORY_DEBUG
29291 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
29292 #endif
29293
29294 #ifdef SQLITE_DEBUG
29295 SQLITE_PRIVATE int sqlite3OSTrace = 0;
29296 #define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
29297 #else
29298 #define OSTRACE(X)
29299 #endif
29300
29301 /*
29302 ** Macros for performance tracing.  Normally turned off.  Only works
29303 ** on i486 hardware.
29304 */
29305 #ifdef SQLITE_PERFORMANCE_TRACE
29306
29307 /* 
29308 ** hwtime.h contains inline assembler code for implementing 
29309 ** high-performance timing routines.
29310 */
29311 /************** Include hwtime.h in the middle of os_common.h ****************/
29312 /************** Begin file hwtime.h ******************************************/
29313 /*
29314 ** 2008 May 27
29315 **
29316 ** The author disclaims copyright to this source code.  In place of
29317 ** a legal notice, here is a blessing:
29318 **
29319 **    May you do good and not evil.
29320 **    May you find forgiveness for yourself and forgive others.
29321 **    May you share freely, never taking more than you give.
29322 **
29323 ******************************************************************************
29324 **
29325 ** This file contains inline asm code for retrieving "high-performance"
29326 ** counters for x86 class CPUs.
29327 */
29328 #ifndef _HWTIME_H_
29329 #define _HWTIME_H_
29330
29331 /*
29332 ** The following routine only works on pentium-class (or newer) processors.
29333 ** It uses the RDTSC opcode to read the cycle count value out of the
29334 ** processor and returns that value.  This can be used for high-res
29335 ** profiling.
29336 */
29337 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
29338       (defined(i386) || defined(__i386__) || defined(_M_IX86))
29339
29340   #if defined(__GNUC__)
29341
29342   __inline__ sqlite_uint64 sqlite3Hwtime(void){
29343      unsigned int lo, hi;
29344      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
29345      return (sqlite_uint64)hi << 32 | lo;
29346   }
29347
29348   #elif defined(_MSC_VER)
29349
29350   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
29351      __asm {
29352         rdtsc
29353         ret       ; return value at EDX:EAX
29354      }
29355   }
29356
29357   #endif
29358
29359 #elif (defined(__GNUC__) && defined(__x86_64__))
29360
29361   __inline__ sqlite_uint64 sqlite3Hwtime(void){
29362       unsigned long val;
29363       __asm__ __volatile__ ("rdtsc" : "=A" (val));
29364       return val;
29365   }
29366  
29367 #elif (defined(__GNUC__) && defined(__ppc__))
29368
29369   __inline__ sqlite_uint64 sqlite3Hwtime(void){
29370       unsigned long long retval;
29371       unsigned long junk;
29372       __asm__ __volatile__ ("\n\
29373           1:      mftbu   %1\n\
29374                   mftb    %L0\n\
29375                   mftbu   %0\n\
29376                   cmpw    %0,%1\n\
29377                   bne     1b"
29378                   : "=r" (retval), "=r" (junk));
29379       return retval;
29380   }
29381
29382 #else
29383
29384   #error Need implementation of sqlite3Hwtime() for your platform.
29385
29386   /*
29387   ** To compile without implementing sqlite3Hwtime() for your platform,
29388   ** you can remove the above #error and use the following
29389   ** stub function.  You will lose timing support for many
29390   ** of the debugging and testing utilities, but it should at
29391   ** least compile and run.
29392   */
29393 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
29394
29395 #endif
29396
29397 #endif /* !defined(_HWTIME_H_) */
29398
29399 /************** End of hwtime.h **********************************************/
29400 /************** Continuing where we left off in os_common.h ******************/
29401
29402 static sqlite_uint64 g_start;
29403 static sqlite_uint64 g_elapsed;
29404 #define TIMER_START       g_start=sqlite3Hwtime()
29405 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
29406 #define TIMER_ELAPSED     g_elapsed
29407 #else
29408 #define TIMER_START
29409 #define TIMER_END
29410 #define TIMER_ELAPSED     ((sqlite_uint64)0)
29411 #endif
29412
29413 /*
29414 ** If we compile with the SQLITE_TEST macro set, then the following block
29415 ** of code will give us the ability to simulate a disk I/O error.  This
29416 ** is used for testing the I/O recovery logic.
29417 */
29418 #ifdef SQLITE_TEST
29419 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
29420 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
29421 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
29422 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
29423 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
29424 SQLITE_API int sqlite3_diskfull_pending = 0;
29425 SQLITE_API int sqlite3_diskfull = 0;
29426 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
29427 #define SimulateIOError(CODE)  \
29428   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
29429        || sqlite3_io_error_pending-- == 1 )  \
29430               { local_ioerr(); CODE; }
29431 static void local_ioerr(){
29432   IOTRACE(("IOERR\n"));
29433   sqlite3_io_error_hit++;
29434   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
29435 }
29436 #define SimulateDiskfullError(CODE) \
29437    if( sqlite3_diskfull_pending ){ \
29438      if( sqlite3_diskfull_pending == 1 ){ \
29439        local_ioerr(); \
29440        sqlite3_diskfull = 1; \
29441        sqlite3_io_error_hit = 1; \
29442        CODE; \
29443      }else{ \
29444        sqlite3_diskfull_pending--; \
29445      } \
29446    }
29447 #else
29448 #define SimulateIOErrorBenign(X)
29449 #define SimulateIOError(A)
29450 #define SimulateDiskfullError(A)
29451 #endif
29452
29453 /*
29454 ** When testing, keep a count of the number of open files.
29455 */
29456 #ifdef SQLITE_TEST
29457 SQLITE_API int sqlite3_open_file_count = 0;
29458 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
29459 #else
29460 #define OpenCounter(X)
29461 #endif
29462
29463 #endif /* !defined(_OS_COMMON_H_) */
29464
29465 /************** End of os_common.h *******************************************/
29466 /************** Continuing where we left off in os_win.c *********************/
29467
29468 /*
29469 ** Some microsoft compilers lack this definition.
29470 */
29471 #ifndef INVALID_FILE_ATTRIBUTES
29472 # define INVALID_FILE_ATTRIBUTES ((DWORD)-1) 
29473 #endif
29474
29475 /*
29476 ** Determine if we are dealing with WindowsCE - which has a much
29477 ** reduced API.
29478 */
29479 #if SQLITE_OS_WINCE
29480 # define AreFileApisANSI() 1
29481 # define FormatMessageW(a,b,c,d,e,f,g) 0
29482 #endif
29483
29484 /* Forward references */
29485 typedef struct winShm winShm;           /* A connection to shared-memory */
29486 typedef struct winShmNode winShmNode;   /* A region of shared-memory */
29487
29488 /*
29489 ** WinCE lacks native support for file locking so we have to fake it
29490 ** with some code of our own.
29491 */
29492 #if SQLITE_OS_WINCE
29493 typedef struct winceLock {
29494   int nReaders;       /* Number of reader locks obtained */
29495   BOOL bPending;      /* Indicates a pending lock has been obtained */
29496   BOOL bReserved;     /* Indicates a reserved lock has been obtained */
29497   BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
29498 } winceLock;
29499 #endif
29500
29501 /*
29502 ** The winFile structure is a subclass of sqlite3_file* specific to the win32
29503 ** portability layer.
29504 */
29505 typedef struct winFile winFile;
29506 struct winFile {
29507   const sqlite3_io_methods *pMethod; /*** Must be first ***/
29508   sqlite3_vfs *pVfs;      /* The VFS used to open this file */
29509   HANDLE h;               /* Handle for accessing the file */
29510   unsigned char locktype; /* Type of lock currently held on this file */
29511   short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
29512   DWORD lastErrno;        /* The Windows errno from the last I/O error */
29513   DWORD sectorSize;       /* Sector size of the device file is on */
29514   winShm *pShm;           /* Instance of shared memory on this file */
29515   const char *zPath;      /* Full pathname of this file */
29516   int szChunk;            /* Chunk size configured by FCNTL_CHUNK_SIZE */
29517 #if SQLITE_OS_WINCE
29518   WCHAR *zDeleteOnClose;  /* Name of file to delete when closing */
29519   HANDLE hMutex;          /* Mutex used to control access to shared lock */  
29520   HANDLE hShared;         /* Shared memory segment used for locking */
29521   winceLock local;        /* Locks obtained by this instance of winFile */
29522   winceLock *shared;      /* Global shared lock memory for the file  */
29523 #endif
29524 };
29525
29526 /*
29527 ** Forward prototypes.
29528 */
29529 static int getSectorSize(
29530     sqlite3_vfs *pVfs,
29531     const char *zRelative     /* UTF-8 file name */
29532 );
29533
29534 /*
29535 ** The following variable is (normally) set once and never changes
29536 ** thereafter.  It records whether the operating system is Win95
29537 ** or WinNT.
29538 **
29539 ** 0:   Operating system unknown.
29540 ** 1:   Operating system is Win95.
29541 ** 2:   Operating system is WinNT.
29542 **
29543 ** In order to facilitate testing on a WinNT system, the test fixture
29544 ** can manually set this value to 1 to emulate Win98 behavior.
29545 */
29546 #ifdef SQLITE_TEST
29547 SQLITE_API int sqlite3_os_type = 0;
29548 #else
29549 static int sqlite3_os_type = 0;
29550 #endif
29551
29552 /*
29553 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
29554 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
29555 **
29556 ** Here is an interesting observation:  Win95, Win98, and WinME lack
29557 ** the LockFileEx() API.  But we can still statically link against that
29558 ** API as long as we don't call it when running Win95/98/ME.  A call to
29559 ** this routine is used to determine if the host is Win95/98/ME or
29560 ** WinNT/2K/XP so that we will know whether or not we can safely call
29561 ** the LockFileEx() API.
29562 */
29563 #if SQLITE_OS_WINCE
29564 # define isNT()  (1)
29565 #else
29566   static int isNT(void){
29567     if( sqlite3_os_type==0 ){
29568       OSVERSIONINFO sInfo;
29569       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
29570       GetVersionEx(&sInfo);
29571       sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
29572     }
29573     return sqlite3_os_type==2;
29574   }
29575 #endif /* SQLITE_OS_WINCE */
29576
29577 /*
29578 ** Convert a UTF-8 string to microsoft unicode (UTF-16?). 
29579 **
29580 ** Space to hold the returned string is obtained from malloc.
29581 */
29582 static WCHAR *utf8ToUnicode(const char *zFilename){
29583   int nChar;
29584   WCHAR *zWideFilename;
29585
29586   nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
29587   zWideFilename = malloc( nChar*sizeof(zWideFilename[0]) );
29588   if( zWideFilename==0 ){
29589     return 0;
29590   }
29591   nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename, nChar);
29592   if( nChar==0 ){
29593     free(zWideFilename);
29594     zWideFilename = 0;
29595   }
29596   return zWideFilename;
29597 }
29598
29599 /*
29600 ** Convert microsoft unicode to UTF-8.  Space to hold the returned string is
29601 ** obtained from malloc().
29602 */
29603 static char *unicodeToUtf8(const WCHAR *zWideFilename){
29604   int nByte;
29605   char *zFilename;
29606
29607   nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
29608   zFilename = malloc( nByte );
29609   if( zFilename==0 ){
29610     return 0;
29611   }
29612   nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
29613                               0, 0);
29614   if( nByte == 0 ){
29615     free(zFilename);
29616     zFilename = 0;
29617   }
29618   return zFilename;
29619 }
29620
29621 /*
29622 ** Convert an ansi string to microsoft unicode, based on the
29623 ** current codepage settings for file apis.
29624 ** 
29625 ** Space to hold the returned string is obtained
29626 ** from malloc.
29627 */
29628 static WCHAR *mbcsToUnicode(const char *zFilename){
29629   int nByte;
29630   WCHAR *zMbcsFilename;
29631   int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
29632
29633   nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, NULL,0)*sizeof(WCHAR);
29634   zMbcsFilename = malloc( nByte*sizeof(zMbcsFilename[0]) );
29635   if( zMbcsFilename==0 ){
29636     return 0;
29637   }
29638   nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename, nByte);
29639   if( nByte==0 ){
29640     free(zMbcsFilename);
29641     zMbcsFilename = 0;
29642   }
29643   return zMbcsFilename;
29644 }
29645
29646 /*
29647 ** Convert microsoft unicode to multibyte character string, based on the
29648 ** user's Ansi codepage.
29649 **
29650 ** Space to hold the returned string is obtained from
29651 ** malloc().
29652 */
29653 static char *unicodeToMbcs(const WCHAR *zWideFilename){
29654   int nByte;
29655   char *zFilename;
29656   int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
29657
29658   nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
29659   zFilename = malloc( nByte );
29660   if( zFilename==0 ){
29661     return 0;
29662   }
29663   nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename, nByte,
29664                               0, 0);
29665   if( nByte == 0 ){
29666     free(zFilename);
29667     zFilename = 0;
29668   }
29669   return zFilename;
29670 }
29671
29672 /*
29673 ** Convert multibyte character string to UTF-8.  Space to hold the
29674 ** returned string is obtained from malloc().
29675 */
29676 SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
29677   char *zFilenameUtf8;
29678   WCHAR *zTmpWide;
29679
29680   zTmpWide = mbcsToUnicode(zFilename);
29681   if( zTmpWide==0 ){
29682     return 0;
29683   }
29684   zFilenameUtf8 = unicodeToUtf8(zTmpWide);
29685   free(zTmpWide);
29686   return zFilenameUtf8;
29687 }
29688
29689 /*
29690 ** Convert UTF-8 to multibyte character string.  Space to hold the 
29691 ** returned string is obtained from malloc().
29692 */
29693 static char *utf8ToMbcs(const char *zFilename){
29694   char *zFilenameMbcs;
29695   WCHAR *zTmpWide;
29696
29697   zTmpWide = utf8ToUnicode(zFilename);
29698   if( zTmpWide==0 ){
29699     return 0;
29700   }
29701   zFilenameMbcs = unicodeToMbcs(zTmpWide);
29702   free(zTmpWide);
29703   return zFilenameMbcs;
29704 }
29705
29706 #if SQLITE_OS_WINCE
29707 /*************************************************************************
29708 ** This section contains code for WinCE only.
29709 */
29710 /*
29711 ** WindowsCE does not have a localtime() function.  So create a
29712 ** substitute.
29713 */
29714 struct tm *__cdecl localtime(const time_t *t)
29715 {
29716   static struct tm y;
29717   FILETIME uTm, lTm;
29718   SYSTEMTIME pTm;
29719   sqlite3_int64 t64;
29720   t64 = *t;
29721   t64 = (t64 + 11644473600)*10000000;
29722   uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
29723   uTm.dwHighDateTime= (DWORD)(t64 >> 32);
29724   FileTimeToLocalFileTime(&uTm,&lTm);
29725   FileTimeToSystemTime(&lTm,&pTm);
29726   y.tm_year = pTm.wYear - 1900;
29727   y.tm_mon = pTm.wMonth - 1;
29728   y.tm_wday = pTm.wDayOfWeek;
29729   y.tm_mday = pTm.wDay;
29730   y.tm_hour = pTm.wHour;
29731   y.tm_min = pTm.wMinute;
29732   y.tm_sec = pTm.wSecond;
29733   return &y;
29734 }
29735
29736 /* This will never be called, but defined to make the code compile */
29737 #define GetTempPathA(a,b)
29738
29739 #define LockFile(a,b,c,d,e)       winceLockFile(&a, b, c, d, e)
29740 #define UnlockFile(a,b,c,d,e)     winceUnlockFile(&a, b, c, d, e)
29741 #define LockFileEx(a,b,c,d,e,f)   winceLockFileEx(&a, b, c, d, e, f)
29742
29743 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
29744
29745 /*
29746 ** Acquire a lock on the handle h
29747 */
29748 static void winceMutexAcquire(HANDLE h){
29749    DWORD dwErr;
29750    do {
29751      dwErr = WaitForSingleObject(h, INFINITE);
29752    } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
29753 }
29754 /*
29755 ** Release a lock acquired by winceMutexAcquire()
29756 */
29757 #define winceMutexRelease(h) ReleaseMutex(h)
29758
29759 /*
29760 ** Create the mutex and shared memory used for locking in the file
29761 ** descriptor pFile
29762 */
29763 static BOOL winceCreateLock(const char *zFilename, winFile *pFile){
29764   WCHAR *zTok;
29765   WCHAR *zName = utf8ToUnicode(zFilename);
29766   BOOL bInit = TRUE;
29767
29768   /* Initialize the local lockdata */
29769   ZeroMemory(&pFile->local, sizeof(pFile->local));
29770
29771   /* Replace the backslashes from the filename and lowercase it
29772   ** to derive a mutex name. */
29773   zTok = CharLowerW(zName);
29774   for (;*zTok;zTok++){
29775     if (*zTok == '\\') *zTok = '_';
29776   }
29777
29778   /* Create/open the named mutex */
29779   pFile->hMutex = CreateMutexW(NULL, FALSE, zName);
29780   if (!pFile->hMutex){
29781     pFile->lastErrno = GetLastError();
29782     free(zName);
29783     return FALSE;
29784   }
29785
29786   /* Acquire the mutex before continuing */
29787   winceMutexAcquire(pFile->hMutex);
29788   
29789   /* Since the names of named mutexes, semaphores, file mappings etc are 
29790   ** case-sensitive, take advantage of that by uppercasing the mutex name
29791   ** and using that as the shared filemapping name.
29792   */
29793   CharUpperW(zName);
29794   pFile->hShared = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
29795                                        PAGE_READWRITE, 0, sizeof(winceLock),
29796                                        zName);  
29797
29798   /* Set a flag that indicates we're the first to create the memory so it 
29799   ** must be zero-initialized */
29800   if (GetLastError() == ERROR_ALREADY_EXISTS){
29801     bInit = FALSE;
29802   }
29803
29804   free(zName);
29805
29806   /* If we succeeded in making the shared memory handle, map it. */
29807   if (pFile->hShared){
29808     pFile->shared = (winceLock*)MapViewOfFile(pFile->hShared, 
29809              FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
29810     /* If mapping failed, close the shared memory handle and erase it */
29811     if (!pFile->shared){
29812       pFile->lastErrno = GetLastError();
29813       CloseHandle(pFile->hShared);
29814       pFile->hShared = NULL;
29815     }
29816   }
29817
29818   /* If shared memory could not be created, then close the mutex and fail */
29819   if (pFile->hShared == NULL){
29820     winceMutexRelease(pFile->hMutex);
29821     CloseHandle(pFile->hMutex);
29822     pFile->hMutex = NULL;
29823     return FALSE;
29824   }
29825   
29826   /* Initialize the shared memory if we're supposed to */
29827   if (bInit) {
29828     ZeroMemory(pFile->shared, sizeof(winceLock));
29829   }
29830
29831   winceMutexRelease(pFile->hMutex);
29832   return TRUE;
29833 }
29834
29835 /*
29836 ** Destroy the part of winFile that deals with wince locks
29837 */
29838 static void winceDestroyLock(winFile *pFile){
29839   if (pFile->hMutex){
29840     /* Acquire the mutex */
29841     winceMutexAcquire(pFile->hMutex);
29842
29843     /* The following blocks should probably assert in debug mode, but they
29844        are to cleanup in case any locks remained open */
29845     if (pFile->local.nReaders){
29846       pFile->shared->nReaders --;
29847     }
29848     if (pFile->local.bReserved){
29849       pFile->shared->bReserved = FALSE;
29850     }
29851     if (pFile->local.bPending){
29852       pFile->shared->bPending = FALSE;
29853     }
29854     if (pFile->local.bExclusive){
29855       pFile->shared->bExclusive = FALSE;
29856     }
29857
29858     /* De-reference and close our copy of the shared memory handle */
29859     UnmapViewOfFile(pFile->shared);
29860     CloseHandle(pFile->hShared);
29861
29862     /* Done with the mutex */
29863     winceMutexRelease(pFile->hMutex);    
29864     CloseHandle(pFile->hMutex);
29865     pFile->hMutex = NULL;
29866   }
29867 }
29868
29869 /* 
29870 ** An implementation of the LockFile() API of windows for wince
29871 */
29872 static BOOL winceLockFile(
29873   HANDLE *phFile,
29874   DWORD dwFileOffsetLow,
29875   DWORD dwFileOffsetHigh,
29876   DWORD nNumberOfBytesToLockLow,
29877   DWORD nNumberOfBytesToLockHigh
29878 ){
29879   winFile *pFile = HANDLE_TO_WINFILE(phFile);
29880   BOOL bReturn = FALSE;
29881
29882   UNUSED_PARAMETER(dwFileOffsetHigh);
29883   UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
29884
29885   if (!pFile->hMutex) return TRUE;
29886   winceMutexAcquire(pFile->hMutex);
29887
29888   /* Wanting an exclusive lock? */
29889   if (dwFileOffsetLow == (DWORD)SHARED_FIRST
29890        && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
29891     if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
29892        pFile->shared->bExclusive = TRUE;
29893        pFile->local.bExclusive = TRUE;
29894        bReturn = TRUE;
29895     }
29896   }
29897
29898   /* Want a read-only lock? */
29899   else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
29900            nNumberOfBytesToLockLow == 1){
29901     if (pFile->shared->bExclusive == 0){
29902       pFile->local.nReaders ++;
29903       if (pFile->local.nReaders == 1){
29904         pFile->shared->nReaders ++;
29905       }
29906       bReturn = TRUE;
29907     }
29908   }
29909
29910   /* Want a pending lock? */
29911   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToLockLow == 1){
29912     /* If no pending lock has been acquired, then acquire it */
29913     if (pFile->shared->bPending == 0) {
29914       pFile->shared->bPending = TRUE;
29915       pFile->local.bPending = TRUE;
29916       bReturn = TRUE;
29917     }
29918   }
29919
29920   /* Want a reserved lock? */
29921   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToLockLow == 1){
29922     if (pFile->shared->bReserved == 0) {
29923       pFile->shared->bReserved = TRUE;
29924       pFile->local.bReserved = TRUE;
29925       bReturn = TRUE;
29926     }
29927   }
29928
29929   winceMutexRelease(pFile->hMutex);
29930   return bReturn;
29931 }
29932
29933 /*
29934 ** An implementation of the UnlockFile API of windows for wince
29935 */
29936 static BOOL winceUnlockFile(
29937   HANDLE *phFile,
29938   DWORD dwFileOffsetLow,
29939   DWORD dwFileOffsetHigh,
29940   DWORD nNumberOfBytesToUnlockLow,
29941   DWORD nNumberOfBytesToUnlockHigh
29942 ){
29943   winFile *pFile = HANDLE_TO_WINFILE(phFile);
29944   BOOL bReturn = FALSE;
29945
29946   UNUSED_PARAMETER(dwFileOffsetHigh);
29947   UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
29948
29949   if (!pFile->hMutex) return TRUE;
29950   winceMutexAcquire(pFile->hMutex);
29951
29952   /* Releasing a reader lock or an exclusive lock */
29953   if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
29954     /* Did we have an exclusive lock? */
29955     if (pFile->local.bExclusive){
29956       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
29957       pFile->local.bExclusive = FALSE;
29958       pFile->shared->bExclusive = FALSE;
29959       bReturn = TRUE;
29960     }
29961
29962     /* Did we just have a reader lock? */
29963     else if (pFile->local.nReaders){
29964       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE || nNumberOfBytesToUnlockLow == 1);
29965       pFile->local.nReaders --;
29966       if (pFile->local.nReaders == 0)
29967       {
29968         pFile->shared->nReaders --;
29969       }
29970       bReturn = TRUE;
29971     }
29972   }
29973
29974   /* Releasing a pending lock */
29975   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToUnlockLow == 1){
29976     if (pFile->local.bPending){
29977       pFile->local.bPending = FALSE;
29978       pFile->shared->bPending = FALSE;
29979       bReturn = TRUE;
29980     }
29981   }
29982   /* Releasing a reserved lock */
29983   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToUnlockLow == 1){
29984     if (pFile->local.bReserved) {
29985       pFile->local.bReserved = FALSE;
29986       pFile->shared->bReserved = FALSE;
29987       bReturn = TRUE;
29988     }
29989   }
29990
29991   winceMutexRelease(pFile->hMutex);
29992   return bReturn;
29993 }
29994
29995 /*
29996 ** An implementation of the LockFileEx() API of windows for wince
29997 */
29998 static BOOL winceLockFileEx(
29999   HANDLE *phFile,
30000   DWORD dwFlags,
30001   DWORD dwReserved,
30002   DWORD nNumberOfBytesToLockLow,
30003   DWORD nNumberOfBytesToLockHigh,
30004   LPOVERLAPPED lpOverlapped
30005 ){
30006   UNUSED_PARAMETER(dwReserved);
30007   UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
30008
30009   /* If the caller wants a shared read lock, forward this call
30010   ** to winceLockFile */
30011   if (lpOverlapped->Offset == (DWORD)SHARED_FIRST &&
30012       dwFlags == 1 &&
30013       nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
30014     return winceLockFile(phFile, SHARED_FIRST, 0, 1, 0);
30015   }
30016   return FALSE;
30017 }
30018 /*
30019 ** End of the special code for wince
30020 *****************************************************************************/
30021 #endif /* SQLITE_OS_WINCE */
30022
30023 /*****************************************************************************
30024 ** The next group of routines implement the I/O methods specified
30025 ** by the sqlite3_io_methods object.
30026 ******************************************************************************/
30027
30028 /*
30029 ** Some microsoft compilers lack this definition.
30030 */
30031 #ifndef INVALID_SET_FILE_POINTER
30032 # define INVALID_SET_FILE_POINTER ((DWORD)-1)
30033 #endif
30034
30035 /*
30036 ** Move the current position of the file handle passed as the first 
30037 ** argument to offset iOffset within the file. If successful, return 0. 
30038 ** Otherwise, set pFile->lastErrno and return non-zero.
30039 */
30040 static int seekWinFile(winFile *pFile, sqlite3_int64 iOffset){
30041   LONG upperBits;                 /* Most sig. 32 bits of new offset */
30042   LONG lowerBits;                 /* Least sig. 32 bits of new offset */
30043   DWORD dwRet;                    /* Value returned by SetFilePointer() */
30044
30045   upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
30046   lowerBits = (LONG)(iOffset & 0xffffffff);
30047
30048   /* API oddity: If successful, SetFilePointer() returns a dword 
30049   ** containing the lower 32-bits of the new file-offset. Or, if it fails,
30050   ** it returns INVALID_SET_FILE_POINTER. However according to MSDN, 
30051   ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine 
30052   ** whether an error has actually occured, it is also necessary to call 
30053   ** GetLastError().
30054   */
30055   dwRet = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
30056   if( (dwRet==INVALID_SET_FILE_POINTER && GetLastError()!=NO_ERROR) ){
30057     pFile->lastErrno = GetLastError();
30058     return 1;
30059   }
30060
30061   return 0;
30062 }
30063
30064 /*
30065 ** Close a file.
30066 **
30067 ** It is reported that an attempt to close a handle might sometimes
30068 ** fail.  This is a very unreasonable result, but windows is notorious
30069 ** for being unreasonable so I do not doubt that it might happen.  If
30070 ** the close fails, we pause for 100 milliseconds and try again.  As
30071 ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
30072 ** giving up and returning an error.
30073 */
30074 #define MX_CLOSE_ATTEMPT 3
30075 static int winClose(sqlite3_file *id){
30076   int rc, cnt = 0;
30077   winFile *pFile = (winFile*)id;
30078
30079   assert( id!=0 );
30080   assert( pFile->pShm==0 );
30081   OSTRACE(("CLOSE %d\n", pFile->h));
30082   do{
30083     rc = CloseHandle(pFile->h);
30084     /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
30085   }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (Sleep(100), 1) );
30086 #if SQLITE_OS_WINCE
30087 #define WINCE_DELETION_ATTEMPTS 3
30088   winceDestroyLock(pFile);
30089   if( pFile->zDeleteOnClose ){
30090     int cnt = 0;
30091     while(
30092            DeleteFileW(pFile->zDeleteOnClose)==0
30093         && GetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff 
30094         && cnt++ < WINCE_DELETION_ATTEMPTS
30095     ){
30096        Sleep(100);  /* Wait a little before trying again */
30097     }
30098     free(pFile->zDeleteOnClose);
30099   }
30100 #endif
30101   OSTRACE(("CLOSE %d %s\n", pFile->h, rc ? "ok" : "failed"));
30102   OpenCounter(-1);
30103   return rc ? SQLITE_OK : SQLITE_IOERR;
30104 }
30105
30106 /*
30107 ** Read data from a file into a buffer.  Return SQLITE_OK if all
30108 ** bytes were read successfully and SQLITE_IOERR if anything goes
30109 ** wrong.
30110 */
30111 static int winRead(
30112   sqlite3_file *id,          /* File to read from */
30113   void *pBuf,                /* Write content into this buffer */
30114   int amt,                   /* Number of bytes to read */
30115   sqlite3_int64 offset       /* Begin reading at this offset */
30116 ){
30117   winFile *pFile = (winFile*)id;  /* file handle */
30118   DWORD nRead;                    /* Number of bytes actually read from file */
30119
30120   assert( id!=0 );
30121   SimulateIOError(return SQLITE_IOERR_READ);
30122   OSTRACE(("READ %d lock=%d\n", pFile->h, pFile->locktype));
30123
30124   if( seekWinFile(pFile, offset) ){
30125     return SQLITE_FULL;
30126   }
30127   if( !ReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
30128     pFile->lastErrno = GetLastError();
30129     return SQLITE_IOERR_READ;
30130   }
30131   if( nRead<(DWORD)amt ){
30132     /* Unread parts of the buffer must be zero-filled */
30133     memset(&((char*)pBuf)[nRead], 0, amt-nRead);
30134     return SQLITE_IOERR_SHORT_READ;
30135   }
30136
30137   return SQLITE_OK;
30138 }
30139
30140 /*
30141 ** Write data from a buffer into a file.  Return SQLITE_OK on success
30142 ** or some other error code on failure.
30143 */
30144 static int winWrite(
30145   sqlite3_file *id,               /* File to write into */
30146   const void *pBuf,               /* The bytes to be written */
30147   int amt,                        /* Number of bytes to write */
30148   sqlite3_int64 offset            /* Offset into the file to begin writing at */
30149 ){
30150   int rc;                         /* True if error has occured, else false */
30151   winFile *pFile = (winFile*)id;  /* File handle */
30152
30153   assert( amt>0 );
30154   assert( pFile );
30155   SimulateIOError(return SQLITE_IOERR_WRITE);
30156   SimulateDiskfullError(return SQLITE_FULL);
30157
30158   OSTRACE(("WRITE %d lock=%d\n", pFile->h, pFile->locktype));
30159
30160   rc = seekWinFile(pFile, offset);
30161   if( rc==0 ){
30162     u8 *aRem = (u8 *)pBuf;        /* Data yet to be written */
30163     int nRem = amt;               /* Number of bytes yet to be written */
30164     DWORD nWrite;                 /* Bytes written by each WriteFile() call */
30165
30166     while( nRem>0 && WriteFile(pFile->h, aRem, nRem, &nWrite, 0) && nWrite>0 ){
30167       aRem += nWrite;
30168       nRem -= nWrite;
30169     }
30170     if( nRem>0 ){
30171       pFile->lastErrno = GetLastError();
30172       rc = 1;
30173     }
30174   }
30175
30176   if( rc ){
30177     if( pFile->lastErrno==ERROR_HANDLE_DISK_FULL ){
30178       return SQLITE_FULL;
30179     }
30180     return SQLITE_IOERR_WRITE;
30181   }
30182   return SQLITE_OK;
30183 }
30184
30185 /*
30186 ** Truncate an open file to a specified size
30187 */
30188 static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
30189   winFile *pFile = (winFile*)id;  /* File handle object */
30190   int rc = SQLITE_OK;             /* Return code for this function */
30191
30192   assert( pFile );
30193
30194   OSTRACE(("TRUNCATE %d %lld\n", pFile->h, nByte));
30195   SimulateIOError(return SQLITE_IOERR_TRUNCATE);
30196
30197   /* If the user has configured a chunk-size for this file, truncate the
30198   ** file so that it consists of an integer number of chunks (i.e. the
30199   ** actual file size after the operation may be larger than the requested
30200   ** size).
30201   */
30202   if( pFile->szChunk ){
30203     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
30204   }
30205
30206   /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
30207   if( seekWinFile(pFile, nByte) ){
30208     rc = SQLITE_IOERR_TRUNCATE;
30209   }else if( 0==SetEndOfFile(pFile->h) ){
30210     pFile->lastErrno = GetLastError();
30211     rc = SQLITE_IOERR_TRUNCATE;
30212   }
30213
30214   OSTRACE(("TRUNCATE %d %lld %s\n", pFile->h, nByte, rc ? "failed" : "ok"));
30215   return rc;
30216 }
30217
30218 #ifdef SQLITE_TEST
30219 /*
30220 ** Count the number of fullsyncs and normal syncs.  This is used to test
30221 ** that syncs and fullsyncs are occuring at the right times.
30222 */
30223 SQLITE_API int sqlite3_sync_count = 0;
30224 SQLITE_API int sqlite3_fullsync_count = 0;
30225 #endif
30226
30227 /*
30228 ** Make sure all writes to a particular file are committed to disk.
30229 */
30230 static int winSync(sqlite3_file *id, int flags){
30231 #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || defined(SQLITE_DEBUG)
30232   winFile *pFile = (winFile*)id;
30233 #else
30234   UNUSED_PARAMETER(id);
30235 #endif
30236
30237   assert( pFile );
30238   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
30239   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
30240       || (flags&0x0F)==SQLITE_SYNC_FULL
30241   );
30242
30243   OSTRACE(("SYNC %d lock=%d\n", pFile->h, pFile->locktype));
30244
30245 #ifndef SQLITE_TEST
30246   UNUSED_PARAMETER(flags);
30247 #else
30248   if( flags & SQLITE_SYNC_FULL ){
30249     sqlite3_fullsync_count++;
30250   }
30251   sqlite3_sync_count++;
30252 #endif
30253
30254   /* Unix cannot, but some systems may return SQLITE_FULL from here. This
30255   ** line is to test that doing so does not cause any problems.
30256   */
30257   SimulateDiskfullError( return SQLITE_FULL );
30258   SimulateIOError( return SQLITE_IOERR; );
30259
30260   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
30261   ** no-op
30262   */
30263 #ifdef SQLITE_NO_SYNC
30264   return SQLITE_OK;
30265 #else
30266   if( FlushFileBuffers(pFile->h) ){
30267     return SQLITE_OK;
30268   }else{
30269     pFile->lastErrno = GetLastError();
30270     return SQLITE_IOERR;
30271   }
30272 #endif
30273 }
30274
30275 /*
30276 ** Determine the current size of a file in bytes
30277 */
30278 static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
30279   DWORD upperBits;
30280   DWORD lowerBits;
30281   winFile *pFile = (winFile*)id;
30282   DWORD error;
30283
30284   assert( id!=0 );
30285   SimulateIOError(return SQLITE_IOERR_FSTAT);
30286   lowerBits = GetFileSize(pFile->h, &upperBits);
30287   if(   (lowerBits == INVALID_FILE_SIZE)
30288      && ((error = GetLastError()) != NO_ERROR) )
30289   {
30290     pFile->lastErrno = error;
30291     return SQLITE_IOERR_FSTAT;
30292   }
30293   *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
30294   return SQLITE_OK;
30295 }
30296
30297 /*
30298 ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
30299 */
30300 #ifndef LOCKFILE_FAIL_IMMEDIATELY
30301 # define LOCKFILE_FAIL_IMMEDIATELY 1
30302 #endif
30303
30304 /*
30305 ** Acquire a reader lock.
30306 ** Different API routines are called depending on whether or not this
30307 ** is Win95 or WinNT.
30308 */
30309 static int getReadLock(winFile *pFile){
30310   int res;
30311   if( isNT() ){
30312     OVERLAPPED ovlp;
30313     ovlp.Offset = SHARED_FIRST;
30314     ovlp.OffsetHigh = 0;
30315     ovlp.hEvent = 0;
30316     res = LockFileEx(pFile->h, LOCKFILE_FAIL_IMMEDIATELY,
30317                      0, SHARED_SIZE, 0, &ovlp);
30318 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
30319 */
30320 #if SQLITE_OS_WINCE==0
30321   }else{
30322     int lk;
30323     sqlite3_randomness(sizeof(lk), &lk);
30324     pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
30325     res = LockFile(pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
30326 #endif
30327   }
30328   if( res == 0 ){
30329     pFile->lastErrno = GetLastError();
30330   }
30331   return res;
30332 }
30333
30334 /*
30335 ** Undo a readlock
30336 */
30337 static int unlockReadLock(winFile *pFile){
30338   int res;
30339   if( isNT() ){
30340     res = UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
30341 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
30342 */
30343 #if SQLITE_OS_WINCE==0
30344   }else{
30345     res = UnlockFile(pFile->h, SHARED_FIRST + pFile->sharedLockByte, 0, 1, 0);
30346 #endif
30347   }
30348   if( res == 0 ){
30349     pFile->lastErrno = GetLastError();
30350   }
30351   return res;
30352 }
30353
30354 /*
30355 ** Lock the file with the lock specified by parameter locktype - one
30356 ** of the following:
30357 **
30358 **     (1) SHARED_LOCK
30359 **     (2) RESERVED_LOCK
30360 **     (3) PENDING_LOCK
30361 **     (4) EXCLUSIVE_LOCK
30362 **
30363 ** Sometimes when requesting one lock state, additional lock states
30364 ** are inserted in between.  The locking might fail on one of the later
30365 ** transitions leaving the lock state different from what it started but
30366 ** still short of its goal.  The following chart shows the allowed
30367 ** transitions and the inserted intermediate states:
30368 **
30369 **    UNLOCKED -> SHARED
30370 **    SHARED -> RESERVED
30371 **    SHARED -> (PENDING) -> EXCLUSIVE
30372 **    RESERVED -> (PENDING) -> EXCLUSIVE
30373 **    PENDING -> EXCLUSIVE
30374 **
30375 ** This routine will only increase a lock.  The winUnlock() routine
30376 ** erases all locks at once and returns us immediately to locking level 0.
30377 ** It is not possible to lower the locking level one step at a time.  You
30378 ** must go straight to locking level 0.
30379 */
30380 static int winLock(sqlite3_file *id, int locktype){
30381   int rc = SQLITE_OK;    /* Return code from subroutines */
30382   int res = 1;           /* Result of a windows lock call */
30383   int newLocktype;       /* Set pFile->locktype to this value before exiting */
30384   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
30385   winFile *pFile = (winFile*)id;
30386   DWORD error = NO_ERROR;
30387
30388   assert( id!=0 );
30389   OSTRACE(("LOCK %d %d was %d(%d)\n",
30390            pFile->h, locktype, pFile->locktype, pFile->sharedLockByte));
30391
30392   /* If there is already a lock of this type or more restrictive on the
30393   ** OsFile, do nothing. Don't use the end_lock: exit path, as
30394   ** sqlite3OsEnterMutex() hasn't been called yet.
30395   */
30396   if( pFile->locktype>=locktype ){
30397     return SQLITE_OK;
30398   }
30399
30400   /* Make sure the locking sequence is correct
30401   */
30402   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
30403   assert( locktype!=PENDING_LOCK );
30404   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
30405
30406   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
30407   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
30408   ** the PENDING_LOCK byte is temporary.
30409   */
30410   newLocktype = pFile->locktype;
30411   if(   (pFile->locktype==NO_LOCK)
30412      || (   (locktype==EXCLUSIVE_LOCK)
30413          && (pFile->locktype==RESERVED_LOCK))
30414   ){
30415     int cnt = 3;
30416     while( cnt-->0 && (res = LockFile(pFile->h, PENDING_BYTE, 0, 1, 0))==0 ){
30417       /* Try 3 times to get the pending lock.  The pending lock might be
30418       ** held by another reader process who will release it momentarily.
30419       */
30420       OSTRACE(("could not get a PENDING lock. cnt=%d\n", cnt));
30421       Sleep(1);
30422     }
30423     gotPendingLock = res;
30424     if( !res ){
30425       error = GetLastError();
30426     }
30427   }
30428
30429   /* Acquire a shared lock
30430   */
30431   if( locktype==SHARED_LOCK && res ){
30432     assert( pFile->locktype==NO_LOCK );
30433     res = getReadLock(pFile);
30434     if( res ){
30435       newLocktype = SHARED_LOCK;
30436     }else{
30437       error = GetLastError();
30438     }
30439   }
30440
30441   /* Acquire a RESERVED lock
30442   */
30443   if( locktype==RESERVED_LOCK && res ){
30444     assert( pFile->locktype==SHARED_LOCK );
30445     res = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
30446     if( res ){
30447       newLocktype = RESERVED_LOCK;
30448     }else{
30449       error = GetLastError();
30450     }
30451   }
30452
30453   /* Acquire a PENDING lock
30454   */
30455   if( locktype==EXCLUSIVE_LOCK && res ){
30456     newLocktype = PENDING_LOCK;
30457     gotPendingLock = 0;
30458   }
30459
30460   /* Acquire an EXCLUSIVE lock
30461   */
30462   if( locktype==EXCLUSIVE_LOCK && res ){
30463     assert( pFile->locktype>=SHARED_LOCK );
30464     res = unlockReadLock(pFile);
30465     OSTRACE(("unreadlock = %d\n", res));
30466     res = LockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
30467     if( res ){
30468       newLocktype = EXCLUSIVE_LOCK;
30469     }else{
30470       error = GetLastError();
30471       OSTRACE(("error-code = %d\n", error));
30472       getReadLock(pFile);
30473     }
30474   }
30475
30476   /* If we are holding a PENDING lock that ought to be released, then
30477   ** release it now.
30478   */
30479   if( gotPendingLock && locktype==SHARED_LOCK ){
30480     UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
30481   }
30482
30483   /* Update the state of the lock has held in the file descriptor then
30484   ** return the appropriate result code.
30485   */
30486   if( res ){
30487     rc = SQLITE_OK;
30488   }else{
30489     OSTRACE(("LOCK FAILED %d trying for %d but got %d\n", pFile->h,
30490            locktype, newLocktype));
30491     pFile->lastErrno = error;
30492     rc = SQLITE_BUSY;
30493   }
30494   pFile->locktype = (u8)newLocktype;
30495   return rc;
30496 }
30497
30498 /*
30499 ** This routine checks if there is a RESERVED lock held on the specified
30500 ** file by this or any other process. If such a lock is held, return
30501 ** non-zero, otherwise zero.
30502 */
30503 static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
30504   int rc;
30505   winFile *pFile = (winFile*)id;
30506
30507   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
30508
30509   assert( id!=0 );
30510   if( pFile->locktype>=RESERVED_LOCK ){
30511     rc = 1;
30512     OSTRACE(("TEST WR-LOCK %d %d (local)\n", pFile->h, rc));
30513   }else{
30514     rc = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
30515     if( rc ){
30516       UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
30517     }
30518     rc = !rc;
30519     OSTRACE(("TEST WR-LOCK %d %d (remote)\n", pFile->h, rc));
30520   }
30521   *pResOut = rc;
30522   return SQLITE_OK;
30523 }
30524
30525 /*
30526 ** Lower the locking level on file descriptor id to locktype.  locktype
30527 ** must be either NO_LOCK or SHARED_LOCK.
30528 **
30529 ** If the locking level of the file descriptor is already at or below
30530 ** the requested locking level, this routine is a no-op.
30531 **
30532 ** It is not possible for this routine to fail if the second argument
30533 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
30534 ** might return SQLITE_IOERR;
30535 */
30536 static int winUnlock(sqlite3_file *id, int locktype){
30537   int type;
30538   winFile *pFile = (winFile*)id;
30539   int rc = SQLITE_OK;
30540   assert( pFile!=0 );
30541   assert( locktype<=SHARED_LOCK );
30542   OSTRACE(("UNLOCK %d to %d was %d(%d)\n", pFile->h, locktype,
30543           pFile->locktype, pFile->sharedLockByte));
30544   type = pFile->locktype;
30545   if( type>=EXCLUSIVE_LOCK ){
30546     UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
30547     if( locktype==SHARED_LOCK && !getReadLock(pFile) ){
30548       /* This should never happen.  We should always be able to
30549       ** reacquire the read lock */
30550       rc = SQLITE_IOERR_UNLOCK;
30551     }
30552   }
30553   if( type>=RESERVED_LOCK ){
30554     UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
30555   }
30556   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
30557     unlockReadLock(pFile);
30558   }
30559   if( type>=PENDING_LOCK ){
30560     UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
30561   }
30562   pFile->locktype = (u8)locktype;
30563   return rc;
30564 }
30565
30566 /*
30567 ** Control and query of the open file handle.
30568 */
30569 static int winFileControl(sqlite3_file *id, int op, void *pArg){
30570   switch( op ){
30571     case SQLITE_FCNTL_LOCKSTATE: {
30572       *(int*)pArg = ((winFile*)id)->locktype;
30573       return SQLITE_OK;
30574     }
30575     case SQLITE_LAST_ERRNO: {
30576       *(int*)pArg = (int)((winFile*)id)->lastErrno;
30577       return SQLITE_OK;
30578     }
30579     case SQLITE_FCNTL_CHUNK_SIZE: {
30580       ((winFile*)id)->szChunk = *(int *)pArg;
30581       return SQLITE_OK;
30582     }
30583     case SQLITE_FCNTL_SIZE_HINT: {
30584       sqlite3_int64 sz = *(sqlite3_int64*)pArg;
30585       SimulateIOErrorBenign(1);
30586       winTruncate(id, sz);
30587       SimulateIOErrorBenign(0);
30588       return SQLITE_OK;
30589     }
30590   }
30591   return SQLITE_ERROR;
30592 }
30593
30594 /*
30595 ** Return the sector size in bytes of the underlying block device for
30596 ** the specified file. This is almost always 512 bytes, but may be
30597 ** larger for some devices.
30598 **
30599 ** SQLite code assumes this function cannot fail. It also assumes that
30600 ** if two files are created in the same file-system directory (i.e.
30601 ** a database and its journal file) that the sector size will be the
30602 ** same for both.
30603 */
30604 static int winSectorSize(sqlite3_file *id){
30605   assert( id!=0 );
30606   return (int)(((winFile*)id)->sectorSize);
30607 }
30608
30609 /*
30610 ** Return a vector of device characteristics.
30611 */
30612 static int winDeviceCharacteristics(sqlite3_file *id){
30613   UNUSED_PARAMETER(id);
30614   return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN;
30615 }
30616
30617 #ifndef SQLITE_OMIT_WAL
30618
30619 /* 
30620 ** Windows will only let you create file view mappings
30621 ** on allocation size granularity boundaries.
30622 ** During sqlite3_os_init() we do a GetSystemInfo()
30623 ** to get the granularity size.
30624 */
30625 SYSTEM_INFO winSysInfo;
30626
30627 /*
30628 ** Helper functions to obtain and relinquish the global mutex. The
30629 ** global mutex is used to protect the winLockInfo objects used by 
30630 ** this file, all of which may be shared by multiple threads.
30631 **
30632 ** Function winShmMutexHeld() is used to assert() that the global mutex 
30633 ** is held when required. This function is only used as part of assert() 
30634 ** statements. e.g.
30635 **
30636 **   winShmEnterMutex()
30637 **     assert( winShmMutexHeld() );
30638 **   winShmLeaveMutex()
30639 */
30640 static void winShmEnterMutex(void){
30641   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
30642 }
30643 static void winShmLeaveMutex(void){
30644   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
30645 }
30646 #ifdef SQLITE_DEBUG
30647 static int winShmMutexHeld(void) {
30648   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
30649 }
30650 #endif
30651
30652 /*
30653 ** Object used to represent a single file opened and mmapped to provide
30654 ** shared memory.  When multiple threads all reference the same
30655 ** log-summary, each thread has its own winFile object, but they all
30656 ** point to a single instance of this object.  In other words, each
30657 ** log-summary is opened only once per process.
30658 **
30659 ** winShmMutexHeld() must be true when creating or destroying
30660 ** this object or while reading or writing the following fields:
30661 **
30662 **      nRef
30663 **      pNext 
30664 **
30665 ** The following fields are read-only after the object is created:
30666 ** 
30667 **      fid
30668 **      zFilename
30669 **
30670 ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
30671 ** winShmMutexHeld() is true when reading or writing any other field
30672 ** in this structure.
30673 **
30674 */
30675 struct winShmNode {
30676   sqlite3_mutex *mutex;      /* Mutex to access this object */
30677   char *zFilename;           /* Name of the file */
30678   winFile hFile;             /* File handle from winOpen */
30679
30680   int szRegion;              /* Size of shared-memory regions */
30681   int nRegion;               /* Size of array apRegion */
30682   struct ShmRegion {
30683     HANDLE hMap;             /* File handle from CreateFileMapping */
30684     void *pMap;
30685   } *aRegion;
30686   DWORD lastErrno;           /* The Windows errno from the last I/O error */
30687
30688   int nRef;                  /* Number of winShm objects pointing to this */
30689   winShm *pFirst;            /* All winShm objects pointing to this */
30690   winShmNode *pNext;         /* Next in list of all winShmNode objects */
30691 #ifdef SQLITE_DEBUG
30692   u8 nextShmId;              /* Next available winShm.id value */
30693 #endif
30694 };
30695
30696 /*
30697 ** A global array of all winShmNode objects.
30698 **
30699 ** The winShmMutexHeld() must be true while reading or writing this list.
30700 */
30701 static winShmNode *winShmNodeList = 0;
30702
30703 /*
30704 ** Structure used internally by this VFS to record the state of an
30705 ** open shared memory connection.
30706 **
30707 ** The following fields are initialized when this object is created and
30708 ** are read-only thereafter:
30709 **
30710 **    winShm.pShmNode
30711 **    winShm.id
30712 **
30713 ** All other fields are read/write.  The winShm.pShmNode->mutex must be held
30714 ** while accessing any read/write fields.
30715 */
30716 struct winShm {
30717   winShmNode *pShmNode;      /* The underlying winShmNode object */
30718   winShm *pNext;             /* Next winShm with the same winShmNode */
30719   u8 hasMutex;               /* True if holding the winShmNode mutex */
30720   u16 sharedMask;            /* Mask of shared locks held */
30721   u16 exclMask;              /* Mask of exclusive locks held */
30722 #ifdef SQLITE_DEBUG
30723   u8 id;                     /* Id of this connection with its winShmNode */
30724 #endif
30725 };
30726
30727 /*
30728 ** Constants used for locking
30729 */
30730 #define WIN_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)        /* first lock byte */
30731 #define WIN_SHM_DMS    (WIN_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
30732
30733 /*
30734 ** Apply advisory locks for all n bytes beginning at ofst.
30735 */
30736 #define _SHM_UNLCK  1
30737 #define _SHM_RDLCK  2
30738 #define _SHM_WRLCK  3
30739 static int winShmSystemLock(
30740   winShmNode *pFile,    /* Apply locks to this open shared-memory segment */
30741   int lockType,         /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */
30742   int ofst,             /* Offset to first byte to be locked/unlocked */
30743   int nByte             /* Number of bytes to lock or unlock */
30744 ){
30745   OVERLAPPED ovlp;
30746   DWORD dwFlags;
30747   int rc = 0;           /* Result code form Lock/UnlockFileEx() */
30748
30749   /* Access to the winShmNode object is serialized by the caller */
30750   assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
30751
30752   /* Initialize the locking parameters */
30753   dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
30754   if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
30755
30756   memset(&ovlp, 0, sizeof(OVERLAPPED));
30757   ovlp.Offset = ofst;
30758
30759   /* Release/Acquire the system-level lock */
30760   if( lockType==_SHM_UNLCK ){
30761     rc = UnlockFileEx(pFile->hFile.h, 0, nByte, 0, &ovlp);
30762   }else{
30763     rc = LockFileEx(pFile->hFile.h, dwFlags, 0, nByte, 0, &ovlp);
30764   }
30765   
30766   if( rc!= 0 ){
30767     rc = SQLITE_OK;
30768   }else{
30769     pFile->lastErrno =  GetLastError();
30770     rc = SQLITE_BUSY;
30771   }
30772
30773   OSTRACE(("SHM-LOCK %d %s %s 0x%08lx\n", 
30774            pFile->hFile.h,
30775            rc==SQLITE_OK ? "ok" : "failed",
30776            lockType==_SHM_UNLCK ? "UnlockFileEx" : "LockFileEx",
30777            pFile->lastErrno));
30778
30779   return rc;
30780 }
30781
30782 /* Forward references to VFS methods */
30783 static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
30784 static int winDelete(sqlite3_vfs *,const char*,int);
30785
30786 /*
30787 ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
30788 **
30789 ** This is not a VFS shared-memory method; it is a utility function called
30790 ** by VFS shared-memory methods.
30791 */
30792 static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
30793   winShmNode **pp;
30794   winShmNode *p;
30795   BOOL bRc;
30796   assert( winShmMutexHeld() );
30797   pp = &winShmNodeList;
30798   while( (p = *pp)!=0 ){
30799     if( p->nRef==0 ){
30800       int i;
30801       if( p->mutex ) sqlite3_mutex_free(p->mutex);
30802       for(i=0; i<p->nRegion; i++){
30803         bRc = UnmapViewOfFile(p->aRegion[i].pMap);
30804         OSTRACE(("SHM-PURGE pid-%d unmap region=%d %s\n",
30805                  (int)GetCurrentProcessId(), i,
30806                  bRc ? "ok" : "failed"));
30807         bRc = CloseHandle(p->aRegion[i].hMap);
30808         OSTRACE(("SHM-PURGE pid-%d close region=%d %s\n",
30809                  (int)GetCurrentProcessId(), i,
30810                  bRc ? "ok" : "failed"));
30811       }
30812       if( p->hFile.h != INVALID_HANDLE_VALUE ){
30813         SimulateIOErrorBenign(1);
30814         winClose((sqlite3_file *)&p->hFile);
30815         SimulateIOErrorBenign(0);
30816       }
30817       if( deleteFlag ){
30818         SimulateIOErrorBenign(1);
30819         winDelete(pVfs, p->zFilename, 0);
30820         SimulateIOErrorBenign(0);
30821       }
30822       *pp = p->pNext;
30823       sqlite3_free(p->aRegion);
30824       sqlite3_free(p);
30825     }else{
30826       pp = &p->pNext;
30827     }
30828   }
30829 }
30830
30831 /*
30832 ** Open the shared-memory area associated with database file pDbFd.
30833 **
30834 ** When opening a new shared-memory file, if no other instances of that
30835 ** file are currently open, in this process or in other processes, then
30836 ** the file must be truncated to zero length or have its header cleared.
30837 */
30838 static int winOpenSharedMemory(winFile *pDbFd){
30839   struct winShm *p;                  /* The connection to be opened */
30840   struct winShmNode *pShmNode = 0;   /* The underlying mmapped file */
30841   int rc;                            /* Result code */
30842   struct winShmNode *pNew;           /* Newly allocated winShmNode */
30843   int nName;                         /* Size of zName in bytes */
30844
30845   assert( pDbFd->pShm==0 );    /* Not previously opened */
30846
30847   /* Allocate space for the new sqlite3_shm object.  Also speculatively
30848   ** allocate space for a new winShmNode and filename.
30849   */
30850   p = sqlite3_malloc( sizeof(*p) );
30851   if( p==0 ) return SQLITE_NOMEM;
30852   memset(p, 0, sizeof(*p));
30853   nName = sqlite3Strlen30(pDbFd->zPath);
30854   pNew = sqlite3_malloc( sizeof(*pShmNode) + nName + 15 );
30855   if( pNew==0 ){
30856     sqlite3_free(p);
30857     return SQLITE_NOMEM;
30858   }
30859   memset(pNew, 0, sizeof(*pNew));
30860   pNew->zFilename = (char*)&pNew[1];
30861   sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
30862
30863   /* Look to see if there is an existing winShmNode that can be used.
30864   ** If no matching winShmNode currently exists, create a new one.
30865   */
30866   winShmEnterMutex();
30867   for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
30868     /* TBD need to come up with better match here.  Perhaps
30869     ** use FILE_ID_BOTH_DIR_INFO Structure.
30870     */
30871     if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
30872   }
30873   if( pShmNode ){
30874     sqlite3_free(pNew);
30875   }else{
30876     pShmNode = pNew;
30877     pNew = 0;
30878     ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
30879     pShmNode->pNext = winShmNodeList;
30880     winShmNodeList = pShmNode;
30881
30882     pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
30883     if( pShmNode->mutex==0 ){
30884       rc = SQLITE_NOMEM;
30885       goto shm_open_err;
30886     }
30887
30888     rc = winOpen(pDbFd->pVfs,
30889                  pShmNode->zFilename,             /* Name of the file (UTF-8) */
30890                  (sqlite3_file*)&pShmNode->hFile,  /* File handle here */
30891                  SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, /* Mode flags */
30892                  0);
30893     if( SQLITE_OK!=rc ){
30894       rc = SQLITE_CANTOPEN_BKPT;
30895       goto shm_open_err;
30896     }
30897
30898     /* Check to see if another process is holding the dead-man switch.
30899     ** If not, truncate the file to zero length. 
30900     */
30901     if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
30902       rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
30903       if( rc!=SQLITE_OK ){
30904         rc = SQLITE_IOERR_SHMOPEN;
30905       }
30906     }
30907     if( rc==SQLITE_OK ){
30908       winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
30909       rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
30910     }
30911     if( rc ) goto shm_open_err;
30912   }
30913
30914   /* Make the new connection a child of the winShmNode */
30915   p->pShmNode = pShmNode;
30916 #ifdef SQLITE_DEBUG
30917   p->id = pShmNode->nextShmId++;
30918 #endif
30919   pShmNode->nRef++;
30920   pDbFd->pShm = p;
30921   winShmLeaveMutex();
30922
30923   /* The reference count on pShmNode has already been incremented under
30924   ** the cover of the winShmEnterMutex() mutex and the pointer from the
30925   ** new (struct winShm) object to the pShmNode has been set. All that is
30926   ** left to do is to link the new object into the linked list starting
30927   ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex 
30928   ** mutex.
30929   */
30930   sqlite3_mutex_enter(pShmNode->mutex);
30931   p->pNext = pShmNode->pFirst;
30932   pShmNode->pFirst = p;
30933   sqlite3_mutex_leave(pShmNode->mutex);
30934   return SQLITE_OK;
30935
30936   /* Jump here on any error */
30937 shm_open_err:
30938   winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
30939   winShmPurge(pDbFd->pVfs, 0);      /* This call frees pShmNode if required */
30940   sqlite3_free(p);
30941   sqlite3_free(pNew);
30942   winShmLeaveMutex();
30943   return rc;
30944 }
30945
30946 /*
30947 ** Close a connection to shared-memory.  Delete the underlying 
30948 ** storage if deleteFlag is true.
30949 */
30950 static int winShmUnmap(
30951   sqlite3_file *fd,          /* Database holding shared memory */
30952   int deleteFlag             /* Delete after closing if true */
30953 ){
30954   winFile *pDbFd;       /* Database holding shared-memory */
30955   winShm *p;            /* The connection to be closed */
30956   winShmNode *pShmNode; /* The underlying shared-memory file */
30957   winShm **pp;          /* For looping over sibling connections */
30958
30959   pDbFd = (winFile*)fd;
30960   p = pDbFd->pShm;
30961   if( p==0 ) return SQLITE_OK;
30962   pShmNode = p->pShmNode;
30963
30964   /* Remove connection p from the set of connections associated
30965   ** with pShmNode */
30966   sqlite3_mutex_enter(pShmNode->mutex);
30967   for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
30968   *pp = p->pNext;
30969
30970   /* Free the connection p */
30971   sqlite3_free(p);
30972   pDbFd->pShm = 0;
30973   sqlite3_mutex_leave(pShmNode->mutex);
30974
30975   /* If pShmNode->nRef has reached 0, then close the underlying
30976   ** shared-memory file, too */
30977   winShmEnterMutex();
30978   assert( pShmNode->nRef>0 );
30979   pShmNode->nRef--;
30980   if( pShmNode->nRef==0 ){
30981     winShmPurge(pDbFd->pVfs, deleteFlag);
30982   }
30983   winShmLeaveMutex();
30984
30985   return SQLITE_OK;
30986 }
30987
30988 /*
30989 ** Change the lock state for a shared-memory segment.
30990 */
30991 static int winShmLock(
30992   sqlite3_file *fd,          /* Database file holding the shared memory */
30993   int ofst,                  /* First lock to acquire or release */
30994   int n,                     /* Number of locks to acquire or release */
30995   int flags                  /* What to do with the lock */
30996 ){
30997   winFile *pDbFd = (winFile*)fd;        /* Connection holding shared memory */
30998   winShm *p = pDbFd->pShm;              /* The shared memory being locked */
30999   winShm *pX;                           /* For looping over all siblings */
31000   winShmNode *pShmNode = p->pShmNode;
31001   int rc = SQLITE_OK;                   /* Result code */
31002   u16 mask;                             /* Mask of locks to take or release */
31003
31004   assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
31005   assert( n>=1 );
31006   assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
31007        || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
31008        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
31009        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
31010   assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
31011
31012   mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
31013   assert( n>1 || mask==(1<<ofst) );
31014   sqlite3_mutex_enter(pShmNode->mutex);
31015   if( flags & SQLITE_SHM_UNLOCK ){
31016     u16 allMask = 0; /* Mask of locks held by siblings */
31017
31018     /* See if any siblings hold this same lock */
31019     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
31020       if( pX==p ) continue;
31021       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
31022       allMask |= pX->sharedMask;
31023     }
31024
31025     /* Unlock the system-level locks */
31026     if( (mask & allMask)==0 ){
31027       rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);
31028     }else{
31029       rc = SQLITE_OK;
31030     }
31031
31032     /* Undo the local locks */
31033     if( rc==SQLITE_OK ){
31034       p->exclMask &= ~mask;
31035       p->sharedMask &= ~mask;
31036     } 
31037   }else if( flags & SQLITE_SHM_SHARED ){
31038     u16 allShared = 0;  /* Union of locks held by connections other than "p" */
31039
31040     /* Find out which shared locks are already held by sibling connections.
31041     ** If any sibling already holds an exclusive lock, go ahead and return
31042     ** SQLITE_BUSY.
31043     */
31044     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
31045       if( (pX->exclMask & mask)!=0 ){
31046         rc = SQLITE_BUSY;
31047         break;
31048       }
31049       allShared |= pX->sharedMask;
31050     }
31051
31052     /* Get shared locks at the system level, if necessary */
31053     if( rc==SQLITE_OK ){
31054       if( (allShared & mask)==0 ){
31055         rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);
31056       }else{
31057         rc = SQLITE_OK;
31058       }
31059     }
31060
31061     /* Get the local shared locks */
31062     if( rc==SQLITE_OK ){
31063       p->sharedMask |= mask;
31064     }
31065   }else{
31066     /* Make sure no sibling connections hold locks that will block this
31067     ** lock.  If any do, return SQLITE_BUSY right away.
31068     */
31069     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
31070       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
31071         rc = SQLITE_BUSY;
31072         break;
31073       }
31074     }
31075   
31076     /* Get the exclusive locks at the system level.  Then if successful
31077     ** also mark the local connection as being locked.
31078     */
31079     if( rc==SQLITE_OK ){
31080       rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
31081       if( rc==SQLITE_OK ){
31082         assert( (p->sharedMask & mask)==0 );
31083         p->exclMask |= mask;
31084       }
31085     }
31086   }
31087   sqlite3_mutex_leave(pShmNode->mutex);
31088   OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x %s\n",
31089            p->id, (int)GetCurrentProcessId(), p->sharedMask, p->exclMask,
31090            rc ? "failed" : "ok"));
31091   return rc;
31092 }
31093
31094 /*
31095 ** Implement a memory barrier or memory fence on shared memory.  
31096 **
31097 ** All loads and stores begun before the barrier must complete before
31098 ** any load or store begun after the barrier.
31099 */
31100 static void winShmBarrier(
31101   sqlite3_file *fd          /* Database holding the shared memory */
31102 ){
31103   UNUSED_PARAMETER(fd);
31104   /* MemoryBarrier(); // does not work -- do not know why not */
31105   winShmEnterMutex();
31106   winShmLeaveMutex();
31107 }
31108
31109 /*
31110 ** This function is called to obtain a pointer to region iRegion of the 
31111 ** shared-memory associated with the database file fd. Shared-memory regions 
31112 ** are numbered starting from zero. Each shared-memory region is szRegion 
31113 ** bytes in size.
31114 **
31115 ** If an error occurs, an error code is returned and *pp is set to NULL.
31116 **
31117 ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
31118 ** region has not been allocated (by any client, including one running in a
31119 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If 
31120 ** isWrite is non-zero and the requested shared-memory region has not yet 
31121 ** been allocated, it is allocated by this function.
31122 **
31123 ** If the shared-memory region has already been allocated or is allocated by
31124 ** this call as described above, then it is mapped into this processes 
31125 ** address space (if it is not already), *pp is set to point to the mapped 
31126 ** memory and SQLITE_OK returned.
31127 */
31128 static int winShmMap(
31129   sqlite3_file *fd,               /* Handle open on database file */
31130   int iRegion,                    /* Region to retrieve */
31131   int szRegion,                   /* Size of regions */
31132   int isWrite,                    /* True to extend file if necessary */
31133   void volatile **pp              /* OUT: Mapped memory */
31134 ){
31135   winFile *pDbFd = (winFile*)fd;
31136   winShm *p = pDbFd->pShm;
31137   winShmNode *pShmNode;
31138   int rc = SQLITE_OK;
31139
31140   if( !p ){
31141     rc = winOpenSharedMemory(pDbFd);
31142     if( rc!=SQLITE_OK ) return rc;
31143     p = pDbFd->pShm;
31144   }
31145   pShmNode = p->pShmNode;
31146
31147   sqlite3_mutex_enter(pShmNode->mutex);
31148   assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
31149
31150   if( pShmNode->nRegion<=iRegion ){
31151     struct ShmRegion *apNew;           /* New aRegion[] array */
31152     int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
31153     sqlite3_int64 sz;                  /* Current size of wal-index file */
31154
31155     pShmNode->szRegion = szRegion;
31156
31157     /* The requested region is not mapped into this processes address space.
31158     ** Check to see if it has been allocated (i.e. if the wal-index file is
31159     ** large enough to contain the requested region).
31160     */
31161     rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
31162     if( rc!=SQLITE_OK ){
31163       rc = SQLITE_IOERR_SHMSIZE;
31164       goto shmpage_out;
31165     }
31166
31167     if( sz<nByte ){
31168       /* The requested memory region does not exist. If isWrite is set to
31169       ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
31170       **
31171       ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
31172       ** the requested memory region.
31173       */
31174       if( !isWrite ) goto shmpage_out;
31175       rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
31176       if( rc!=SQLITE_OK ){
31177         rc = SQLITE_IOERR_SHMSIZE;
31178         goto shmpage_out;
31179       }
31180     }
31181
31182     /* Map the requested memory region into this processes address space. */
31183     apNew = (struct ShmRegion *)sqlite3_realloc(
31184         pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
31185     );
31186     if( !apNew ){
31187       rc = SQLITE_IOERR_NOMEM;
31188       goto shmpage_out;
31189     }
31190     pShmNode->aRegion = apNew;
31191
31192     while( pShmNode->nRegion<=iRegion ){
31193       HANDLE hMap;                /* file-mapping handle */
31194       void *pMap = 0;             /* Mapped memory region */
31195      
31196       hMap = CreateFileMapping(pShmNode->hFile.h, 
31197           NULL, PAGE_READWRITE, 0, nByte, NULL
31198       );
31199       OSTRACE(("SHM-MAP pid-%d create region=%d nbyte=%d %s\n",
31200                (int)GetCurrentProcessId(), pShmNode->nRegion, nByte,
31201                hMap ? "ok" : "failed"));
31202       if( hMap ){
31203         int iOffset = pShmNode->nRegion*szRegion;
31204         int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
31205         pMap = MapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
31206             0, iOffset - iOffsetShift, szRegion + iOffsetShift
31207         );
31208         OSTRACE(("SHM-MAP pid-%d map region=%d offset=%d size=%d %s\n",
31209                  (int)GetCurrentProcessId(), pShmNode->nRegion, iOffset, szRegion,
31210                  pMap ? "ok" : "failed"));
31211       }
31212       if( !pMap ){
31213         pShmNode->lastErrno = GetLastError();
31214         rc = SQLITE_IOERR;
31215         if( hMap ) CloseHandle(hMap);
31216         goto shmpage_out;
31217       }
31218
31219       pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
31220       pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
31221       pShmNode->nRegion++;
31222     }
31223   }
31224
31225 shmpage_out:
31226   if( pShmNode->nRegion>iRegion ){
31227     int iOffset = iRegion*szRegion;
31228     int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
31229     char *p = (char *)pShmNode->aRegion[iRegion].pMap;
31230     *pp = (void *)&p[iOffsetShift];
31231   }else{
31232     *pp = 0;
31233   }
31234   sqlite3_mutex_leave(pShmNode->mutex);
31235   return rc;
31236 }
31237
31238 #else
31239 # define winShmMap     0
31240 # define winShmLock    0
31241 # define winShmBarrier 0
31242 # define winShmUnmap   0
31243 #endif /* #ifndef SQLITE_OMIT_WAL */
31244
31245 /*
31246 ** Here ends the implementation of all sqlite3_file methods.
31247 **
31248 ********************** End sqlite3_file Methods *******************************
31249 ******************************************************************************/
31250
31251 /*
31252 ** This vector defines all the methods that can operate on an
31253 ** sqlite3_file for win32.
31254 */
31255 static const sqlite3_io_methods winIoMethod = {
31256   2,                              /* iVersion */
31257   winClose,                       /* xClose */
31258   winRead,                        /* xRead */
31259   winWrite,                       /* xWrite */
31260   winTruncate,                    /* xTruncate */
31261   winSync,                        /* xSync */
31262   winFileSize,                    /* xFileSize */
31263   winLock,                        /* xLock */
31264   winUnlock,                      /* xUnlock */
31265   winCheckReservedLock,           /* xCheckReservedLock */
31266   winFileControl,                 /* xFileControl */
31267   winSectorSize,                  /* xSectorSize */
31268   winDeviceCharacteristics,       /* xDeviceCharacteristics */
31269   winShmMap,                      /* xShmMap */
31270   winShmLock,                     /* xShmLock */
31271   winShmBarrier,                  /* xShmBarrier */
31272   winShmUnmap                     /* xShmUnmap */
31273 };
31274
31275 /****************************************************************************
31276 **************************** sqlite3_vfs methods ****************************
31277 **
31278 ** This division contains the implementation of methods on the
31279 ** sqlite3_vfs object.
31280 */
31281
31282 /*
31283 ** Convert a UTF-8 filename into whatever form the underlying
31284 ** operating system wants filenames in.  Space to hold the result
31285 ** is obtained from malloc and must be freed by the calling
31286 ** function.
31287 */
31288 static void *convertUtf8Filename(const char *zFilename){
31289   void *zConverted = 0;
31290   if( isNT() ){
31291     zConverted = utf8ToUnicode(zFilename);
31292 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
31293 */
31294 #if SQLITE_OS_WINCE==0
31295   }else{
31296     zConverted = utf8ToMbcs(zFilename);
31297 #endif
31298   }
31299   /* caller will handle out of memory */
31300   return zConverted;
31301 }
31302
31303 /*
31304 ** Create a temporary file name in zBuf.  zBuf must be big enough to
31305 ** hold at pVfs->mxPathname characters.
31306 */
31307 static int getTempname(int nBuf, char *zBuf){
31308   static char zChars[] =
31309     "abcdefghijklmnopqrstuvwxyz"
31310     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
31311     "0123456789";
31312   size_t i, j;
31313   char zTempPath[MAX_PATH+1];
31314
31315   /* It's odd to simulate an io-error here, but really this is just
31316   ** using the io-error infrastructure to test that SQLite handles this
31317   ** function failing. 
31318   */
31319   SimulateIOError( return SQLITE_IOERR );
31320
31321   if( sqlite3_temp_directory ){
31322     sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlite3_temp_directory);
31323   }else if( isNT() ){
31324     char *zMulti;
31325     WCHAR zWidePath[MAX_PATH];
31326     GetTempPathW(MAX_PATH-30, zWidePath);
31327     zMulti = unicodeToUtf8(zWidePath);
31328     if( zMulti ){
31329       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zMulti);
31330       free(zMulti);
31331     }else{
31332       return SQLITE_NOMEM;
31333     }
31334 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
31335 ** Since the ASCII version of these Windows API do not exist for WINCE,
31336 ** it's important to not reference them for WINCE builds.
31337 */
31338 #if SQLITE_OS_WINCE==0
31339   }else{
31340     char *zUtf8;
31341     char zMbcsPath[MAX_PATH];
31342     GetTempPathA(MAX_PATH-30, zMbcsPath);
31343     zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
31344     if( zUtf8 ){
31345       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zUtf8);
31346       free(zUtf8);
31347     }else{
31348       return SQLITE_NOMEM;
31349     }
31350 #endif
31351   }
31352
31353   /* Check that the output buffer is large enough for the temporary file 
31354   ** name. If it is not, return SQLITE_ERROR.
31355   */
31356   if( (sqlite3Strlen30(zTempPath) + sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX) + 17) >= nBuf ){
31357     return SQLITE_ERROR;
31358   }
31359
31360   for(i=sqlite3Strlen30(zTempPath); i>0 && zTempPath[i-1]=='\\'; i--){}
31361   zTempPath[i] = 0;
31362
31363   sqlite3_snprintf(nBuf-17, zBuf,
31364                    "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath);
31365   j = sqlite3Strlen30(zBuf);
31366   sqlite3_randomness(15, &zBuf[j]);
31367   for(i=0; i<15; i++, j++){
31368     zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
31369   }
31370   zBuf[j] = 0;
31371
31372   OSTRACE(("TEMP FILENAME: %s\n", zBuf));
31373   return SQLITE_OK; 
31374 }
31375
31376 /*
31377 ** The return value of getLastErrorMsg
31378 ** is zero if the error message fits in the buffer, or non-zero
31379 ** otherwise (if the message was truncated).
31380 */
31381 static int getLastErrorMsg(int nBuf, char *zBuf){
31382   /* FormatMessage returns 0 on failure.  Otherwise it
31383   ** returns the number of TCHARs written to the output
31384   ** buffer, excluding the terminating null char.
31385   */
31386   DWORD error = GetLastError();
31387   DWORD dwLen = 0;
31388   char *zOut = 0;
31389
31390   if( isNT() ){
31391     WCHAR *zTempWide = NULL;
31392     dwLen = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
31393                            NULL,
31394                            error,
31395                            0,
31396                            (LPWSTR) &zTempWide,
31397                            0,
31398                            0);
31399     if( dwLen > 0 ){
31400       /* allocate a buffer and convert to UTF8 */
31401       zOut = unicodeToUtf8(zTempWide);
31402       /* free the system buffer allocated by FormatMessage */
31403       LocalFree(zTempWide);
31404     }
31405 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
31406 ** Since the ASCII version of these Windows API do not exist for WINCE,
31407 ** it's important to not reference them for WINCE builds.
31408 */
31409 #if SQLITE_OS_WINCE==0
31410   }else{
31411     char *zTemp = NULL;
31412     dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
31413                            NULL,
31414                            error,
31415                            0,
31416                            (LPSTR) &zTemp,
31417                            0,
31418                            0);
31419     if( dwLen > 0 ){
31420       /* allocate a buffer and convert to UTF8 */
31421       zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
31422       /* free the system buffer allocated by FormatMessage */
31423       LocalFree(zTemp);
31424     }
31425 #endif
31426   }
31427   if( 0 == dwLen ){
31428     sqlite3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", error, error);
31429   }else{
31430     /* copy a maximum of nBuf chars to output buffer */
31431     sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
31432     /* free the UTF8 buffer */
31433     free(zOut);
31434   }
31435   return 0;
31436 }
31437
31438 /*
31439 ** Open a file.
31440 */
31441 static int winOpen(
31442   sqlite3_vfs *pVfs,        /* Not used */
31443   const char *zName,        /* Name of the file (UTF-8) */
31444   sqlite3_file *id,         /* Write the SQLite file handle here */
31445   int flags,                /* Open mode flags */
31446   int *pOutFlags            /* Status return flags */
31447 ){
31448   HANDLE h;
31449   DWORD dwDesiredAccess;
31450   DWORD dwShareMode;
31451   DWORD dwCreationDisposition;
31452   DWORD dwFlagsAndAttributes = 0;
31453 #if SQLITE_OS_WINCE
31454   int isTemp = 0;
31455 #endif
31456   winFile *pFile = (winFile*)id;
31457   void *zConverted;              /* Filename in OS encoding */
31458   const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
31459
31460   /* If argument zPath is a NULL pointer, this function is required to open
31461   ** a temporary file. Use this buffer to store the file name in.
31462   */
31463   char zTmpname[MAX_PATH+1];     /* Buffer used to create temp filename */
31464
31465   int rc = SQLITE_OK;            /* Function Return Code */
31466 #if !defined(NDEBUG) || SQLITE_OS_WINCE
31467   int eType = flags&0xFFFFFF00;  /* Type of file to open */
31468 #endif
31469
31470   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
31471   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
31472   int isCreate     = (flags & SQLITE_OPEN_CREATE);
31473 #ifndef NDEBUG
31474   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
31475 #endif
31476   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
31477
31478 #ifndef NDEBUG
31479   int isOpenJournal = (isCreate && (
31480         eType==SQLITE_OPEN_MASTER_JOURNAL 
31481      || eType==SQLITE_OPEN_MAIN_JOURNAL 
31482      || eType==SQLITE_OPEN_WAL
31483   ));
31484 #endif
31485
31486   /* Check the following statements are true: 
31487   **
31488   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and 
31489   **   (b) if CREATE is set, then READWRITE must also be set, and
31490   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
31491   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
31492   */
31493   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
31494   assert(isCreate==0 || isReadWrite);
31495   assert(isExclusive==0 || isCreate);
31496   assert(isDelete==0 || isCreate);
31497
31498   /* The main DB, main journal, WAL file and master journal are never 
31499   ** automatically deleted. Nor are they ever temporary files.  */
31500   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
31501   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
31502   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
31503   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
31504
31505   /* Assert that the upper layer has set one of the "file-type" flags. */
31506   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB 
31507        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL 
31508        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL 
31509        || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
31510   );
31511
31512   assert( id!=0 );
31513   UNUSED_PARAMETER(pVfs);
31514
31515   pFile->h = INVALID_HANDLE_VALUE;
31516
31517   /* If the second argument to this function is NULL, generate a 
31518   ** temporary file name to use 
31519   */
31520   if( !zUtf8Name ){
31521     assert(isDelete && !isOpenJournal);
31522     rc = getTempname(MAX_PATH+1, zTmpname);
31523     if( rc!=SQLITE_OK ){
31524       return rc;
31525     }
31526     zUtf8Name = zTmpname;
31527   }
31528
31529   /* Convert the filename to the system encoding. */
31530   zConverted = convertUtf8Filename(zUtf8Name);
31531   if( zConverted==0 ){
31532     return SQLITE_NOMEM;
31533   }
31534
31535   if( isReadWrite ){
31536     dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
31537   }else{
31538     dwDesiredAccess = GENERIC_READ;
31539   }
31540
31541   /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is 
31542   ** created. SQLite doesn't use it to indicate "exclusive access" 
31543   ** as it is usually understood.
31544   */
31545   if( isExclusive ){
31546     /* Creates a new file, only if it does not already exist. */
31547     /* If the file exists, it fails. */
31548     dwCreationDisposition = CREATE_NEW;
31549   }else if( isCreate ){
31550     /* Open existing file, or create if it doesn't exist */
31551     dwCreationDisposition = OPEN_ALWAYS;
31552   }else{
31553     /* Opens a file, only if it exists. */
31554     dwCreationDisposition = OPEN_EXISTING;
31555   }
31556
31557   dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
31558
31559   if( isDelete ){
31560 #if SQLITE_OS_WINCE
31561     dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
31562     isTemp = 1;
31563 #else
31564     dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
31565                                | FILE_ATTRIBUTE_HIDDEN
31566                                | FILE_FLAG_DELETE_ON_CLOSE;
31567 #endif
31568   }else{
31569     dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
31570   }
31571   /* Reports from the internet are that performance is always
31572   ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
31573 #if SQLITE_OS_WINCE
31574   dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
31575 #endif
31576
31577   if( isNT() ){
31578     h = CreateFileW((WCHAR*)zConverted,
31579        dwDesiredAccess,
31580        dwShareMode,
31581        NULL,
31582        dwCreationDisposition,
31583        dwFlagsAndAttributes,
31584        NULL
31585     );
31586 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
31587 ** Since the ASCII version of these Windows API do not exist for WINCE,
31588 ** it's important to not reference them for WINCE builds.
31589 */
31590 #if SQLITE_OS_WINCE==0
31591   }else{
31592     h = CreateFileA((char*)zConverted,
31593        dwDesiredAccess,
31594        dwShareMode,
31595        NULL,
31596        dwCreationDisposition,
31597        dwFlagsAndAttributes,
31598        NULL
31599     );
31600 #endif
31601   }
31602
31603   OSTRACE(("OPEN %d %s 0x%lx %s\n", 
31604            h, zName, dwDesiredAccess, 
31605            h==INVALID_HANDLE_VALUE ? "failed" : "ok"));
31606
31607   if( h==INVALID_HANDLE_VALUE ){
31608     pFile->lastErrno = GetLastError();
31609     free(zConverted);
31610     if( isReadWrite ){
31611       return winOpen(pVfs, zName, id, 
31612              ((flags|SQLITE_OPEN_READONLY)&~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)), pOutFlags);
31613     }else{
31614       return SQLITE_CANTOPEN_BKPT;
31615     }
31616   }
31617
31618   if( pOutFlags ){
31619     if( isReadWrite ){
31620       *pOutFlags = SQLITE_OPEN_READWRITE;
31621     }else{
31622       *pOutFlags = SQLITE_OPEN_READONLY;
31623     }
31624   }
31625
31626   memset(pFile, 0, sizeof(*pFile));
31627   pFile->pMethod = &winIoMethod;
31628   pFile->h = h;
31629   pFile->lastErrno = NO_ERROR;
31630   pFile->pVfs = pVfs;
31631   pFile->pShm = 0;
31632   pFile->zPath = zName;
31633   pFile->sectorSize = getSectorSize(pVfs, zUtf8Name);
31634
31635 #if SQLITE_OS_WINCE
31636   if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
31637        && !winceCreateLock(zName, pFile)
31638   ){
31639     CloseHandle(h);
31640     free(zConverted);
31641     return SQLITE_CANTOPEN_BKPT;
31642   }
31643   if( isTemp ){
31644     pFile->zDeleteOnClose = zConverted;
31645   }else
31646 #endif
31647   {
31648     free(zConverted);
31649   }
31650
31651   OpenCounter(+1);
31652   return rc;
31653 }
31654
31655 /*
31656 ** Delete the named file.
31657 **
31658 ** Note that windows does not allow a file to be deleted if some other
31659 ** process has it open.  Sometimes a virus scanner or indexing program
31660 ** will open a journal file shortly after it is created in order to do
31661 ** whatever it does.  While this other process is holding the
31662 ** file open, we will be unable to delete it.  To work around this
31663 ** problem, we delay 100 milliseconds and try to delete again.  Up
31664 ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
31665 ** up and returning an error.
31666 */
31667 #define MX_DELETION_ATTEMPTS 5
31668 static int winDelete(
31669   sqlite3_vfs *pVfs,          /* Not used on win32 */
31670   const char *zFilename,      /* Name of file to delete */
31671   int syncDir                 /* Not used on win32 */
31672 ){
31673   int cnt = 0;
31674   DWORD rc;
31675   DWORD error = 0;
31676   void *zConverted;
31677   UNUSED_PARAMETER(pVfs);
31678   UNUSED_PARAMETER(syncDir);
31679
31680   SimulateIOError(return SQLITE_IOERR_DELETE);
31681   zConverted = convertUtf8Filename(zFilename);
31682   if( zConverted==0 ){
31683     return SQLITE_NOMEM;
31684   }
31685   if( isNT() ){
31686     do{
31687       DeleteFileW(zConverted);
31688     }while(   (   ((rc = GetFileAttributesW(zConverted)) != INVALID_FILE_ATTRIBUTES)
31689                || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
31690            && (++cnt < MX_DELETION_ATTEMPTS)
31691            && (Sleep(100), 1) );
31692 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
31693 ** Since the ASCII version of these Windows API do not exist for WINCE,
31694 ** it's important to not reference them for WINCE builds.
31695 */
31696 #if SQLITE_OS_WINCE==0
31697   }else{
31698     do{
31699       DeleteFileA(zConverted);
31700     }while(   (   ((rc = GetFileAttributesA(zConverted)) != INVALID_FILE_ATTRIBUTES)
31701                || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
31702            && (++cnt < MX_DELETION_ATTEMPTS)
31703            && (Sleep(100), 1) );
31704 #endif
31705   }
31706   free(zConverted);
31707   OSTRACE(("DELETE \"%s\" %s\n", zFilename,
31708        ( (rc==INVALID_FILE_ATTRIBUTES) && (error==ERROR_FILE_NOT_FOUND)) ?
31709          "ok" : "failed" ));
31710  
31711   return (   (rc == INVALID_FILE_ATTRIBUTES) 
31712           && (error == ERROR_FILE_NOT_FOUND)) ? SQLITE_OK : SQLITE_IOERR_DELETE;
31713 }
31714
31715 /*
31716 ** Check the existance and status of a file.
31717 */
31718 static int winAccess(
31719   sqlite3_vfs *pVfs,         /* Not used on win32 */
31720   const char *zFilename,     /* Name of file to check */
31721   int flags,                 /* Type of test to make on this file */
31722   int *pResOut               /* OUT: Result */
31723 ){
31724   DWORD attr;
31725   int rc = 0;
31726   void *zConverted;
31727   UNUSED_PARAMETER(pVfs);
31728
31729   SimulateIOError( return SQLITE_IOERR_ACCESS; );
31730   zConverted = convertUtf8Filename(zFilename);
31731   if( zConverted==0 ){
31732     return SQLITE_NOMEM;
31733   }
31734   if( isNT() ){
31735     WIN32_FILE_ATTRIBUTE_DATA sAttrData;
31736     memset(&sAttrData, 0, sizeof(sAttrData));
31737     if( GetFileAttributesExW((WCHAR*)zConverted,
31738                              GetFileExInfoStandard, 
31739                              &sAttrData) ){
31740       /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
31741       ** as if it does not exist.
31742       */
31743       if(    flags==SQLITE_ACCESS_EXISTS
31744           && sAttrData.nFileSizeHigh==0 
31745           && sAttrData.nFileSizeLow==0 ){
31746         attr = INVALID_FILE_ATTRIBUTES;
31747       }else{
31748         attr = sAttrData.dwFileAttributes;
31749       }
31750     }else{
31751       if( GetLastError()!=ERROR_FILE_NOT_FOUND ){
31752         free(zConverted);
31753         return SQLITE_IOERR_ACCESS;
31754       }else{
31755         attr = INVALID_FILE_ATTRIBUTES;
31756       }
31757     }
31758 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
31759 ** Since the ASCII version of these Windows API do not exist for WINCE,
31760 ** it's important to not reference them for WINCE builds.
31761 */
31762 #if SQLITE_OS_WINCE==0
31763   }else{
31764     attr = GetFileAttributesA((char*)zConverted);
31765 #endif
31766   }
31767   free(zConverted);
31768   switch( flags ){
31769     case SQLITE_ACCESS_READ:
31770     case SQLITE_ACCESS_EXISTS:
31771       rc = attr!=INVALID_FILE_ATTRIBUTES;
31772       break;
31773     case SQLITE_ACCESS_READWRITE:
31774       rc = (attr & FILE_ATTRIBUTE_READONLY)==0;
31775       break;
31776     default:
31777       assert(!"Invalid flags argument");
31778   }
31779   *pResOut = rc;
31780   return SQLITE_OK;
31781 }
31782
31783
31784 /*
31785 ** Turn a relative pathname into a full pathname.  Write the full
31786 ** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
31787 ** bytes in size.
31788 */
31789 static int winFullPathname(
31790   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
31791   const char *zRelative,        /* Possibly relative input path */
31792   int nFull,                    /* Size of output buffer in bytes */
31793   char *zFull                   /* Output buffer */
31794 ){
31795   
31796 #if defined(__CYGWIN__)
31797   SimulateIOError( return SQLITE_ERROR );
31798   UNUSED_PARAMETER(nFull);
31799   cygwin_conv_to_full_win32_path(zRelative, zFull);
31800   return SQLITE_OK;
31801 #endif
31802
31803 #if SQLITE_OS_WINCE
31804   SimulateIOError( return SQLITE_ERROR );
31805   UNUSED_PARAMETER(nFull);
31806   /* WinCE has no concept of a relative pathname, or so I am told. */
31807   sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zRelative);
31808   return SQLITE_OK;
31809 #endif
31810
31811 #if !SQLITE_OS_WINCE && !defined(__CYGWIN__)
31812   int nByte;
31813   void *zConverted;
31814   char *zOut;
31815
31816   /* It's odd to simulate an io-error here, but really this is just
31817   ** using the io-error infrastructure to test that SQLite handles this
31818   ** function failing. This function could fail if, for example, the
31819   ** current working directory has been unlinked.
31820   */
31821   SimulateIOError( return SQLITE_ERROR );
31822   UNUSED_PARAMETER(nFull);
31823   zConverted = convertUtf8Filename(zRelative);
31824   if( isNT() ){
31825     WCHAR *zTemp;
31826     nByte = GetFullPathNameW((WCHAR*)zConverted, 0, 0, 0) + 3;
31827     zTemp = malloc( nByte*sizeof(zTemp[0]) );
31828     if( zTemp==0 ){
31829       free(zConverted);
31830       return SQLITE_NOMEM;
31831     }
31832     GetFullPathNameW((WCHAR*)zConverted, nByte, zTemp, 0);
31833     free(zConverted);
31834     zOut = unicodeToUtf8(zTemp);
31835     free(zTemp);
31836 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
31837 ** Since the ASCII version of these Windows API do not exist for WINCE,
31838 ** it's important to not reference them for WINCE builds.
31839 */
31840 #if SQLITE_OS_WINCE==0
31841   }else{
31842     char *zTemp;
31843     nByte = GetFullPathNameA((char*)zConverted, 0, 0, 0) + 3;
31844     zTemp = malloc( nByte*sizeof(zTemp[0]) );
31845     if( zTemp==0 ){
31846       free(zConverted);
31847       return SQLITE_NOMEM;
31848     }
31849     GetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
31850     free(zConverted);
31851     zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
31852     free(zTemp);
31853 #endif
31854   }
31855   if( zOut ){
31856     sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zOut);
31857     free(zOut);
31858     return SQLITE_OK;
31859   }else{
31860     return SQLITE_NOMEM;
31861   }
31862 #endif
31863 }
31864
31865 /*
31866 ** Get the sector size of the device used to store
31867 ** file.
31868 */
31869 static int getSectorSize(
31870     sqlite3_vfs *pVfs,
31871     const char *zRelative     /* UTF-8 file name */
31872 ){
31873   DWORD bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE;
31874   /* GetDiskFreeSpace is not supported under WINCE */
31875 #if SQLITE_OS_WINCE
31876   UNUSED_PARAMETER(pVfs);
31877   UNUSED_PARAMETER(zRelative);
31878 #else
31879   char zFullpath[MAX_PATH+1];
31880   int rc;
31881   DWORD dwRet = 0;
31882   DWORD dwDummy;
31883
31884   /*
31885   ** We need to get the full path name of the file
31886   ** to get the drive letter to look up the sector
31887   ** size.
31888   */
31889   SimulateIOErrorBenign(1);
31890   rc = winFullPathname(pVfs, zRelative, MAX_PATH, zFullpath);
31891   SimulateIOErrorBenign(0);
31892   if( rc == SQLITE_OK )
31893   {
31894     void *zConverted = convertUtf8Filename(zFullpath);
31895     if( zConverted ){
31896       if( isNT() ){
31897         /* trim path to just drive reference */
31898         WCHAR *p = zConverted;
31899         for(;*p;p++){
31900           if( *p == '\\' ){
31901             *p = '\0';
31902             break;
31903           }
31904         }
31905         dwRet = GetDiskFreeSpaceW((WCHAR*)zConverted,
31906                                   &dwDummy,
31907                                   &bytesPerSector,
31908                                   &dwDummy,
31909                                   &dwDummy);
31910       }else{
31911         /* trim path to just drive reference */
31912         char *p = (char *)zConverted;
31913         for(;*p;p++){
31914           if( *p == '\\' ){
31915             *p = '\0';
31916             break;
31917           }
31918         }
31919         dwRet = GetDiskFreeSpaceA((char*)zConverted,
31920                                   &dwDummy,
31921                                   &bytesPerSector,
31922                                   &dwDummy,
31923                                   &dwDummy);
31924       }
31925       free(zConverted);
31926     }
31927     if( !dwRet ){
31928       bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE;
31929     }
31930   }
31931 #endif
31932   return (int) bytesPerSector; 
31933 }
31934
31935 #ifndef SQLITE_OMIT_LOAD_EXTENSION
31936 /*
31937 ** Interfaces for opening a shared library, finding entry points
31938 ** within the shared library, and closing the shared library.
31939 */
31940 /*
31941 ** Interfaces for opening a shared library, finding entry points
31942 ** within the shared library, and closing the shared library.
31943 */
31944 static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
31945   HANDLE h;
31946   void *zConverted = convertUtf8Filename(zFilename);
31947   UNUSED_PARAMETER(pVfs);
31948   if( zConverted==0 ){
31949     return 0;
31950   }
31951   if( isNT() ){
31952     h = LoadLibraryW((WCHAR*)zConverted);
31953 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
31954 ** Since the ASCII version of these Windows API do not exist for WINCE,
31955 ** it's important to not reference them for WINCE builds.
31956 */
31957 #if SQLITE_OS_WINCE==0
31958   }else{
31959     h = LoadLibraryA((char*)zConverted);
31960 #endif
31961   }
31962   free(zConverted);
31963   return (void*)h;
31964 }
31965 static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
31966   UNUSED_PARAMETER(pVfs);
31967   getLastErrorMsg(nBuf, zBufOut);
31968 }
31969 void (*winDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol))(void){
31970   UNUSED_PARAMETER(pVfs);
31971 #if SQLITE_OS_WINCE
31972   /* The GetProcAddressA() routine is only available on wince. */
31973   return (void(*)(void))GetProcAddressA((HANDLE)pHandle, zSymbol);
31974 #else
31975   /* All other windows platforms expect GetProcAddress() to take
31976   ** an Ansi string regardless of the _UNICODE setting */
31977   return (void(*)(void))GetProcAddress((HANDLE)pHandle, zSymbol);
31978 #endif
31979 }
31980 void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
31981   UNUSED_PARAMETER(pVfs);
31982   FreeLibrary((HANDLE)pHandle);
31983 }
31984 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
31985   #define winDlOpen  0
31986   #define winDlError 0
31987   #define winDlSym   0
31988   #define winDlClose 0
31989 #endif
31990
31991
31992 /*
31993 ** Write up to nBuf bytes of randomness into zBuf.
31994 */
31995 static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
31996   int n = 0;
31997   UNUSED_PARAMETER(pVfs);
31998 #if defined(SQLITE_TEST)
31999   n = nBuf;
32000   memset(zBuf, 0, nBuf);
32001 #else
32002   if( sizeof(SYSTEMTIME)<=nBuf-n ){
32003     SYSTEMTIME x;
32004     GetSystemTime(&x);
32005     memcpy(&zBuf[n], &x, sizeof(x));
32006     n += sizeof(x);
32007   }
32008   if( sizeof(DWORD)<=nBuf-n ){
32009     DWORD pid = GetCurrentProcessId();
32010     memcpy(&zBuf[n], &pid, sizeof(pid));
32011     n += sizeof(pid);
32012   }
32013   if( sizeof(DWORD)<=nBuf-n ){
32014     DWORD cnt = GetTickCount();
32015     memcpy(&zBuf[n], &cnt, sizeof(cnt));
32016     n += sizeof(cnt);
32017   }
32018   if( sizeof(LARGE_INTEGER)<=nBuf-n ){
32019     LARGE_INTEGER i;
32020     QueryPerformanceCounter(&i);
32021     memcpy(&zBuf[n], &i, sizeof(i));
32022     n += sizeof(i);
32023   }
32024 #endif
32025   return n;
32026 }
32027
32028
32029 /*
32030 ** Sleep for a little while.  Return the amount of time slept.
32031 */
32032 static int winSleep(sqlite3_vfs *pVfs, int microsec){
32033   Sleep((microsec+999)/1000);
32034   UNUSED_PARAMETER(pVfs);
32035   return ((microsec+999)/1000)*1000;
32036 }
32037
32038 /*
32039 ** The following variable, if set to a non-zero value, is interpreted as
32040 ** the number of seconds since 1970 and is used to set the result of
32041 ** sqlite3OsCurrentTime() during testing.
32042 */
32043 #ifdef SQLITE_TEST
32044 SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
32045 #endif
32046
32047 /*
32048 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
32049 ** the current time and date as a Julian Day number times 86_400_000.  In
32050 ** other words, write into *piNow the number of milliseconds since the Julian
32051 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
32052 ** proleptic Gregorian calendar.
32053 **
32054 ** On success, return 0.  Return 1 if the time and date cannot be found.
32055 */
32056 static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
32057   /* FILETIME structure is a 64-bit value representing the number of 
32058      100-nanosecond intervals since January 1, 1601 (= JD 2305813.5). 
32059   */
32060   FILETIME ft;
32061   static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
32062 #ifdef SQLITE_TEST
32063   static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
32064 #endif
32065   /* 2^32 - to avoid use of LL and warnings in gcc */
32066   static const sqlite3_int64 max32BitValue = 
32067       (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 + (sqlite3_int64)294967296;
32068
32069 #if SQLITE_OS_WINCE
32070   SYSTEMTIME time;
32071   GetSystemTime(&time);
32072   /* if SystemTimeToFileTime() fails, it returns zero. */
32073   if (!SystemTimeToFileTime(&time,&ft)){
32074     return 1;
32075   }
32076 #else
32077   GetSystemTimeAsFileTime( &ft );
32078 #endif
32079
32080   *piNow = winFiletimeEpoch +
32081             ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) + 
32082                (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
32083
32084 #ifdef SQLITE_TEST
32085   if( sqlite3_current_time ){
32086     *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
32087   }
32088 #endif
32089   UNUSED_PARAMETER(pVfs);
32090   return 0;
32091 }
32092
32093 /*
32094 ** Find the current time (in Universal Coordinated Time).  Write the
32095 ** current time and date as a Julian Day number into *prNow and
32096 ** return 0.  Return 1 if the time and date cannot be found.
32097 */
32098 int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
32099   int rc;
32100   sqlite3_int64 i;
32101   rc = winCurrentTimeInt64(pVfs, &i);
32102   if( !rc ){
32103     *prNow = i/86400000.0;
32104   }
32105   return rc;
32106 }
32107
32108 /*
32109 ** The idea is that this function works like a combination of
32110 ** GetLastError() and FormatMessage() on windows (or errno and
32111 ** strerror_r() on unix). After an error is returned by an OS
32112 ** function, SQLite calls this function with zBuf pointing to
32113 ** a buffer of nBuf bytes. The OS layer should populate the
32114 ** buffer with a nul-terminated UTF-8 encoded error message
32115 ** describing the last IO error to have occurred within the calling
32116 ** thread.
32117 **
32118 ** If the error message is too large for the supplied buffer,
32119 ** it should be truncated. The return value of xGetLastError
32120 ** is zero if the error message fits in the buffer, or non-zero
32121 ** otherwise (if the message was truncated). If non-zero is returned,
32122 ** then it is not necessary to include the nul-terminator character
32123 ** in the output buffer.
32124 **
32125 ** Not supplying an error message will have no adverse effect
32126 ** on SQLite. It is fine to have an implementation that never
32127 ** returns an error message:
32128 **
32129 **   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
32130 **     assert(zBuf[0]=='\0');
32131 **     return 0;
32132 **   }
32133 **
32134 ** However if an error message is supplied, it will be incorporated
32135 ** by sqlite into the error message available to the user using
32136 ** sqlite3_errmsg(), possibly making IO errors easier to debug.
32137 */
32138 static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
32139   UNUSED_PARAMETER(pVfs);
32140   return getLastErrorMsg(nBuf, zBuf);
32141 }
32142
32143
32144
32145 /*
32146 ** Initialize and deinitialize the operating system interface.
32147 */
32148 SQLITE_API int sqlite3_os_init(void){
32149   static sqlite3_vfs winVfs = {
32150     2,                   /* iVersion */
32151     sizeof(winFile),     /* szOsFile */
32152     MAX_PATH,            /* mxPathname */
32153     0,                   /* pNext */
32154     "win32",             /* zName */
32155     0,                   /* pAppData */
32156     winOpen,             /* xOpen */
32157     winDelete,           /* xDelete */
32158     winAccess,           /* xAccess */
32159     winFullPathname,     /* xFullPathname */
32160     winDlOpen,           /* xDlOpen */
32161     winDlError,          /* xDlError */
32162     winDlSym,            /* xDlSym */
32163     winDlClose,          /* xDlClose */
32164     winRandomness,       /* xRandomness */
32165     winSleep,            /* xSleep */
32166     winCurrentTime,      /* xCurrentTime */
32167     winGetLastError,     /* xGetLastError */
32168     winCurrentTimeInt64, /* xCurrentTimeInt64 */
32169   };
32170
32171 #ifndef SQLITE_OMIT_WAL
32172   /* get memory map allocation granularity */
32173   memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
32174   GetSystemInfo(&winSysInfo);
32175   assert(winSysInfo.dwAllocationGranularity > 0);
32176 #endif
32177
32178   sqlite3_vfs_register(&winVfs, 1);
32179   return SQLITE_OK; 
32180 }
32181 SQLITE_API int sqlite3_os_end(void){ 
32182   return SQLITE_OK;
32183 }
32184
32185 #endif /* SQLITE_OS_WIN */
32186
32187 /************** End of os_win.c **********************************************/
32188 /************** Begin file bitvec.c ******************************************/
32189 /*
32190 ** 2008 February 16
32191 **
32192 ** The author disclaims copyright to this source code.  In place of
32193 ** a legal notice, here is a blessing:
32194 **
32195 **    May you do good and not evil.
32196 **    May you find forgiveness for yourself and forgive others.
32197 **    May you share freely, never taking more than you give.
32198 **
32199 *************************************************************************
32200 ** This file implements an object that represents a fixed-length
32201 ** bitmap.  Bits are numbered starting with 1.
32202 **
32203 ** A bitmap is used to record which pages of a database file have been
32204 ** journalled during a transaction, or which pages have the "dont-write"
32205 ** property.  Usually only a few pages are meet either condition.
32206 ** So the bitmap is usually sparse and has low cardinality.
32207 ** But sometimes (for example when during a DROP of a large table) most
32208 ** or all of the pages in a database can get journalled.  In those cases, 
32209 ** the bitmap becomes dense with high cardinality.  The algorithm needs 
32210 ** to handle both cases well.
32211 **
32212 ** The size of the bitmap is fixed when the object is created.
32213 **
32214 ** All bits are clear when the bitmap is created.  Individual bits
32215 ** may be set or cleared one at a time.
32216 **
32217 ** Test operations are about 100 times more common that set operations.
32218 ** Clear operations are exceedingly rare.  There are usually between
32219 ** 5 and 500 set operations per Bitvec object, though the number of sets can
32220 ** sometimes grow into tens of thousands or larger.  The size of the
32221 ** Bitvec object is the number of pages in the database file at the
32222 ** start of a transaction, and is thus usually less than a few thousand,
32223 ** but can be as large as 2 billion for a really big database.
32224 */
32225
32226 /* Size of the Bitvec structure in bytes. */
32227 #define BITVEC_SZ        512
32228
32229 /* Round the union size down to the nearest pointer boundary, since that's how 
32230 ** it will be aligned within the Bitvec struct. */
32231 #define BITVEC_USIZE     (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
32232
32233 /* Type of the array "element" for the bitmap representation. 
32234 ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE. 
32235 ** Setting this to the "natural word" size of your CPU may improve
32236 ** performance. */
32237 #define BITVEC_TELEM     u8
32238 /* Size, in bits, of the bitmap element. */
32239 #define BITVEC_SZELEM    8
32240 /* Number of elements in a bitmap array. */
32241 #define BITVEC_NELEM     (BITVEC_USIZE/sizeof(BITVEC_TELEM))
32242 /* Number of bits in the bitmap array. */
32243 #define BITVEC_NBIT      (BITVEC_NELEM*BITVEC_SZELEM)
32244
32245 /* Number of u32 values in hash table. */
32246 #define BITVEC_NINT      (BITVEC_USIZE/sizeof(u32))
32247 /* Maximum number of entries in hash table before 
32248 ** sub-dividing and re-hashing. */
32249 #define BITVEC_MXHASH    (BITVEC_NINT/2)
32250 /* Hashing function for the aHash representation.
32251 ** Empirical testing showed that the *37 multiplier 
32252 ** (an arbitrary prime)in the hash function provided 
32253 ** no fewer collisions than the no-op *1. */
32254 #define BITVEC_HASH(X)   (((X)*1)%BITVEC_NINT)
32255
32256 #define BITVEC_NPTR      (BITVEC_USIZE/sizeof(Bitvec *))
32257
32258
32259 /*
32260 ** A bitmap is an instance of the following structure.
32261 **
32262 ** This bitmap records the existance of zero or more bits
32263 ** with values between 1 and iSize, inclusive.
32264 **
32265 ** There are three possible representations of the bitmap.
32266 ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
32267 ** bitmap.  The least significant bit is bit 1.
32268 **
32269 ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
32270 ** a hash table that will hold up to BITVEC_MXHASH distinct values.
32271 **
32272 ** Otherwise, the value i is redirected into one of BITVEC_NPTR
32273 ** sub-bitmaps pointed to by Bitvec.u.apSub[].  Each subbitmap
32274 ** handles up to iDivisor separate values of i.  apSub[0] holds
32275 ** values between 1 and iDivisor.  apSub[1] holds values between
32276 ** iDivisor+1 and 2*iDivisor.  apSub[N] holds values between
32277 ** N*iDivisor+1 and (N+1)*iDivisor.  Each subbitmap is normalized
32278 ** to hold deal with values between 1 and iDivisor.
32279 */
32280 struct Bitvec {
32281   u32 iSize;      /* Maximum bit index.  Max iSize is 4,294,967,296. */
32282   u32 nSet;       /* Number of bits that are set - only valid for aHash
32283                   ** element.  Max is BITVEC_NINT.  For BITVEC_SZ of 512,
32284                   ** this would be 125. */
32285   u32 iDivisor;   /* Number of bits handled by each apSub[] entry. */
32286                   /* Should >=0 for apSub element. */
32287                   /* Max iDivisor is max(u32) / BITVEC_NPTR + 1.  */
32288                   /* For a BITVEC_SZ of 512, this would be 34,359,739. */
32289   union {
32290     BITVEC_TELEM aBitmap[BITVEC_NELEM];    /* Bitmap representation */
32291     u32 aHash[BITVEC_NINT];      /* Hash table representation */
32292     Bitvec *apSub[BITVEC_NPTR];  /* Recursive representation */
32293   } u;
32294 };
32295
32296 /*
32297 ** Create a new bitmap object able to handle bits between 0 and iSize,
32298 ** inclusive.  Return a pointer to the new object.  Return NULL if 
32299 ** malloc fails.
32300 */
32301 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
32302   Bitvec *p;
32303   assert( sizeof(*p)==BITVEC_SZ );
32304   p = sqlite3MallocZero( sizeof(*p) );
32305   if( p ){
32306     p->iSize = iSize;
32307   }
32308   return p;
32309 }
32310
32311 /*
32312 ** Check to see if the i-th bit is set.  Return true or false.
32313 ** If p is NULL (if the bitmap has not been created) or if
32314 ** i is out of range, then return false.
32315 */
32316 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
32317   if( p==0 ) return 0;
32318   if( i>p->iSize || i==0 ) return 0;
32319   i--;
32320   while( p->iDivisor ){
32321     u32 bin = i/p->iDivisor;
32322     i = i%p->iDivisor;
32323     p = p->u.apSub[bin];
32324     if (!p) {
32325       return 0;
32326     }
32327   }
32328   if( p->iSize<=BITVEC_NBIT ){
32329     return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
32330   } else{
32331     u32 h = BITVEC_HASH(i++);
32332     while( p->u.aHash[h] ){
32333       if( p->u.aHash[h]==i ) return 1;
32334       h = (h+1) % BITVEC_NINT;
32335     }
32336     return 0;
32337   }
32338 }
32339
32340 /*
32341 ** Set the i-th bit.  Return 0 on success and an error code if
32342 ** anything goes wrong.
32343 **
32344 ** This routine might cause sub-bitmaps to be allocated.  Failing
32345 ** to get the memory needed to hold the sub-bitmap is the only
32346 ** that can go wrong with an insert, assuming p and i are valid.
32347 **
32348 ** The calling function must ensure that p is a valid Bitvec object
32349 ** and that the value for "i" is within range of the Bitvec object.
32350 ** Otherwise the behavior is undefined.
32351 */
32352 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
32353   u32 h;
32354   if( p==0 ) return SQLITE_OK;
32355   assert( i>0 );
32356   assert( i<=p->iSize );
32357   i--;
32358   while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
32359     u32 bin = i/p->iDivisor;
32360     i = i%p->iDivisor;
32361     if( p->u.apSub[bin]==0 ){
32362       p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
32363       if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
32364     }
32365     p = p->u.apSub[bin];
32366   }
32367   if( p->iSize<=BITVEC_NBIT ){
32368     p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
32369     return SQLITE_OK;
32370   }
32371   h = BITVEC_HASH(i++);
32372   /* if there wasn't a hash collision, and this doesn't */
32373   /* completely fill the hash, then just add it without */
32374   /* worring about sub-dividing and re-hashing. */
32375   if( !p->u.aHash[h] ){
32376     if (p->nSet<(BITVEC_NINT-1)) {
32377       goto bitvec_set_end;
32378     } else {
32379       goto bitvec_set_rehash;
32380     }
32381   }
32382   /* there was a collision, check to see if it's already */
32383   /* in hash, if not, try to find a spot for it */
32384   do {
32385     if( p->u.aHash[h]==i ) return SQLITE_OK;
32386     h++;
32387     if( h>=BITVEC_NINT ) h = 0;
32388   } while( p->u.aHash[h] );
32389   /* we didn't find it in the hash.  h points to the first */
32390   /* available free spot. check to see if this is going to */
32391   /* make our hash too "full".  */
32392 bitvec_set_rehash:
32393   if( p->nSet>=BITVEC_MXHASH ){
32394     unsigned int j;
32395     int rc;
32396     u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
32397     if( aiValues==0 ){
32398       return SQLITE_NOMEM;
32399     }else{
32400       memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
32401       memset(p->u.apSub, 0, sizeof(p->u.apSub));
32402       p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
32403       rc = sqlite3BitvecSet(p, i);
32404       for(j=0; j<BITVEC_NINT; j++){
32405         if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
32406       }
32407       sqlite3StackFree(0, aiValues);
32408       return rc;
32409     }
32410   }
32411 bitvec_set_end:
32412   p->nSet++;
32413   p->u.aHash[h] = i;
32414   return SQLITE_OK;
32415 }
32416
32417 /*
32418 ** Clear the i-th bit.
32419 **
32420 ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
32421 ** that BitvecClear can use to rebuilt its hash table.
32422 */
32423 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
32424   if( p==0 ) return;
32425   assert( i>0 );
32426   i--;
32427   while( p->iDivisor ){
32428     u32 bin = i/p->iDivisor;
32429     i = i%p->iDivisor;
32430     p = p->u.apSub[bin];
32431     if (!p) {
32432       return;
32433     }
32434   }
32435   if( p->iSize<=BITVEC_NBIT ){
32436     p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
32437   }else{
32438     unsigned int j;
32439     u32 *aiValues = pBuf;
32440     memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
32441     memset(p->u.aHash, 0, sizeof(p->u.aHash));
32442     p->nSet = 0;
32443     for(j=0; j<BITVEC_NINT; j++){
32444       if( aiValues[j] && aiValues[j]!=(i+1) ){
32445         u32 h = BITVEC_HASH(aiValues[j]-1);
32446         p->nSet++;
32447         while( p->u.aHash[h] ){
32448           h++;
32449           if( h>=BITVEC_NINT ) h = 0;
32450         }
32451         p->u.aHash[h] = aiValues[j];
32452       }
32453     }
32454   }
32455 }
32456
32457 /*
32458 ** Destroy a bitmap object.  Reclaim all memory used.
32459 */
32460 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
32461   if( p==0 ) return;
32462   if( p->iDivisor ){
32463     unsigned int i;
32464     for(i=0; i<BITVEC_NPTR; i++){
32465       sqlite3BitvecDestroy(p->u.apSub[i]);
32466     }
32467   }
32468   sqlite3_free(p);
32469 }
32470
32471 /*
32472 ** Return the value of the iSize parameter specified when Bitvec *p
32473 ** was created.
32474 */
32475 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
32476   return p->iSize;
32477 }
32478
32479 #ifndef SQLITE_OMIT_BUILTIN_TEST
32480 /*
32481 ** Let V[] be an array of unsigned characters sufficient to hold
32482 ** up to N bits.  Let I be an integer between 0 and N.  0<=I<N.
32483 ** Then the following macros can be used to set, clear, or test
32484 ** individual bits within V.
32485 */
32486 #define SETBIT(V,I)      V[I>>3] |= (1<<(I&7))
32487 #define CLEARBIT(V,I)    V[I>>3] &= ~(1<<(I&7))
32488 #define TESTBIT(V,I)     (V[I>>3]&(1<<(I&7)))!=0
32489
32490 /*
32491 ** This routine runs an extensive test of the Bitvec code.
32492 **
32493 ** The input is an array of integers that acts as a program
32494 ** to test the Bitvec.  The integers are opcodes followed
32495 ** by 0, 1, or 3 operands, depending on the opcode.  Another
32496 ** opcode follows immediately after the last operand.
32497 **
32498 ** There are 6 opcodes numbered from 0 through 5.  0 is the
32499 ** "halt" opcode and causes the test to end.
32500 **
32501 **    0          Halt and return the number of errors
32502 **    1 N S X    Set N bits beginning with S and incrementing by X
32503 **    2 N S X    Clear N bits beginning with S and incrementing by X
32504 **    3 N        Set N randomly chosen bits
32505 **    4 N        Clear N randomly chosen bits
32506 **    5 N S X    Set N bits from S increment X in array only, not in bitvec
32507 **
32508 ** The opcodes 1 through 4 perform set and clear operations are performed
32509 ** on both a Bitvec object and on a linear array of bits obtained from malloc.
32510 ** Opcode 5 works on the linear array only, not on the Bitvec.
32511 ** Opcode 5 is used to deliberately induce a fault in order to
32512 ** confirm that error detection works.
32513 **
32514 ** At the conclusion of the test the linear array is compared
32515 ** against the Bitvec object.  If there are any differences,
32516 ** an error is returned.  If they are the same, zero is returned.
32517 **
32518 ** If a memory allocation error occurs, return -1.
32519 */
32520 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
32521   Bitvec *pBitvec = 0;
32522   unsigned char *pV = 0;
32523   int rc = -1;
32524   int i, nx, pc, op;
32525   void *pTmpSpace;
32526
32527   /* Allocate the Bitvec to be tested and a linear array of
32528   ** bits to act as the reference */
32529   pBitvec = sqlite3BitvecCreate( sz );
32530   pV = sqlite3_malloc( (sz+7)/8 + 1 );
32531   pTmpSpace = sqlite3_malloc(BITVEC_SZ);
32532   if( pBitvec==0 || pV==0 || pTmpSpace==0  ) goto bitvec_end;
32533   memset(pV, 0, (sz+7)/8 + 1);
32534
32535   /* NULL pBitvec tests */
32536   sqlite3BitvecSet(0, 1);
32537   sqlite3BitvecClear(0, 1, pTmpSpace);
32538
32539   /* Run the program */
32540   pc = 0;
32541   while( (op = aOp[pc])!=0 ){
32542     switch( op ){
32543       case 1:
32544       case 2:
32545       case 5: {
32546         nx = 4;
32547         i = aOp[pc+2] - 1;
32548         aOp[pc+2] += aOp[pc+3];
32549         break;
32550       }
32551       case 3:
32552       case 4: 
32553       default: {
32554         nx = 2;
32555         sqlite3_randomness(sizeof(i), &i);
32556         break;
32557       }
32558     }
32559     if( (--aOp[pc+1]) > 0 ) nx = 0;
32560     pc += nx;
32561     i = (i & 0x7fffffff)%sz;
32562     if( (op & 1)!=0 ){
32563       SETBIT(pV, (i+1));
32564       if( op!=5 ){
32565         if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
32566       }
32567     }else{
32568       CLEARBIT(pV, (i+1));
32569       sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
32570     }
32571   }
32572
32573   /* Test to make sure the linear array exactly matches the
32574   ** Bitvec object.  Start with the assumption that they do
32575   ** match (rc==0).  Change rc to non-zero if a discrepancy
32576   ** is found.
32577   */
32578   rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
32579           + sqlite3BitvecTest(pBitvec, 0)
32580           + (sqlite3BitvecSize(pBitvec) - sz);
32581   for(i=1; i<=sz; i++){
32582     if(  (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
32583       rc = i;
32584       break;
32585     }
32586   }
32587
32588   /* Free allocated structure */
32589 bitvec_end:
32590   sqlite3_free(pTmpSpace);
32591   sqlite3_free(pV);
32592   sqlite3BitvecDestroy(pBitvec);
32593   return rc;
32594 }
32595 #endif /* SQLITE_OMIT_BUILTIN_TEST */
32596
32597 /************** End of bitvec.c **********************************************/
32598 /************** Begin file pcache.c ******************************************/
32599 /*
32600 ** 2008 August 05
32601 **
32602 ** The author disclaims copyright to this source code.  In place of
32603 ** a legal notice, here is a blessing:
32604 **
32605 **    May you do good and not evil.
32606 **    May you find forgiveness for yourself and forgive others.
32607 **    May you share freely, never taking more than you give.
32608 **
32609 *************************************************************************
32610 ** This file implements that page cache.
32611 */
32612
32613 /*
32614 ** A complete page cache is an instance of this structure.
32615 */
32616 struct PCache {
32617   PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
32618   PgHdr *pSynced;                     /* Last synced page in dirty page list */
32619   int nRef;                           /* Number of referenced pages */
32620   int nMax;                           /* Configured cache size */
32621   int szPage;                         /* Size of every page in this cache */
32622   int szExtra;                        /* Size of extra space for each page */
32623   int bPurgeable;                     /* True if pages are on backing store */
32624   int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */
32625   void *pStress;                      /* Argument to xStress */
32626   sqlite3_pcache *pCache;             /* Pluggable cache module */
32627   PgHdr *pPage1;                      /* Reference to page 1 */
32628 };
32629
32630 /*
32631 ** Some of the assert() macros in this code are too expensive to run
32632 ** even during normal debugging.  Use them only rarely on long-running
32633 ** tests.  Enable the expensive asserts using the
32634 ** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
32635 */
32636 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
32637 # define expensive_assert(X)  assert(X)
32638 #else
32639 # define expensive_assert(X)
32640 #endif
32641
32642 /********************************** Linked List Management ********************/
32643
32644 #if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
32645 /*
32646 ** Check that the pCache->pSynced variable is set correctly. If it
32647 ** is not, either fail an assert or return zero. Otherwise, return
32648 ** non-zero. This is only used in debugging builds, as follows:
32649 **
32650 **   expensive_assert( pcacheCheckSynced(pCache) );
32651 */
32652 static int pcacheCheckSynced(PCache *pCache){
32653   PgHdr *p;
32654   for(p=pCache->pDirtyTail; p!=pCache->pSynced; p=p->pDirtyPrev){
32655     assert( p->nRef || (p->flags&PGHDR_NEED_SYNC) );
32656   }
32657   return (p==0 || p->nRef || (p->flags&PGHDR_NEED_SYNC)==0);
32658 }
32659 #endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
32660
32661 /*
32662 ** Remove page pPage from the list of dirty pages.
32663 */
32664 static void pcacheRemoveFromDirtyList(PgHdr *pPage){
32665   PCache *p = pPage->pCache;
32666
32667   assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
32668   assert( pPage->pDirtyPrev || pPage==p->pDirty );
32669
32670   /* Update the PCache1.pSynced variable if necessary. */
32671   if( p->pSynced==pPage ){
32672     PgHdr *pSynced = pPage->pDirtyPrev;
32673     while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
32674       pSynced = pSynced->pDirtyPrev;
32675     }
32676     p->pSynced = pSynced;
32677   }
32678
32679   if( pPage->pDirtyNext ){
32680     pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
32681   }else{
32682     assert( pPage==p->pDirtyTail );
32683     p->pDirtyTail = pPage->pDirtyPrev;
32684   }
32685   if( pPage->pDirtyPrev ){
32686     pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
32687   }else{
32688     assert( pPage==p->pDirty );
32689     p->pDirty = pPage->pDirtyNext;
32690   }
32691   pPage->pDirtyNext = 0;
32692   pPage->pDirtyPrev = 0;
32693
32694   expensive_assert( pcacheCheckSynced(p) );
32695 }
32696
32697 /*
32698 ** Add page pPage to the head of the dirty list (PCache1.pDirty is set to
32699 ** pPage).
32700 */
32701 static void pcacheAddToDirtyList(PgHdr *pPage){
32702   PCache *p = pPage->pCache;
32703
32704   assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
32705
32706   pPage->pDirtyNext = p->pDirty;
32707   if( pPage->pDirtyNext ){
32708     assert( pPage->pDirtyNext->pDirtyPrev==0 );
32709     pPage->pDirtyNext->pDirtyPrev = pPage;
32710   }
32711   p->pDirty = pPage;
32712   if( !p->pDirtyTail ){
32713     p->pDirtyTail = pPage;
32714   }
32715   if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
32716     p->pSynced = pPage;
32717   }
32718   expensive_assert( pcacheCheckSynced(p) );
32719 }
32720
32721 /*
32722 ** Wrapper around the pluggable caches xUnpin method. If the cache is
32723 ** being used for an in-memory database, this function is a no-op.
32724 */
32725 static void pcacheUnpin(PgHdr *p){
32726   PCache *pCache = p->pCache;
32727   if( pCache->bPurgeable ){
32728     if( p->pgno==1 ){
32729       pCache->pPage1 = 0;
32730     }
32731     sqlite3GlobalConfig.pcache.xUnpin(pCache->pCache, p, 0);
32732   }
32733 }
32734
32735 /*************************************************** General Interfaces ******
32736 **
32737 ** Initialize and shutdown the page cache subsystem. Neither of these 
32738 ** functions are threadsafe.
32739 */
32740 SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
32741   if( sqlite3GlobalConfig.pcache.xInit==0 ){
32742     /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
32743     ** built-in default page cache is used instead of the application defined
32744     ** page cache. */
32745     sqlite3PCacheSetDefault();
32746   }
32747   return sqlite3GlobalConfig.pcache.xInit(sqlite3GlobalConfig.pcache.pArg);
32748 }
32749 SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
32750   if( sqlite3GlobalConfig.pcache.xShutdown ){
32751     /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
32752     sqlite3GlobalConfig.pcache.xShutdown(sqlite3GlobalConfig.pcache.pArg);
32753   }
32754 }
32755
32756 /*
32757 ** Return the size in bytes of a PCache object.
32758 */
32759 SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
32760
32761 /*
32762 ** Create a new PCache object. Storage space to hold the object
32763 ** has already been allocated and is passed in as the p pointer. 
32764 ** The caller discovers how much space needs to be allocated by 
32765 ** calling sqlite3PcacheSize().
32766 */
32767 SQLITE_PRIVATE void sqlite3PcacheOpen(
32768   int szPage,                  /* Size of every page */
32769   int szExtra,                 /* Extra space associated with each page */
32770   int bPurgeable,              /* True if pages are on backing store */
32771   int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
32772   void *pStress,               /* Argument to xStress */
32773   PCache *p                    /* Preallocated space for the PCache */
32774 ){
32775   memset(p, 0, sizeof(PCache));
32776   p->szPage = szPage;
32777   p->szExtra = szExtra;
32778   p->bPurgeable = bPurgeable;
32779   p->xStress = xStress;
32780   p->pStress = pStress;
32781   p->nMax = 100;
32782 }
32783
32784 /*
32785 ** Change the page size for PCache object. The caller must ensure that there
32786 ** are no outstanding page references when this function is called.
32787 */
32788 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
32789   assert( pCache->nRef==0 && pCache->pDirty==0 );
32790   if( pCache->pCache ){
32791     sqlite3GlobalConfig.pcache.xDestroy(pCache->pCache);
32792     pCache->pCache = 0;
32793     pCache->pPage1 = 0;
32794   }
32795   pCache->szPage = szPage;
32796 }
32797
32798 /*
32799 ** Try to obtain a page from the cache.
32800 */
32801 SQLITE_PRIVATE int sqlite3PcacheFetch(
32802   PCache *pCache,       /* Obtain the page from this cache */
32803   Pgno pgno,            /* Page number to obtain */
32804   int createFlag,       /* If true, create page if it does not exist already */
32805   PgHdr **ppPage        /* Write the page here */
32806 ){
32807   PgHdr *pPage = 0;
32808   int eCreate;
32809
32810   assert( pCache!=0 );
32811   assert( createFlag==1 || createFlag==0 );
32812   assert( pgno>0 );
32813
32814   /* If the pluggable cache (sqlite3_pcache*) has not been allocated,
32815   ** allocate it now.
32816   */
32817   if( !pCache->pCache && createFlag ){
32818     sqlite3_pcache *p;
32819     int nByte;
32820     nByte = pCache->szPage + pCache->szExtra + sizeof(PgHdr);
32821     p = sqlite3GlobalConfig.pcache.xCreate(nByte, pCache->bPurgeable);
32822     if( !p ){
32823       return SQLITE_NOMEM;
32824     }
32825     sqlite3GlobalConfig.pcache.xCachesize(p, pCache->nMax);
32826     pCache->pCache = p;
32827   }
32828
32829   eCreate = createFlag * (1 + (!pCache->bPurgeable || !pCache->pDirty));
32830   if( pCache->pCache ){
32831     pPage = sqlite3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, eCreate);
32832   }
32833
32834   if( !pPage && eCreate==1 ){
32835     PgHdr *pPg;
32836
32837     /* Find a dirty page to write-out and recycle. First try to find a 
32838     ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
32839     ** cleared), but if that is not possible settle for any other 
32840     ** unreferenced dirty page.
32841     */
32842     expensive_assert( pcacheCheckSynced(pCache) );
32843     for(pPg=pCache->pSynced; 
32844         pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC)); 
32845         pPg=pPg->pDirtyPrev
32846     );
32847     pCache->pSynced = pPg;
32848     if( !pPg ){
32849       for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
32850     }
32851     if( pPg ){
32852       int rc;
32853       rc = pCache->xStress(pCache->pStress, pPg);
32854       if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
32855         return rc;
32856       }
32857     }
32858
32859     pPage = sqlite3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, 2);
32860   }
32861
32862   if( pPage ){
32863     if( !pPage->pData ){
32864       memset(pPage, 0, sizeof(PgHdr));
32865       pPage->pData = (void *)&pPage[1];
32866       pPage->pExtra = (void*)&((char *)pPage->pData)[pCache->szPage];
32867       memset(pPage->pExtra, 0, pCache->szExtra);
32868       pPage->pCache = pCache;
32869       pPage->pgno = pgno;
32870     }
32871     assert( pPage->pCache==pCache );
32872     assert( pPage->pgno==pgno );
32873     assert( pPage->pData==(void *)&pPage[1] );
32874     assert( pPage->pExtra==(void *)&((char *)&pPage[1])[pCache->szPage] );
32875
32876     if( 0==pPage->nRef ){
32877       pCache->nRef++;
32878     }
32879     pPage->nRef++;
32880     if( pgno==1 ){
32881       pCache->pPage1 = pPage;
32882     }
32883   }
32884   *ppPage = pPage;
32885   return (pPage==0 && eCreate) ? SQLITE_NOMEM : SQLITE_OK;
32886 }
32887
32888 /*
32889 ** Decrement the reference count on a page. If the page is clean and the
32890 ** reference count drops to 0, then it is made elible for recycling.
32891 */
32892 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr *p){
32893   assert( p->nRef>0 );
32894   p->nRef--;
32895   if( p->nRef==0 ){
32896     PCache *pCache = p->pCache;
32897     pCache->nRef--;
32898     if( (p->flags&PGHDR_DIRTY)==0 ){
32899       pcacheUnpin(p);
32900     }else{
32901       /* Move the page to the head of the dirty list. */
32902       pcacheRemoveFromDirtyList(p);
32903       pcacheAddToDirtyList(p);
32904     }
32905   }
32906 }
32907
32908 /*
32909 ** Increase the reference count of a supplied page by 1.
32910 */
32911 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
32912   assert(p->nRef>0);
32913   p->nRef++;
32914 }
32915
32916 /*
32917 ** Drop a page from the cache. There must be exactly one reference to the
32918 ** page. This function deletes that reference, so after it returns the
32919 ** page pointed to by p is invalid.
32920 */
32921 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
32922   PCache *pCache;
32923   assert( p->nRef==1 );
32924   if( p->flags&PGHDR_DIRTY ){
32925     pcacheRemoveFromDirtyList(p);
32926   }
32927   pCache = p->pCache;
32928   pCache->nRef--;
32929   if( p->pgno==1 ){
32930     pCache->pPage1 = 0;
32931   }
32932   sqlite3GlobalConfig.pcache.xUnpin(pCache->pCache, p, 1);
32933 }
32934
32935 /*
32936 ** Make sure the page is marked as dirty. If it isn't dirty already,
32937 ** make it so.
32938 */
32939 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
32940   p->flags &= ~PGHDR_DONT_WRITE;
32941   assert( p->nRef>0 );
32942   if( 0==(p->flags & PGHDR_DIRTY) ){
32943     p->flags |= PGHDR_DIRTY;
32944     pcacheAddToDirtyList( p);
32945   }
32946 }
32947
32948 /*
32949 ** Make sure the page is marked as clean. If it isn't clean already,
32950 ** make it so.
32951 */
32952 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
32953   if( (p->flags & PGHDR_DIRTY) ){
32954     pcacheRemoveFromDirtyList(p);
32955     p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
32956     if( p->nRef==0 ){
32957       pcacheUnpin(p);
32958     }
32959   }
32960 }
32961
32962 /*
32963 ** Make every page in the cache clean.
32964 */
32965 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
32966   PgHdr *p;
32967   while( (p = pCache->pDirty)!=0 ){
32968     sqlite3PcacheMakeClean(p);
32969   }
32970 }
32971
32972 /*
32973 ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
32974 */
32975 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
32976   PgHdr *p;
32977   for(p=pCache->pDirty; p; p=p->pDirtyNext){
32978     p->flags &= ~PGHDR_NEED_SYNC;
32979   }
32980   pCache->pSynced = pCache->pDirtyTail;
32981 }
32982
32983 /*
32984 ** Change the page number of page p to newPgno. 
32985 */
32986 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
32987   PCache *pCache = p->pCache;
32988   assert( p->nRef>0 );
32989   assert( newPgno>0 );
32990   sqlite3GlobalConfig.pcache.xRekey(pCache->pCache, p, p->pgno, newPgno);
32991   p->pgno = newPgno;
32992   if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
32993     pcacheRemoveFromDirtyList(p);
32994     pcacheAddToDirtyList(p);
32995   }
32996 }
32997
32998 /*
32999 ** Drop every cache entry whose page number is greater than "pgno". The
33000 ** caller must ensure that there are no outstanding references to any pages
33001 ** other than page 1 with a page number greater than pgno.
33002 **
33003 ** If there is a reference to page 1 and the pgno parameter passed to this
33004 ** function is 0, then the data area associated with page 1 is zeroed, but
33005 ** the page object is not dropped.
33006 */
33007 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
33008   if( pCache->pCache ){
33009     PgHdr *p;
33010     PgHdr *pNext;
33011     for(p=pCache->pDirty; p; p=pNext){
33012       pNext = p->pDirtyNext;
33013       /* This routine never gets call with a positive pgno except right
33014       ** after sqlite3PcacheCleanAll().  So if there are dirty pages,
33015       ** it must be that pgno==0.
33016       */
33017       assert( p->pgno>0 );
33018       if( ALWAYS(p->pgno>pgno) ){
33019         assert( p->flags&PGHDR_DIRTY );
33020         sqlite3PcacheMakeClean(p);
33021       }
33022     }
33023     if( pgno==0 && pCache->pPage1 ){
33024       memset(pCache->pPage1->pData, 0, pCache->szPage);
33025       pgno = 1;
33026     }
33027     sqlite3GlobalConfig.pcache.xTruncate(pCache->pCache, pgno+1);
33028   }
33029 }
33030
33031 /*
33032 ** Close a cache.
33033 */
33034 SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
33035   if( pCache->pCache ){
33036     sqlite3GlobalConfig.pcache.xDestroy(pCache->pCache);
33037   }
33038 }
33039
33040 /* 
33041 ** Discard the contents of the cache.
33042 */
33043 SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
33044   sqlite3PcacheTruncate(pCache, 0);
33045 }
33046
33047 /*
33048 ** Merge two lists of pages connected by pDirty and in pgno order.
33049 ** Do not both fixing the pDirtyPrev pointers.
33050 */
33051 static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
33052   PgHdr result, *pTail;
33053   pTail = &result;
33054   while( pA && pB ){
33055     if( pA->pgno<pB->pgno ){
33056       pTail->pDirty = pA;
33057       pTail = pA;
33058       pA = pA->pDirty;
33059     }else{
33060       pTail->pDirty = pB;
33061       pTail = pB;
33062       pB = pB->pDirty;
33063     }
33064   }
33065   if( pA ){
33066     pTail->pDirty = pA;
33067   }else if( pB ){
33068     pTail->pDirty = pB;
33069   }else{
33070     pTail->pDirty = 0;
33071   }
33072   return result.pDirty;
33073 }
33074
33075 /*
33076 ** Sort the list of pages in accending order by pgno.  Pages are
33077 ** connected by pDirty pointers.  The pDirtyPrev pointers are
33078 ** corrupted by this sort.
33079 **
33080 ** Since there cannot be more than 2^31 distinct pages in a database,
33081 ** there cannot be more than 31 buckets required by the merge sorter.
33082 ** One extra bucket is added to catch overflow in case something
33083 ** ever changes to make the previous sentence incorrect.
33084 */
33085 #define N_SORT_BUCKET  32
33086 static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
33087   PgHdr *a[N_SORT_BUCKET], *p;
33088   int i;
33089   memset(a, 0, sizeof(a));
33090   while( pIn ){
33091     p = pIn;
33092     pIn = p->pDirty;
33093     p->pDirty = 0;
33094     for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
33095       if( a[i]==0 ){
33096         a[i] = p;
33097         break;
33098       }else{
33099         p = pcacheMergeDirtyList(a[i], p);
33100         a[i] = 0;
33101       }
33102     }
33103     if( NEVER(i==N_SORT_BUCKET-1) ){
33104       /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
33105       ** the input list.  But that is impossible.
33106       */
33107       a[i] = pcacheMergeDirtyList(a[i], p);
33108     }
33109   }
33110   p = a[0];
33111   for(i=1; i<N_SORT_BUCKET; i++){
33112     p = pcacheMergeDirtyList(p, a[i]);
33113   }
33114   return p;
33115 }
33116
33117 /*
33118 ** Return a list of all dirty pages in the cache, sorted by page number.
33119 */
33120 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
33121   PgHdr *p;
33122   for(p=pCache->pDirty; p; p=p->pDirtyNext){
33123     p->pDirty = p->pDirtyNext;
33124   }
33125   return pcacheSortDirtyList(pCache->pDirty);
33126 }
33127
33128 /* 
33129 ** Return the total number of referenced pages held by the cache.
33130 */
33131 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
33132   return pCache->nRef;
33133 }
33134
33135 /*
33136 ** Return the number of references to the page supplied as an argument.
33137 */
33138 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
33139   return p->nRef;
33140 }
33141
33142 /* 
33143 ** Return the total number of pages in the cache.
33144 */
33145 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
33146   int nPage = 0;
33147   if( pCache->pCache ){
33148     nPage = sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache);
33149   }
33150   return nPage;
33151 }
33152
33153 #ifdef SQLITE_TEST
33154 /*
33155 ** Get the suggested cache-size value.
33156 */
33157 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
33158   return pCache->nMax;
33159 }
33160 #endif
33161
33162 /*
33163 ** Set the suggested cache-size value.
33164 */
33165 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
33166   pCache->nMax = mxPage;
33167   if( pCache->pCache ){
33168     sqlite3GlobalConfig.pcache.xCachesize(pCache->pCache, mxPage);
33169   }
33170 }
33171
33172 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
33173 /*
33174 ** For all dirty pages currently in the cache, invoke the specified
33175 ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
33176 ** defined.
33177 */
33178 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
33179   PgHdr *pDirty;
33180   for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
33181     xIter(pDirty);
33182   }
33183 }
33184 #endif
33185
33186 /************** End of pcache.c **********************************************/
33187 /************** Begin file pcache1.c *****************************************/
33188 /*
33189 ** 2008 November 05
33190 **
33191 ** The author disclaims copyright to this source code.  In place of
33192 ** a legal notice, here is a blessing:
33193 **
33194 **    May you do good and not evil.
33195 **    May you find forgiveness for yourself and forgive others.
33196 **    May you share freely, never taking more than you give.
33197 **
33198 *************************************************************************
33199 **
33200 ** This file implements the default page cache implementation (the
33201 ** sqlite3_pcache interface). It also contains part of the implementation
33202 ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
33203 ** If the default page cache implementation is overriden, then neither of
33204 ** these two features are available.
33205 */
33206
33207
33208 typedef struct PCache1 PCache1;
33209 typedef struct PgHdr1 PgHdr1;
33210 typedef struct PgFreeslot PgFreeslot;
33211
33212 /* Each page cache is an instance of the following object.  Every
33213 ** open database file (including each in-memory database and each
33214 ** temporary or transient database) has a single page cache which
33215 ** is an instance of this object.
33216 **
33217 ** Pointers to structures of this type are cast and returned as 
33218 ** opaque sqlite3_pcache* handles.
33219 */
33220 struct PCache1 {
33221   /* Cache configuration parameters. Page size (szPage) and the purgeable
33222   ** flag (bPurgeable) are set when the cache is created. nMax may be 
33223   ** modified at any time by a call to the pcache1CacheSize() method.
33224   ** The global mutex must be held when accessing nMax.
33225   */
33226   int szPage;                         /* Size of allocated pages in bytes */
33227   int bPurgeable;                     /* True if cache is purgeable */
33228   unsigned int nMin;                  /* Minimum number of pages reserved */
33229   unsigned int nMax;                  /* Configured "cache_size" value */
33230
33231   /* Hash table of all pages. The following variables may only be accessed
33232   ** when the accessor is holding the global mutex (see pcache1EnterMutex() 
33233   ** and pcache1LeaveMutex()).
33234   */
33235   unsigned int nRecyclable;           /* Number of pages in the LRU list */
33236   unsigned int nPage;                 /* Total number of pages in apHash */
33237   unsigned int nHash;                 /* Number of slots in apHash[] */
33238   PgHdr1 **apHash;                    /* Hash table for fast lookup by key */
33239
33240   unsigned int iMaxKey;               /* Largest key seen since xTruncate() */
33241 };
33242
33243 /*
33244 ** Each cache entry is represented by an instance of the following 
33245 ** structure. A buffer of PgHdr1.pCache->szPage bytes is allocated 
33246 ** directly before this structure in memory (see the PGHDR1_TO_PAGE() 
33247 ** macro below).
33248 */
33249 struct PgHdr1 {
33250   unsigned int iKey;             /* Key value (page number) */
33251   PgHdr1 *pNext;                 /* Next in hash table chain */
33252   PCache1 *pCache;               /* Cache that currently owns this page */
33253   PgHdr1 *pLruNext;              /* Next in LRU list of unpinned pages */
33254   PgHdr1 *pLruPrev;              /* Previous in LRU list of unpinned pages */
33255 };
33256
33257 /*
33258 ** Free slots in the allocator used to divide up the buffer provided using
33259 ** the SQLITE_CONFIG_PAGECACHE mechanism.
33260 */
33261 struct PgFreeslot {
33262   PgFreeslot *pNext;  /* Next free slot */
33263 };
33264
33265 /*
33266 ** Global data used by this cache.
33267 */
33268 static SQLITE_WSD struct PCacheGlobal {
33269   sqlite3_mutex *mutex;               /* static mutex MUTEX_STATIC_LRU */
33270
33271   int nMaxPage;                       /* Sum of nMaxPage for purgeable caches */
33272   int nMinPage;                       /* Sum of nMinPage for purgeable caches */
33273   int nCurrentPage;                   /* Number of purgeable pages allocated */
33274   PgHdr1 *pLruHead, *pLruTail;        /* LRU list of unpinned pages */
33275
33276   /* Variables related to SQLITE_CONFIG_PAGECACHE settings. */
33277   int szSlot;                         /* Size of each free slot */
33278   int nSlot;                          /* The number of pcache slots */
33279   int nFreeSlot;                      /* Number of unused pcache slots */
33280   int nReserve;                       /* Try to keep nFreeSlot above this */
33281   void *pStart, *pEnd;                /* Bounds of pagecache malloc range */
33282   PgFreeslot *pFree;                  /* Free page blocks */
33283   int isInit;                         /* True if initialized */
33284 } pcache1_g;
33285
33286 /*
33287 ** All code in this file should access the global structure above via the
33288 ** alias "pcache1". This ensures that the WSD emulation is used when
33289 ** compiling for systems that do not support real WSD.
33290 */
33291 #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
33292
33293 /*
33294 ** When a PgHdr1 structure is allocated, the associated PCache1.szPage
33295 ** bytes of data are located directly before it in memory (i.e. the total
33296 ** size of the allocation is sizeof(PgHdr1)+PCache1.szPage byte). The
33297 ** PGHDR1_TO_PAGE() macro takes a pointer to a PgHdr1 structure as
33298 ** an argument and returns a pointer to the associated block of szPage
33299 ** bytes. The PAGE_TO_PGHDR1() macro does the opposite: its argument is
33300 ** a pointer to a block of szPage bytes of data and the return value is
33301 ** a pointer to the associated PgHdr1 structure.
33302 **
33303 **   assert( PGHDR1_TO_PAGE(PAGE_TO_PGHDR1(pCache, X))==X );
33304 */
33305 #define PGHDR1_TO_PAGE(p)    (void*)(((char*)p) - p->pCache->szPage)
33306 #define PAGE_TO_PGHDR1(c, p) (PgHdr1*)(((char*)p) + c->szPage)
33307
33308 /*
33309 ** Macros to enter and leave the global LRU mutex.
33310 */
33311 #define pcache1EnterMutex() sqlite3_mutex_enter(pcache1.mutex)
33312 #define pcache1LeaveMutex() sqlite3_mutex_leave(pcache1.mutex)
33313
33314 /******************************************************************************/
33315 /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
33316
33317 /*
33318 ** This function is called during initialization if a static buffer is 
33319 ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
33320 ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
33321 ** enough to contain 'n' buffers of 'sz' bytes each.
33322 */
33323 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
33324   if( pcache1.isInit ){
33325     PgFreeslot *p;
33326     sz = ROUNDDOWN8(sz);
33327     pcache1.szSlot = sz;
33328     pcache1.nSlot = pcache1.nFreeSlot = n;
33329     pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
33330     pcache1.pStart = pBuf;
33331     pcache1.pFree = 0;
33332     while( n-- ){
33333       p = (PgFreeslot*)pBuf;
33334       p->pNext = pcache1.pFree;
33335       pcache1.pFree = p;
33336       pBuf = (void*)&((char*)pBuf)[sz];
33337     }
33338     pcache1.pEnd = pBuf;
33339   }
33340 }
33341
33342 /*
33343 ** Malloc function used within this file to allocate space from the buffer
33344 ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no 
33345 ** such buffer exists or there is no space left in it, this function falls 
33346 ** back to sqlite3Malloc().
33347 */
33348 static void *pcache1Alloc(int nByte){
33349   void *p;
33350   assert( sqlite3_mutex_held(pcache1.mutex) );
33351   sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
33352   if( nByte<=pcache1.szSlot && pcache1.pFree ){
33353     assert( pcache1.isInit );
33354     p = (PgHdr1 *)pcache1.pFree;
33355     pcache1.pFree = pcache1.pFree->pNext;
33356     pcache1.nFreeSlot--;
33357     assert( pcache1.nFreeSlot>=0 );
33358     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
33359   }else{
33360
33361     /* Allocate a new buffer using sqlite3Malloc. Before doing so, exit the
33362     ** global pcache mutex and unlock the pager-cache object pCache. This is 
33363     ** so that if the attempt to allocate a new buffer causes the the 
33364     ** configured soft-heap-limit to be breached, it will be possible to
33365     ** reclaim memory from this pager-cache.
33366     */
33367     pcache1LeaveMutex();
33368     p = sqlite3Malloc(nByte);
33369     pcache1EnterMutex();
33370     if( p ){
33371       int sz = sqlite3MallocSize(p);
33372       sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
33373     }
33374     sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
33375   }
33376   return p;
33377 }
33378
33379 /*
33380 ** Free an allocated buffer obtained from pcache1Alloc().
33381 */
33382 static void pcache1Free(void *p){
33383   assert( sqlite3_mutex_held(pcache1.mutex) );
33384   if( p==0 ) return;
33385   if( p>=pcache1.pStart && p<pcache1.pEnd ){
33386     PgFreeslot *pSlot;
33387     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
33388     pSlot = (PgFreeslot*)p;
33389     pSlot->pNext = pcache1.pFree;
33390     pcache1.pFree = pSlot;
33391     pcache1.nFreeSlot++;
33392     assert( pcache1.nFreeSlot<=pcache1.nSlot );
33393   }else{
33394     int iSize;
33395     assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
33396     sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
33397     iSize = sqlite3MallocSize(p);
33398     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -iSize);
33399     sqlite3_free(p);
33400   }
33401 }
33402
33403 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
33404 /*
33405 ** Return the size of a pcache allocation
33406 */
33407 static int pcache1MemSize(void *p){
33408   assert( sqlite3_mutex_held(pcache1.mutex) );
33409   if( p>=pcache1.pStart && p<pcache1.pEnd ){
33410     return pcache1.szSlot;
33411   }else{
33412     int iSize;
33413     assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
33414     sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
33415     iSize = sqlite3MallocSize(p);
33416     sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
33417     return iSize;
33418   }
33419 }
33420 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
33421
33422 /*
33423 ** Allocate a new page object initially associated with cache pCache.
33424 */
33425 static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
33426   int nByte = sizeof(PgHdr1) + pCache->szPage;
33427   void *pPg = pcache1Alloc(nByte);
33428   PgHdr1 *p;
33429   if( pPg ){
33430     p = PAGE_TO_PGHDR1(pCache, pPg);
33431     if( pCache->bPurgeable ){
33432       pcache1.nCurrentPage++;
33433     }
33434   }else{
33435     p = 0;
33436   }
33437   return p;
33438 }
33439
33440 /*
33441 ** Free a page object allocated by pcache1AllocPage().
33442 **
33443 ** The pointer is allowed to be NULL, which is prudent.  But it turns out
33444 ** that the current implementation happens to never call this routine
33445 ** with a NULL pointer, so we mark the NULL test with ALWAYS().
33446 */
33447 static void pcache1FreePage(PgHdr1 *p){
33448   if( ALWAYS(p) ){
33449     if( p->pCache->bPurgeable ){
33450       pcache1.nCurrentPage--;
33451     }
33452     pcache1Free(PGHDR1_TO_PAGE(p));
33453   }
33454 }
33455
33456 /*
33457 ** Malloc function used by SQLite to obtain space from the buffer configured
33458 ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
33459 ** exists, this function falls back to sqlite3Malloc().
33460 */
33461 SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
33462   void *p;
33463   pcache1EnterMutex();
33464   p = pcache1Alloc(sz);
33465   pcache1LeaveMutex();
33466   return p;
33467 }
33468
33469 /*
33470 ** Free an allocated buffer obtained from sqlite3PageMalloc().
33471 */
33472 SQLITE_PRIVATE void sqlite3PageFree(void *p){
33473   pcache1EnterMutex();
33474   pcache1Free(p);
33475   pcache1LeaveMutex();
33476 }
33477
33478
33479 /*
33480 ** Return true if it desirable to avoid allocating a new page cache
33481 ** entry.
33482 **
33483 ** If memory was allocated specifically to the page cache using
33484 ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
33485 ** it is desirable to avoid allocating a new page cache entry because
33486 ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
33487 ** for all page cache needs and we should not need to spill the
33488 ** allocation onto the heap.
33489 **
33490 ** Or, the heap is used for all page cache memory put the heap is
33491 ** under memory pressure, then again it is desirable to avoid
33492 ** allocating a new page cache entry in order to avoid stressing
33493 ** the heap even further.
33494 */
33495 static int pcache1UnderMemoryPressure(PCache1 *pCache){
33496   assert( sqlite3_mutex_held(pcache1.mutex) );
33497   if( pcache1.nSlot && pCache->szPage<=pcache1.szSlot ){
33498     return pcache1.nFreeSlot<pcache1.nReserve;
33499   }else{
33500     return sqlite3HeapNearlyFull();
33501   }
33502 }
33503
33504 /******************************************************************************/
33505 /******** General Implementation Functions ************************************/
33506
33507 /*
33508 ** This function is used to resize the hash table used by the cache passed
33509 ** as the first argument.
33510 **
33511 ** The global mutex must be held when this function is called.
33512 */
33513 static int pcache1ResizeHash(PCache1 *p){
33514   PgHdr1 **apNew;
33515   unsigned int nNew;
33516   unsigned int i;
33517
33518   assert( sqlite3_mutex_held(pcache1.mutex) );
33519
33520   nNew = p->nHash*2;
33521   if( nNew<256 ){
33522     nNew = 256;
33523   }
33524
33525   pcache1LeaveMutex();
33526   if( p->nHash ){ sqlite3BeginBenignMalloc(); }
33527   apNew = (PgHdr1 **)sqlite3_malloc(sizeof(PgHdr1 *)*nNew);
33528   if( p->nHash ){ sqlite3EndBenignMalloc(); }
33529   pcache1EnterMutex();
33530   if( apNew ){
33531     memset(apNew, 0, sizeof(PgHdr1 *)*nNew);
33532     for(i=0; i<p->nHash; i++){
33533       PgHdr1 *pPage;
33534       PgHdr1 *pNext = p->apHash[i];
33535       while( (pPage = pNext)!=0 ){
33536         unsigned int h = pPage->iKey % nNew;
33537         pNext = pPage->pNext;
33538         pPage->pNext = apNew[h];
33539         apNew[h] = pPage;
33540       }
33541     }
33542     sqlite3_free(p->apHash);
33543     p->apHash = apNew;
33544     p->nHash = nNew;
33545   }
33546
33547   return (p->apHash ? SQLITE_OK : SQLITE_NOMEM);
33548 }
33549
33550 /*
33551 ** This function is used internally to remove the page pPage from the 
33552 ** global LRU list, if is part of it. If pPage is not part of the global
33553 ** LRU list, then this function is a no-op.
33554 **
33555 ** The global mutex must be held when this function is called.
33556 */
33557 static void pcache1PinPage(PgHdr1 *pPage){
33558   assert( sqlite3_mutex_held(pcache1.mutex) );
33559   if( pPage && (pPage->pLruNext || pPage==pcache1.pLruTail) ){
33560     if( pPage->pLruPrev ){
33561       pPage->pLruPrev->pLruNext = pPage->pLruNext;
33562     }
33563     if( pPage->pLruNext ){
33564       pPage->pLruNext->pLruPrev = pPage->pLruPrev;
33565     }
33566     if( pcache1.pLruHead==pPage ){
33567       pcache1.pLruHead = pPage->pLruNext;
33568     }
33569     if( pcache1.pLruTail==pPage ){
33570       pcache1.pLruTail = pPage->pLruPrev;
33571     }
33572     pPage->pLruNext = 0;
33573     pPage->pLruPrev = 0;
33574     pPage->pCache->nRecyclable--;
33575   }
33576 }
33577
33578
33579 /*
33580 ** Remove the page supplied as an argument from the hash table 
33581 ** (PCache1.apHash structure) that it is currently stored in.
33582 **
33583 ** The global mutex must be held when this function is called.
33584 */
33585 static void pcache1RemoveFromHash(PgHdr1 *pPage){
33586   unsigned int h;
33587   PCache1 *pCache = pPage->pCache;
33588   PgHdr1 **pp;
33589
33590   h = pPage->iKey % pCache->nHash;
33591   for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
33592   *pp = (*pp)->pNext;
33593
33594   pCache->nPage--;
33595 }
33596
33597 /*
33598 ** If there are currently more than pcache.nMaxPage pages allocated, try
33599 ** to recycle pages to reduce the number allocated to pcache.nMaxPage.
33600 */
33601 static void pcache1EnforceMaxPage(void){
33602   assert( sqlite3_mutex_held(pcache1.mutex) );
33603   while( pcache1.nCurrentPage>pcache1.nMaxPage && pcache1.pLruTail ){
33604     PgHdr1 *p = pcache1.pLruTail;
33605     pcache1PinPage(p);
33606     pcache1RemoveFromHash(p);
33607     pcache1FreePage(p);
33608   }
33609 }
33610
33611 /*
33612 ** Discard all pages from cache pCache with a page number (key value) 
33613 ** greater than or equal to iLimit. Any pinned pages that meet this 
33614 ** criteria are unpinned before they are discarded.
33615 **
33616 ** The global mutex must be held when this function is called.
33617 */
33618 static void pcache1TruncateUnsafe(
33619   PCache1 *pCache, 
33620   unsigned int iLimit 
33621 ){
33622   TESTONLY( unsigned int nPage = 0; )      /* Used to assert pCache->nPage is correct */
33623   unsigned int h;
33624   assert( sqlite3_mutex_held(pcache1.mutex) );
33625   for(h=0; h<pCache->nHash; h++){
33626     PgHdr1 **pp = &pCache->apHash[h]; 
33627     PgHdr1 *pPage;
33628     while( (pPage = *pp)!=0 ){
33629       if( pPage->iKey>=iLimit ){
33630         pCache->nPage--;
33631         *pp = pPage->pNext;
33632         pcache1PinPage(pPage);
33633         pcache1FreePage(pPage);
33634       }else{
33635         pp = &pPage->pNext;
33636         TESTONLY( nPage++; )
33637       }
33638     }
33639   }
33640   assert( pCache->nPage==nPage );
33641 }
33642
33643 /******************************************************************************/
33644 /******** sqlite3_pcache Methods **********************************************/
33645
33646 /*
33647 ** Implementation of the sqlite3_pcache.xInit method.
33648 */
33649 static int pcache1Init(void *NotUsed){
33650   UNUSED_PARAMETER(NotUsed);
33651   assert( pcache1.isInit==0 );
33652   memset(&pcache1, 0, sizeof(pcache1));
33653   if( sqlite3GlobalConfig.bCoreMutex ){
33654     pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
33655   }
33656   pcache1.isInit = 1;
33657   return SQLITE_OK;
33658 }
33659
33660 /*
33661 ** Implementation of the sqlite3_pcache.xShutdown method.
33662 ** Note that the static mutex allocated in xInit does 
33663 ** not need to be freed.
33664 */
33665 static void pcache1Shutdown(void *NotUsed){
33666   UNUSED_PARAMETER(NotUsed);
33667   assert( pcache1.isInit!=0 );
33668   memset(&pcache1, 0, sizeof(pcache1));
33669 }
33670
33671 /*
33672 ** Implementation of the sqlite3_pcache.xCreate method.
33673 **
33674 ** Allocate a new cache.
33675 */
33676 static sqlite3_pcache *pcache1Create(int szPage, int bPurgeable){
33677   PCache1 *pCache;
33678
33679   pCache = (PCache1 *)sqlite3_malloc(sizeof(PCache1));
33680   if( pCache ){
33681     memset(pCache, 0, sizeof(PCache1));
33682     pCache->szPage = szPage;
33683     pCache->bPurgeable = (bPurgeable ? 1 : 0);
33684     if( bPurgeable ){
33685       pCache->nMin = 10;
33686       pcache1EnterMutex();
33687       pcache1.nMinPage += pCache->nMin;
33688       pcache1LeaveMutex();
33689     }
33690   }
33691   return (sqlite3_pcache *)pCache;
33692 }
33693
33694 /*
33695 ** Implementation of the sqlite3_pcache.xCachesize method. 
33696 **
33697 ** Configure the cache_size limit for a cache.
33698 */
33699 static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
33700   PCache1 *pCache = (PCache1 *)p;
33701   if( pCache->bPurgeable ){
33702     pcache1EnterMutex();
33703     pcache1.nMaxPage += (nMax - pCache->nMax);
33704     pCache->nMax = nMax;
33705     pcache1EnforceMaxPage();
33706     pcache1LeaveMutex();
33707   }
33708 }
33709
33710 /*
33711 ** Implementation of the sqlite3_pcache.xPagecount method. 
33712 */
33713 static int pcache1Pagecount(sqlite3_pcache *p){
33714   int n;
33715   pcache1EnterMutex();
33716   n = ((PCache1 *)p)->nPage;
33717   pcache1LeaveMutex();
33718   return n;
33719 }
33720
33721 /*
33722 ** Implementation of the sqlite3_pcache.xFetch method. 
33723 **
33724 ** Fetch a page by key value.
33725 **
33726 ** Whether or not a new page may be allocated by this function depends on
33727 ** the value of the createFlag argument.  0 means do not allocate a new
33728 ** page.  1 means allocate a new page if space is easily available.  2 
33729 ** means to try really hard to allocate a new page.
33730 **
33731 ** For a non-purgeable cache (a cache used as the storage for an in-memory
33732 ** database) there is really no difference between createFlag 1 and 2.  So
33733 ** the calling function (pcache.c) will never have a createFlag of 1 on
33734 ** a non-purgable cache.
33735 **
33736 ** There are three different approaches to obtaining space for a page,
33737 ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
33738 **
33739 **   1. Regardless of the value of createFlag, the cache is searched for a 
33740 **      copy of the requested page. If one is found, it is returned.
33741 **
33742 **   2. If createFlag==0 and the page is not already in the cache, NULL is
33743 **      returned.
33744 **
33745 **   3. If createFlag is 1, and the page is not already in the cache, then
33746 **      return NULL (do not allocate a new page) if any of the following
33747 **      conditions are true:
33748 **
33749 **       (a) the number of pages pinned by the cache is greater than
33750 **           PCache1.nMax, or
33751 **
33752 **       (b) the number of pages pinned by the cache is greater than
33753 **           the sum of nMax for all purgeable caches, less the sum of 
33754 **           nMin for all other purgeable caches, or
33755 **
33756 **   4. If none of the first three conditions apply and the cache is marked
33757 **      as purgeable, and if one of the following is true:
33758 **
33759 **       (a) The number of pages allocated for the cache is already 
33760 **           PCache1.nMax, or
33761 **
33762 **       (b) The number of pages allocated for all purgeable caches is
33763 **           already equal to or greater than the sum of nMax for all
33764 **           purgeable caches,
33765 **
33766 **       (c) The system is under memory pressure and wants to avoid
33767 **           unnecessary pages cache entry allocations
33768 **
33769 **      then attempt to recycle a page from the LRU list. If it is the right
33770 **      size, return the recycled buffer. Otherwise, free the buffer and
33771 **      proceed to step 5. 
33772 **
33773 **   5. Otherwise, allocate and return a new page buffer.
33774 */
33775 static void *pcache1Fetch(sqlite3_pcache *p, unsigned int iKey, int createFlag){
33776   unsigned int nPinned;
33777   PCache1 *pCache = (PCache1 *)p;
33778   PgHdr1 *pPage = 0;
33779
33780   assert( pCache->bPurgeable || createFlag!=1 );
33781   pcache1EnterMutex();
33782   if( createFlag==1 ) sqlite3BeginBenignMalloc();
33783
33784   /* Search the hash table for an existing entry. */
33785   if( pCache->nHash>0 ){
33786     unsigned int h = iKey % pCache->nHash;
33787     for(pPage=pCache->apHash[h]; pPage&&pPage->iKey!=iKey; pPage=pPage->pNext);
33788   }
33789
33790   if( pPage || createFlag==0 ){
33791     pcache1PinPage(pPage);
33792     goto fetch_out;
33793   }
33794
33795   /* Step 3 of header comment. */
33796   nPinned = pCache->nPage - pCache->nRecyclable;
33797   if( createFlag==1 && (
33798         nPinned>=(pcache1.nMaxPage+pCache->nMin-pcache1.nMinPage)
33799      || nPinned>=(pCache->nMax * 9 / 10)
33800      || pcache1UnderMemoryPressure(pCache)
33801   )){
33802     goto fetch_out;
33803   }
33804
33805   if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){
33806     goto fetch_out;
33807   }
33808
33809   /* Step 4. Try to recycle a page buffer if appropriate. */
33810   if( pCache->bPurgeable && pcache1.pLruTail && (
33811          (pCache->nPage+1>=pCache->nMax)
33812       || pcache1.nCurrentPage>=pcache1.nMaxPage
33813       || pcache1UnderMemoryPressure(pCache)
33814   )){
33815     pPage = pcache1.pLruTail;
33816     pcache1RemoveFromHash(pPage);
33817     pcache1PinPage(pPage);
33818     if( pPage->pCache->szPage!=pCache->szPage ){
33819       pcache1FreePage(pPage);
33820       pPage = 0;
33821     }else{
33822       pcache1.nCurrentPage -= (pPage->pCache->bPurgeable - pCache->bPurgeable);
33823     }
33824   }
33825
33826   /* Step 5. If a usable page buffer has still not been found, 
33827   ** attempt to allocate a new one. 
33828   */
33829   if( !pPage ){
33830     pPage = pcache1AllocPage(pCache);
33831   }
33832
33833   if( pPage ){
33834     unsigned int h = iKey % pCache->nHash;
33835     pCache->nPage++;
33836     pPage->iKey = iKey;
33837     pPage->pNext = pCache->apHash[h];
33838     pPage->pCache = pCache;
33839     pPage->pLruPrev = 0;
33840     pPage->pLruNext = 0;
33841     *(void **)(PGHDR1_TO_PAGE(pPage)) = 0;
33842     pCache->apHash[h] = pPage;
33843   }
33844
33845 fetch_out:
33846   if( pPage && iKey>pCache->iMaxKey ){
33847     pCache->iMaxKey = iKey;
33848   }
33849   if( createFlag==1 ) sqlite3EndBenignMalloc();
33850   pcache1LeaveMutex();
33851   return (pPage ? PGHDR1_TO_PAGE(pPage) : 0);
33852 }
33853
33854
33855 /*
33856 ** Implementation of the sqlite3_pcache.xUnpin method.
33857 **
33858 ** Mark a page as unpinned (eligible for asynchronous recycling).
33859 */
33860 static void pcache1Unpin(sqlite3_pcache *p, void *pPg, int reuseUnlikely){
33861   PCache1 *pCache = (PCache1 *)p;
33862   PgHdr1 *pPage = PAGE_TO_PGHDR1(pCache, pPg);
33863  
33864   assert( pPage->pCache==pCache );
33865   pcache1EnterMutex();
33866
33867   /* It is an error to call this function if the page is already 
33868   ** part of the global LRU list.
33869   */
33870   assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
33871   assert( pcache1.pLruHead!=pPage && pcache1.pLruTail!=pPage );
33872
33873   if( reuseUnlikely || pcache1.nCurrentPage>pcache1.nMaxPage ){
33874     pcache1RemoveFromHash(pPage);
33875     pcache1FreePage(pPage);
33876   }else{
33877     /* Add the page to the global LRU list. Normally, the page is added to
33878     ** the head of the list (last page to be recycled). However, if the 
33879     ** reuseUnlikely flag passed to this function is true, the page is added
33880     ** to the tail of the list (first page to be recycled).
33881     */
33882     if( pcache1.pLruHead ){
33883       pcache1.pLruHead->pLruPrev = pPage;
33884       pPage->pLruNext = pcache1.pLruHead;
33885       pcache1.pLruHead = pPage;
33886     }else{
33887       pcache1.pLruTail = pPage;
33888       pcache1.pLruHead = pPage;
33889     }
33890     pCache->nRecyclable++;
33891   }
33892
33893   pcache1LeaveMutex();
33894 }
33895
33896 /*
33897 ** Implementation of the sqlite3_pcache.xRekey method. 
33898 */
33899 static void pcache1Rekey(
33900   sqlite3_pcache *p,
33901   void *pPg,
33902   unsigned int iOld,
33903   unsigned int iNew
33904 ){
33905   PCache1 *pCache = (PCache1 *)p;
33906   PgHdr1 *pPage = PAGE_TO_PGHDR1(pCache, pPg);
33907   PgHdr1 **pp;
33908   unsigned int h; 
33909   assert( pPage->iKey==iOld );
33910   assert( pPage->pCache==pCache );
33911
33912   pcache1EnterMutex();
33913
33914   h = iOld%pCache->nHash;
33915   pp = &pCache->apHash[h];
33916   while( (*pp)!=pPage ){
33917     pp = &(*pp)->pNext;
33918   }
33919   *pp = pPage->pNext;
33920
33921   h = iNew%pCache->nHash;
33922   pPage->iKey = iNew;
33923   pPage->pNext = pCache->apHash[h];
33924   pCache->apHash[h] = pPage;
33925   if( iNew>pCache->iMaxKey ){
33926     pCache->iMaxKey = iNew;
33927   }
33928
33929   pcache1LeaveMutex();
33930 }
33931
33932 /*
33933 ** Implementation of the sqlite3_pcache.xTruncate method. 
33934 **
33935 ** Discard all unpinned pages in the cache with a page number equal to
33936 ** or greater than parameter iLimit. Any pinned pages with a page number
33937 ** equal to or greater than iLimit are implicitly unpinned.
33938 */
33939 static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
33940   PCache1 *pCache = (PCache1 *)p;
33941   pcache1EnterMutex();
33942   if( iLimit<=pCache->iMaxKey ){
33943     pcache1TruncateUnsafe(pCache, iLimit);
33944     pCache->iMaxKey = iLimit-1;
33945   }
33946   pcache1LeaveMutex();
33947 }
33948
33949 /*
33950 ** Implementation of the sqlite3_pcache.xDestroy method. 
33951 **
33952 ** Destroy a cache allocated using pcache1Create().
33953 */
33954 static void pcache1Destroy(sqlite3_pcache *p){
33955   PCache1 *pCache = (PCache1 *)p;
33956   assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
33957   pcache1EnterMutex();
33958   pcache1TruncateUnsafe(pCache, 0);
33959   pcache1.nMaxPage -= pCache->nMax;
33960   pcache1.nMinPage -= pCache->nMin;
33961   pcache1EnforceMaxPage();
33962   pcache1LeaveMutex();
33963   sqlite3_free(pCache->apHash);
33964   sqlite3_free(pCache);
33965 }
33966
33967 /*
33968 ** This function is called during initialization (sqlite3_initialize()) to
33969 ** install the default pluggable cache module, assuming the user has not
33970 ** already provided an alternative.
33971 */
33972 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
33973   static const sqlite3_pcache_methods defaultMethods = {
33974     0,                       /* pArg */
33975     pcache1Init,             /* xInit */
33976     pcache1Shutdown,         /* xShutdown */
33977     pcache1Create,           /* xCreate */
33978     pcache1Cachesize,        /* xCachesize */
33979     pcache1Pagecount,        /* xPagecount */
33980     pcache1Fetch,            /* xFetch */
33981     pcache1Unpin,            /* xUnpin */
33982     pcache1Rekey,            /* xRekey */
33983     pcache1Truncate,         /* xTruncate */
33984     pcache1Destroy           /* xDestroy */
33985   };
33986   sqlite3_config(SQLITE_CONFIG_PCACHE, &defaultMethods);
33987 }
33988
33989 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
33990 /*
33991 ** This function is called to free superfluous dynamically allocated memory
33992 ** held by the pager system. Memory in use by any SQLite pager allocated
33993 ** by the current thread may be sqlite3_free()ed.
33994 **
33995 ** nReq is the number of bytes of memory required. Once this much has
33996 ** been released, the function returns. The return value is the total number 
33997 ** of bytes of memory released.
33998 */
33999 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
34000   int nFree = 0;
34001   if( pcache1.pStart==0 ){
34002     PgHdr1 *p;
34003     pcache1EnterMutex();
34004     while( (nReq<0 || nFree<nReq) && ((p=pcache1.pLruTail)!=0) ){
34005       nFree += pcache1MemSize(PGHDR1_TO_PAGE(p));
34006       pcache1PinPage(p);
34007       pcache1RemoveFromHash(p);
34008       pcache1FreePage(p);
34009     }
34010     pcache1LeaveMutex();
34011   }
34012   return nFree;
34013 }
34014 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
34015
34016 #ifdef SQLITE_TEST
34017 /*
34018 ** This function is used by test procedures to inspect the internal state
34019 ** of the global cache.
34020 */
34021 SQLITE_PRIVATE void sqlite3PcacheStats(
34022   int *pnCurrent,      /* OUT: Total number of pages cached */
34023   int *pnMax,          /* OUT: Global maximum cache size */
34024   int *pnMin,          /* OUT: Sum of PCache1.nMin for purgeable caches */
34025   int *pnRecyclable    /* OUT: Total number of pages available for recycling */
34026 ){
34027   PgHdr1 *p;
34028   int nRecyclable = 0;
34029   for(p=pcache1.pLruHead; p; p=p->pLruNext){
34030     nRecyclable++;
34031   }
34032   *pnCurrent = pcache1.nCurrentPage;
34033   *pnMax = pcache1.nMaxPage;
34034   *pnMin = pcache1.nMinPage;
34035   *pnRecyclable = nRecyclable;
34036 }
34037 #endif
34038
34039 /************** End of pcache1.c *********************************************/
34040 /************** Begin file rowset.c ******************************************/
34041 /*
34042 ** 2008 December 3
34043 **
34044 ** The author disclaims copyright to this source code.  In place of
34045 ** a legal notice, here is a blessing:
34046 **
34047 **    May you do good and not evil.
34048 **    May you find forgiveness for yourself and forgive others.
34049 **    May you share freely, never taking more than you give.
34050 **
34051 *************************************************************************
34052 **
34053 ** This module implements an object we call a "RowSet".
34054 **
34055 ** The RowSet object is a collection of rowids.  Rowids
34056 ** are inserted into the RowSet in an arbitrary order.  Inserts
34057 ** can be intermixed with tests to see if a given rowid has been
34058 ** previously inserted into the RowSet.
34059 **
34060 ** After all inserts are finished, it is possible to extract the
34061 ** elements of the RowSet in sorted order.  Once this extraction
34062 ** process has started, no new elements may be inserted.
34063 **
34064 ** Hence, the primitive operations for a RowSet are:
34065 **
34066 **    CREATE
34067 **    INSERT
34068 **    TEST
34069 **    SMALLEST
34070 **    DESTROY
34071 **
34072 ** The CREATE and DESTROY primitives are the constructor and destructor,
34073 ** obviously.  The INSERT primitive adds a new element to the RowSet.
34074 ** TEST checks to see if an element is already in the RowSet.  SMALLEST
34075 ** extracts the least value from the RowSet.
34076 **
34077 ** The INSERT primitive might allocate additional memory.  Memory is
34078 ** allocated in chunks so most INSERTs do no allocation.  There is an 
34079 ** upper bound on the size of allocated memory.  No memory is freed
34080 ** until DESTROY.
34081 **
34082 ** The TEST primitive includes a "batch" number.  The TEST primitive
34083 ** will only see elements that were inserted before the last change
34084 ** in the batch number.  In other words, if an INSERT occurs between
34085 ** two TESTs where the TESTs have the same batch nubmer, then the
34086 ** value added by the INSERT will not be visible to the second TEST.
34087 ** The initial batch number is zero, so if the very first TEST contains
34088 ** a non-zero batch number, it will see all prior INSERTs.
34089 **
34090 ** No INSERTs may occurs after a SMALLEST.  An assertion will fail if
34091 ** that is attempted.
34092 **
34093 ** The cost of an INSERT is roughly constant.  (Sometime new memory
34094 ** has to be allocated on an INSERT.)  The cost of a TEST with a new
34095 ** batch number is O(NlogN) where N is the number of elements in the RowSet.
34096 ** The cost of a TEST using the same batch number is O(logN).  The cost
34097 ** of the first SMALLEST is O(NlogN).  Second and subsequent SMALLEST
34098 ** primitives are constant time.  The cost of DESTROY is O(N).
34099 **
34100 ** There is an added cost of O(N) when switching between TEST and
34101 ** SMALLEST primitives.
34102 */
34103
34104
34105 /*
34106 ** Target size for allocation chunks.
34107 */
34108 #define ROWSET_ALLOCATION_SIZE 1024
34109
34110 /*
34111 ** The number of rowset entries per allocation chunk.
34112 */
34113 #define ROWSET_ENTRY_PER_CHUNK  \
34114                        ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
34115
34116 /*
34117 ** Each entry in a RowSet is an instance of the following object.
34118 */
34119 struct RowSetEntry {            
34120   i64 v;                        /* ROWID value for this entry */
34121   struct RowSetEntry *pRight;   /* Right subtree (larger entries) or list */
34122   struct RowSetEntry *pLeft;    /* Left subtree (smaller entries) */
34123 };
34124
34125 /*
34126 ** RowSetEntry objects are allocated in large chunks (instances of the
34127 ** following structure) to reduce memory allocation overhead.  The
34128 ** chunks are kept on a linked list so that they can be deallocated
34129 ** when the RowSet is destroyed.
34130 */
34131 struct RowSetChunk {
34132   struct RowSetChunk *pNextChunk;        /* Next chunk on list of them all */
34133   struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
34134 };
34135
34136 /*
34137 ** A RowSet in an instance of the following structure.
34138 **
34139 ** A typedef of this structure if found in sqliteInt.h.
34140 */
34141 struct RowSet {
34142   struct RowSetChunk *pChunk;    /* List of all chunk allocations */
34143   sqlite3 *db;                   /* The database connection */
34144   struct RowSetEntry *pEntry;    /* List of entries using pRight */
34145   struct RowSetEntry *pLast;     /* Last entry on the pEntry list */
34146   struct RowSetEntry *pFresh;    /* Source of new entry objects */
34147   struct RowSetEntry *pTree;     /* Binary tree of entries */
34148   u16 nFresh;                    /* Number of objects on pFresh */
34149   u8 isSorted;                   /* True if pEntry is sorted */
34150   u8 iBatch;                     /* Current insert batch */
34151 };
34152
34153 /*
34154 ** Turn bulk memory into a RowSet object.  N bytes of memory
34155 ** are available at pSpace.  The db pointer is used as a memory context
34156 ** for any subsequent allocations that need to occur.
34157 ** Return a pointer to the new RowSet object.
34158 **
34159 ** It must be the case that N is sufficient to make a Rowset.  If not
34160 ** an assertion fault occurs.
34161 ** 
34162 ** If N is larger than the minimum, use the surplus as an initial
34163 ** allocation of entries available to be filled.
34164 */
34165 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
34166   RowSet *p;
34167   assert( N >= ROUND8(sizeof(*p)) );
34168   p = pSpace;
34169   p->pChunk = 0;
34170   p->db = db;
34171   p->pEntry = 0;
34172   p->pLast = 0;
34173   p->pTree = 0;
34174   p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
34175   p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
34176   p->isSorted = 1;
34177   p->iBatch = 0;
34178   return p;
34179 }
34180
34181 /*
34182 ** Deallocate all chunks from a RowSet.  This frees all memory that
34183 ** the RowSet has allocated over its lifetime.  This routine is
34184 ** the destructor for the RowSet.
34185 */
34186 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
34187   struct RowSetChunk *pChunk, *pNextChunk;
34188   for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
34189     pNextChunk = pChunk->pNextChunk;
34190     sqlite3DbFree(p->db, pChunk);
34191   }
34192   p->pChunk = 0;
34193   p->nFresh = 0;
34194   p->pEntry = 0;
34195   p->pLast = 0;
34196   p->pTree = 0;
34197   p->isSorted = 1;
34198 }
34199
34200 /*
34201 ** Insert a new value into a RowSet.
34202 **
34203 ** The mallocFailed flag of the database connection is set if a
34204 ** memory allocation fails.
34205 */
34206 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
34207   struct RowSetEntry *pEntry;  /* The new entry */
34208   struct RowSetEntry *pLast;   /* The last prior entry */
34209   assert( p!=0 );
34210   if( p->nFresh==0 ){
34211     struct RowSetChunk *pNew;
34212     pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
34213     if( pNew==0 ){
34214       return;
34215     }
34216     pNew->pNextChunk = p->pChunk;
34217     p->pChunk = pNew;
34218     p->pFresh = pNew->aEntry;
34219     p->nFresh = ROWSET_ENTRY_PER_CHUNK;
34220   }
34221   pEntry = p->pFresh++;
34222   p->nFresh--;
34223   pEntry->v = rowid;
34224   pEntry->pRight = 0;
34225   pLast = p->pLast;
34226   if( pLast ){
34227     if( p->isSorted && rowid<=pLast->v ){
34228       p->isSorted = 0;
34229     }
34230     pLast->pRight = pEntry;
34231   }else{
34232     assert( p->pEntry==0 ); /* Fires if INSERT after SMALLEST */
34233     p->pEntry = pEntry;
34234   }
34235   p->pLast = pEntry;
34236 }
34237
34238 /*
34239 ** Merge two lists of RowSetEntry objects.  Remove duplicates.
34240 **
34241 ** The input lists are connected via pRight pointers and are 
34242 ** assumed to each already be in sorted order.
34243 */
34244 static struct RowSetEntry *rowSetMerge(
34245   struct RowSetEntry *pA,    /* First sorted list to be merged */
34246   struct RowSetEntry *pB     /* Second sorted list to be merged */
34247 ){
34248   struct RowSetEntry head;
34249   struct RowSetEntry *pTail;
34250
34251   pTail = &head;
34252   while( pA && pB ){
34253     assert( pA->pRight==0 || pA->v<=pA->pRight->v );
34254     assert( pB->pRight==0 || pB->v<=pB->pRight->v );
34255     if( pA->v<pB->v ){
34256       pTail->pRight = pA;
34257       pA = pA->pRight;
34258       pTail = pTail->pRight;
34259     }else if( pB->v<pA->v ){
34260       pTail->pRight = pB;
34261       pB = pB->pRight;
34262       pTail = pTail->pRight;
34263     }else{
34264       pA = pA->pRight;
34265     }
34266   }
34267   if( pA ){
34268     assert( pA->pRight==0 || pA->v<=pA->pRight->v );
34269     pTail->pRight = pA;
34270   }else{
34271     assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
34272     pTail->pRight = pB;
34273   }
34274   return head.pRight;
34275 }
34276
34277 /*
34278 ** Sort all elements on the pEntry list of the RowSet into ascending order.
34279 */ 
34280 static void rowSetSort(RowSet *p){
34281   unsigned int i;
34282   struct RowSetEntry *pEntry;
34283   struct RowSetEntry *aBucket[40];
34284
34285   assert( p->isSorted==0 );
34286   memset(aBucket, 0, sizeof(aBucket));
34287   while( p->pEntry ){
34288     pEntry = p->pEntry;
34289     p->pEntry = pEntry->pRight;
34290     pEntry->pRight = 0;
34291     for(i=0; aBucket[i]; i++){
34292       pEntry = rowSetMerge(aBucket[i], pEntry);
34293       aBucket[i] = 0;
34294     }
34295     aBucket[i] = pEntry;
34296   }
34297   pEntry = 0;
34298   for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
34299     pEntry = rowSetMerge(pEntry, aBucket[i]);
34300   }
34301   p->pEntry = pEntry;
34302   p->pLast = 0;
34303   p->isSorted = 1;
34304 }
34305
34306
34307 /*
34308 ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
34309 ** Convert this tree into a linked list connected by the pRight pointers
34310 ** and return pointers to the first and last elements of the new list.
34311 */
34312 static void rowSetTreeToList(
34313   struct RowSetEntry *pIn,         /* Root of the input tree */
34314   struct RowSetEntry **ppFirst,    /* Write head of the output list here */
34315   struct RowSetEntry **ppLast      /* Write tail of the output list here */
34316 ){
34317   assert( pIn!=0 );
34318   if( pIn->pLeft ){
34319     struct RowSetEntry *p;
34320     rowSetTreeToList(pIn->pLeft, ppFirst, &p);
34321     p->pRight = pIn;
34322   }else{
34323     *ppFirst = pIn;
34324   }
34325   if( pIn->pRight ){
34326     rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
34327   }else{
34328     *ppLast = pIn;
34329   }
34330   assert( (*ppLast)->pRight==0 );
34331 }
34332
34333
34334 /*
34335 ** Convert a sorted list of elements (connected by pRight) into a binary
34336 ** tree with depth of iDepth.  A depth of 1 means the tree contains a single
34337 ** node taken from the head of *ppList.  A depth of 2 means a tree with
34338 ** three nodes.  And so forth.
34339 **
34340 ** Use as many entries from the input list as required and update the
34341 ** *ppList to point to the unused elements of the list.  If the input
34342 ** list contains too few elements, then construct an incomplete tree
34343 ** and leave *ppList set to NULL.
34344 **
34345 ** Return a pointer to the root of the constructed binary tree.
34346 */
34347 static struct RowSetEntry *rowSetNDeepTree(
34348   struct RowSetEntry **ppList,
34349   int iDepth
34350 ){
34351   struct RowSetEntry *p;         /* Root of the new tree */
34352   struct RowSetEntry *pLeft;     /* Left subtree */
34353   if( *ppList==0 ){
34354     return 0;
34355   }
34356   if( iDepth==1 ){
34357     p = *ppList;
34358     *ppList = p->pRight;
34359     p->pLeft = p->pRight = 0;
34360     return p;
34361   }
34362   pLeft = rowSetNDeepTree(ppList, iDepth-1);
34363   p = *ppList;
34364   if( p==0 ){
34365     return pLeft;
34366   }
34367   p->pLeft = pLeft;
34368   *ppList = p->pRight;
34369   p->pRight = rowSetNDeepTree(ppList, iDepth-1);
34370   return p;
34371 }
34372
34373 /*
34374 ** Convert a sorted list of elements into a binary tree. Make the tree
34375 ** as deep as it needs to be in order to contain the entire list.
34376 */
34377 static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
34378   int iDepth;           /* Depth of the tree so far */
34379   struct RowSetEntry *p;       /* Current tree root */
34380   struct RowSetEntry *pLeft;   /* Left subtree */
34381
34382   assert( pList!=0 );
34383   p = pList;
34384   pList = p->pRight;
34385   p->pLeft = p->pRight = 0;
34386   for(iDepth=1; pList; iDepth++){
34387     pLeft = p;
34388     p = pList;
34389     pList = p->pRight;
34390     p->pLeft = pLeft;
34391     p->pRight = rowSetNDeepTree(&pList, iDepth);
34392   }
34393   return p;
34394 }
34395
34396 /*
34397 ** Convert the list in p->pEntry into a sorted list if it is not
34398 ** sorted already.  If there is a binary tree on p->pTree, then
34399 ** convert it into a list too and merge it into the p->pEntry list.
34400 */
34401 static void rowSetToList(RowSet *p){
34402   if( !p->isSorted ){
34403     rowSetSort(p);
34404   }
34405   if( p->pTree ){
34406     struct RowSetEntry *pHead, *pTail;
34407     rowSetTreeToList(p->pTree, &pHead, &pTail);
34408     p->pTree = 0;
34409     p->pEntry = rowSetMerge(p->pEntry, pHead);
34410   }
34411 }
34412
34413 /*
34414 ** Extract the smallest element from the RowSet.
34415 ** Write the element into *pRowid.  Return 1 on success.  Return
34416 ** 0 if the RowSet is already empty.
34417 **
34418 ** After this routine has been called, the sqlite3RowSetInsert()
34419 ** routine may not be called again.  
34420 */
34421 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
34422   rowSetToList(p);
34423   if( p->pEntry ){
34424     *pRowid = p->pEntry->v;
34425     p->pEntry = p->pEntry->pRight;
34426     if( p->pEntry==0 ){
34427       sqlite3RowSetClear(p);
34428     }
34429     return 1;
34430   }else{
34431     return 0;
34432   }
34433 }
34434
34435 /*
34436 ** Check to see if element iRowid was inserted into the the rowset as
34437 ** part of any insert batch prior to iBatch.  Return 1 or 0.
34438 */
34439 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, u8 iBatch, sqlite3_int64 iRowid){
34440   struct RowSetEntry *p;
34441   if( iBatch!=pRowSet->iBatch ){
34442     if( pRowSet->pEntry ){
34443       rowSetToList(pRowSet);
34444       pRowSet->pTree = rowSetListToTree(pRowSet->pEntry);
34445       pRowSet->pEntry = 0;
34446       pRowSet->pLast = 0;
34447     }
34448     pRowSet->iBatch = iBatch;
34449   }
34450   p = pRowSet->pTree;
34451   while( p ){
34452     if( p->v<iRowid ){
34453       p = p->pRight;
34454     }else if( p->v>iRowid ){
34455       p = p->pLeft;
34456     }else{
34457       return 1;
34458     }
34459   }
34460   return 0;
34461 }
34462
34463 /************** End of rowset.c **********************************************/
34464 /************** Begin file pager.c *******************************************/
34465 /*
34466 ** 2001 September 15
34467 **
34468 ** The author disclaims copyright to this source code.  In place of
34469 ** a legal notice, here is a blessing:
34470 **
34471 **    May you do good and not evil.
34472 **    May you find forgiveness for yourself and forgive others.
34473 **    May you share freely, never taking more than you give.
34474 **
34475 *************************************************************************
34476 ** This is the implementation of the page cache subsystem or "pager".
34477 ** 
34478 ** The pager is used to access a database disk file.  It implements
34479 ** atomic commit and rollback through the use of a journal file that
34480 ** is separate from the database file.  The pager also implements file
34481 ** locking to prevent two processes from writing the same database
34482 ** file simultaneously, or one process from reading the database while
34483 ** another is writing.
34484 */
34485 #ifndef SQLITE_OMIT_DISKIO
34486 /************** Include wal.h in the middle of pager.c ***********************/
34487 /************** Begin file wal.h *********************************************/
34488 /*
34489 ** 2010 February 1
34490 **
34491 ** The author disclaims copyright to this source code.  In place of
34492 ** a legal notice, here is a blessing:
34493 **
34494 **    May you do good and not evil.
34495 **    May you find forgiveness for yourself and forgive others.
34496 **    May you share freely, never taking more than you give.
34497 **
34498 *************************************************************************
34499 ** This header file defines the interface to the write-ahead logging 
34500 ** system. Refer to the comments below and the header comment attached to 
34501 ** the implementation of each function in log.c for further details.
34502 */
34503
34504 #ifndef _WAL_H_
34505 #define _WAL_H_
34506
34507
34508 #ifdef SQLITE_OMIT_WAL
34509 # define sqlite3WalOpen(x,y,z)                 0
34510 # define sqlite3WalClose(w,x,y,z)              0
34511 # define sqlite3WalBeginReadTransaction(y,z)   0
34512 # define sqlite3WalEndReadTransaction(z)
34513 # define sqlite3WalRead(v,w,x,y,z)             0
34514 # define sqlite3WalDbsize(y)                   0
34515 # define sqlite3WalBeginWriteTransaction(y)    0
34516 # define sqlite3WalEndWriteTransaction(x)      0
34517 # define sqlite3WalUndo(x,y,z)                 0
34518 # define sqlite3WalSavepoint(y,z)
34519 # define sqlite3WalSavepointUndo(y,z)          0
34520 # define sqlite3WalFrames(u,v,w,x,y,z)         0
34521 # define sqlite3WalCheckpoint(u,v,w,x)         0
34522 # define sqlite3WalCallback(z)                 0
34523 # define sqlite3WalExclusiveMode(y,z)          0
34524 #else
34525
34526 #define WAL_SAVEPOINT_NDATA 4
34527
34528 /* Connection to a write-ahead log (WAL) file. 
34529 ** There is one object of this type for each pager. 
34530 */
34531 typedef struct Wal Wal;
34532
34533 /* Open and close a connection to a write-ahead log. */
34534 SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *zName, Wal**);
34535 SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);
34536
34537 /* Used by readers to open (lock) and close (unlock) a snapshot.  A 
34538 ** snapshot is like a read-transaction.  It is the state of the database
34539 ** at an instant in time.  sqlite3WalOpenSnapshot gets a read lock and
34540 ** preserves the current state even if the other threads or processes
34541 ** write to or checkpoint the WAL.  sqlite3WalCloseSnapshot() closes the
34542 ** transaction and releases the lock.
34543 */
34544 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
34545 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
34546
34547 /* Read a page from the write-ahead log, if it is present. */
34548 SQLITE_PRIVATE int sqlite3WalRead(Wal *pWal, Pgno pgno, int *pInWal, int nOut, u8 *pOut);
34549
34550 /* If the WAL is not empty, return the size of the database. */
34551 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
34552
34553 /* Obtain or release the WRITER lock. */
34554 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
34555 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
34556
34557 /* Undo any frames written (but not committed) to the log */
34558 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
34559
34560 /* Return an integer that records the current (uncommitted) write
34561 ** position in the WAL */
34562 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
34563
34564 /* Move the write position of the WAL back to iFrame.  Called in
34565 ** response to a ROLLBACK TO command. */
34566 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
34567
34568 /* Write a frame or frames to the log. */
34569 SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
34570
34571 /* Copy pages from the log to the database file */ 
34572 SQLITE_PRIVATE int sqlite3WalCheckpoint(
34573   Wal *pWal,                      /* Write-ahead log connection */
34574   int sync_flags,                 /* Flags to sync db file with (or 0) */
34575   int nBuf,                       /* Size of buffer nBuf */
34576   u8 *zBuf                        /* Temporary buffer to use */
34577 );
34578
34579 /* Return the value to pass to a sqlite3_wal_hook callback, the
34580 ** number of frames in the WAL at the point of the last commit since
34581 ** sqlite3WalCallback() was called.  If no commits have occurred since
34582 ** the last call, then return 0.
34583 */
34584 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
34585
34586 /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
34587 ** by the pager layer on the database file.
34588 */
34589 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
34590
34591 #endif /* ifndef SQLITE_OMIT_WAL */
34592 #endif /* _WAL_H_ */
34593
34594 /************** End of wal.h *************************************************/
34595 /************** Continuing where we left off in pager.c **********************/
34596
34597
34598 /******************* NOTES ON THE DESIGN OF THE PAGER ************************
34599 **
34600 ** This comment block describes invariants that hold when using a rollback
34601 ** journal.  These invariants do not apply for journal_mode=WAL,
34602 ** journal_mode=MEMORY, or journal_mode=OFF.
34603 **
34604 ** Within this comment block, a page is deemed to have been synced
34605 ** automatically as soon as it is written when PRAGMA synchronous=OFF.
34606 ** Otherwise, the page is not synced until the xSync method of the VFS
34607 ** is called successfully on the file containing the page.
34608 **
34609 ** Definition:  A page of the database file is said to be "overwriteable" if
34610 ** one or more of the following are true about the page:
34611 ** 
34612 **     (a)  The original content of the page as it was at the beginning of
34613 **          the transaction has been written into the rollback journal and
34614 **          synced.
34615 ** 
34616 **     (b)  The page was a freelist leaf page at the start of the transaction.
34617 ** 
34618 **     (c)  The page number is greater than the largest page that existed in
34619 **          the database file at the start of the transaction.
34620 ** 
34621 ** (1) A page of the database file is never overwritten unless one of the
34622 **     following are true:
34623 ** 
34624 **     (a) The page and all other pages on the same sector are overwriteable.
34625 ** 
34626 **     (b) The atomic page write optimization is enabled, and the entire
34627 **         transaction other than the update of the transaction sequence
34628 **         number consists of a single page change.
34629 ** 
34630 ** (2) The content of a page written into the rollback journal exactly matches
34631 **     both the content in the database when the rollback journal was written
34632 **     and the content in the database at the beginning of the current
34633 **     transaction.
34634 ** 
34635 ** (3) Writes to the database file are an integer multiple of the page size
34636 **     in length and are aligned on a page boundary.
34637 ** 
34638 ** (4) Reads from the database file are either aligned on a page boundary and
34639 **     an integer multiple of the page size in length or are taken from the
34640 **     first 100 bytes of the database file.
34641 ** 
34642 ** (5) All writes to the database file are synced prior to the rollback journal
34643 **     being deleted, truncated, or zeroed.
34644 ** 
34645 ** (6) If a master journal file is used, then all writes to the database file
34646 **     are synced prior to the master journal being deleted.
34647 ** 
34648 ** Definition: Two databases (or the same database at two points it time)
34649 ** are said to be "logically equivalent" if they give the same answer to
34650 ** all queries.  Note in particular the the content of freelist leaf
34651 ** pages can be changed arbitarily without effecting the logical equivalence
34652 ** of the database.
34653 ** 
34654 ** (7) At any time, if any subset, including the empty set and the total set,
34655 **     of the unsynced changes to a rollback journal are removed and the 
34656 **     journal is rolled back, the resulting database file will be logical
34657 **     equivalent to the database file at the beginning of the transaction.
34658 ** 
34659 ** (8) When a transaction is rolled back, the xTruncate method of the VFS
34660 **     is called to restore the database file to the same size it was at
34661 **     the beginning of the transaction.  (In some VFSes, the xTruncate
34662 **     method is a no-op, but that does not change the fact the SQLite will
34663 **     invoke it.)
34664 ** 
34665 ** (9) Whenever the database file is modified, at least one bit in the range
34666 **     of bytes from 24 through 39 inclusive will be changed prior to releasing
34667 **     the EXCLUSIVE lock, thus signaling other connections on the same
34668 **     database to flush their caches.
34669 **
34670 ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
34671 **      than one billion transactions.
34672 **
34673 ** (11) A database file is well-formed at the beginning and at the conclusion
34674 **      of every transaction.
34675 **
34676 ** (12) An EXCLUSIVE lock is held on the database file when writing to
34677 **      the database file.
34678 **
34679 ** (13) A SHARED lock is held on the database file while reading any
34680 **      content out of the database file.
34681 **
34682 ******************************************************************************/
34683
34684 /*
34685 ** Macros for troubleshooting.  Normally turned off
34686 */
34687 #if 0
34688 int sqlite3PagerTrace=1;  /* True to enable tracing */
34689 #define sqlite3DebugPrintf printf
34690 #define PAGERTRACE(X)     if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
34691 #else
34692 #define PAGERTRACE(X)
34693 #endif
34694
34695 /*
34696 ** The following two macros are used within the PAGERTRACE() macros above
34697 ** to print out file-descriptors. 
34698 **
34699 ** PAGERID() takes a pointer to a Pager struct as its argument. The
34700 ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
34701 ** struct as its argument.
34702 */
34703 #define PAGERID(p) ((int)(p->fd))
34704 #define FILEHANDLEID(fd) ((int)fd)
34705
34706 /*
34707 ** The Pager.eState variable stores the current 'state' of a pager. A
34708 ** pager may be in any one of the seven states shown in the following
34709 ** state diagram.
34710 **
34711 **                            OPEN <------+------+
34712 **                              |         |      |
34713 **                              V         |      |
34714 **               +---------> READER-------+      |
34715 **               |              |                |
34716 **               |              V                |
34717 **               |<-------WRITER_LOCKED------> ERROR
34718 **               |              |                ^  
34719 **               |              V                |
34720 **               |<------WRITER_CACHEMOD-------->|
34721 **               |              |                |
34722 **               |              V                |
34723 **               |<-------WRITER_DBMOD---------->|
34724 **               |              |                |
34725 **               |              V                |
34726 **               +<------WRITER_FINISHED-------->+
34727 **
34728 **
34729 ** List of state transitions and the C [function] that performs each:
34730 ** 
34731 **   OPEN              -> READER              [sqlite3PagerSharedLock]
34732 **   READER            -> OPEN                [pager_unlock]
34733 **
34734 **   READER            -> WRITER_LOCKED       [sqlite3PagerBegin]
34735 **   WRITER_LOCKED     -> WRITER_CACHEMOD     [pager_open_journal]
34736 **   WRITER_CACHEMOD   -> WRITER_DBMOD        [syncJournal]
34737 **   WRITER_DBMOD      -> WRITER_FINISHED     [sqlite3PagerCommitPhaseOne]
34738 **   WRITER_***        -> READER              [pager_end_transaction]
34739 **
34740 **   WRITER_***        -> ERROR               [pager_error]
34741 **   ERROR             -> OPEN                [pager_unlock]
34742 ** 
34743 **
34744 **  OPEN:
34745 **
34746 **    The pager starts up in this state. Nothing is guaranteed in this
34747 **    state - the file may or may not be locked and the database size is
34748 **    unknown. The database may not be read or written.
34749 **
34750 **    * No read or write transaction is active.
34751 **    * Any lock, or no lock at all, may be held on the database file.
34752 **    * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
34753 **
34754 **  READER:
34755 **
34756 **    In this state all the requirements for reading the database in 
34757 **    rollback (non-WAL) mode are met. Unless the pager is (or recently
34758 **    was) in exclusive-locking mode, a user-level read transaction is 
34759 **    open. The database size is known in this state.
34760 **
34761 **    A connection running with locking_mode=normal enters this state when
34762 **    it opens a read-transaction on the database and returns to state
34763 **    OPEN after the read-transaction is completed. However a connection
34764 **    running in locking_mode=exclusive (including temp databases) remains in
34765 **    this state even after the read-transaction is closed. The only way
34766 **    a locking_mode=exclusive connection can transition from READER to OPEN
34767 **    is via the ERROR state (see below).
34768 ** 
34769 **    * A read transaction may be active (but a write-transaction cannot).
34770 **    * A SHARED or greater lock is held on the database file.
34771 **    * The dbSize variable may be trusted (even if a user-level read 
34772 **      transaction is not active). The dbOrigSize and dbFileSize variables
34773 **      may not be trusted at this point.
34774 **    * If the database is a WAL database, then the WAL connection is open.
34775 **    * Even if a read-transaction is not open, it is guaranteed that 
34776 **      there is no hot-journal in the file-system.
34777 **
34778 **  WRITER_LOCKED:
34779 **
34780 **    The pager moves to this state from READER when a write-transaction
34781 **    is first opened on the database. In WRITER_LOCKED state, all locks 
34782 **    required to start a write-transaction are held, but no actual 
34783 **    modifications to the cache or database have taken place.
34784 **
34785 **    In rollback mode, a RESERVED or (if the transaction was opened with 
34786 **    BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
34787 **    moving to this state, but the journal file is not written to or opened 
34788 **    to in this state. If the transaction is committed or rolled back while 
34789 **    in WRITER_LOCKED state, all that is required is to unlock the database 
34790 **    file.
34791 **
34792 **    IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
34793 **    If the connection is running with locking_mode=exclusive, an attempt
34794 **    is made to obtain an EXCLUSIVE lock on the database file.
34795 **
34796 **    * A write transaction is active.
34797 **    * If the connection is open in rollback-mode, a RESERVED or greater 
34798 **      lock is held on the database file.
34799 **    * If the connection is open in WAL-mode, a WAL write transaction
34800 **      is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
34801 **      called).
34802 **    * The dbSize, dbOrigSize and dbFileSize variables are all valid.
34803 **    * The contents of the pager cache have not been modified.
34804 **    * The journal file may or may not be open.
34805 **    * Nothing (not even the first header) has been written to the journal.
34806 **
34807 **  WRITER_CACHEMOD:
34808 **
34809 **    A pager moves from WRITER_LOCKED state to this state when a page is
34810 **    first modified by the upper layer. In rollback mode the journal file
34811 **    is opened (if it is not already open) and a header written to the
34812 **    start of it. The database file on disk has not been modified.
34813 **
34814 **    * A write transaction is active.
34815 **    * A RESERVED or greater lock is held on the database file.
34816 **    * The journal file is open and the first header has been written 
34817 **      to it, but the header has not been synced to disk.
34818 **    * The contents of the page cache have been modified.
34819 **
34820 **  WRITER_DBMOD:
34821 **
34822 **    The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
34823 **    when it modifies the contents of the database file. WAL connections
34824 **    never enter this state (since they do not modify the database file,
34825 **    just the log file).
34826 **
34827 **    * A write transaction is active.
34828 **    * An EXCLUSIVE or greater lock is held on the database file.
34829 **    * The journal file is open and the first header has been written 
34830 **      and synced to disk.
34831 **    * The contents of the page cache have been modified (and possibly
34832 **      written to disk).
34833 **
34834 **  WRITER_FINISHED:
34835 **
34836 **    It is not possible for a WAL connection to enter this state.
34837 **
34838 **    A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
34839 **    state after the entire transaction has been successfully written into the
34840 **    database file. In this state the transaction may be committed simply
34841 **    by finalizing the journal file. Once in WRITER_FINISHED state, it is 
34842 **    not possible to modify the database further. At this point, the upper 
34843 **    layer must either commit or rollback the transaction.
34844 **
34845 **    * A write transaction is active.
34846 **    * An EXCLUSIVE or greater lock is held on the database file.
34847 **    * All writing and syncing of journal and database data has finished.
34848 **      If no error occured, all that remains is to finalize the journal to
34849 **      commit the transaction. If an error did occur, the caller will need
34850 **      to rollback the transaction. 
34851 **
34852 **  ERROR:
34853 **
34854 **    The ERROR state is entered when an IO or disk-full error (including
34855 **    SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it 
34856 **    difficult to be sure that the in-memory pager state (cache contents, 
34857 **    db size etc.) are consistent with the contents of the file-system.
34858 **
34859 **    Temporary pager files may enter the ERROR state, but in-memory pagers
34860 **    cannot.
34861 **
34862 **    For example, if an IO error occurs while performing a rollback, 
34863 **    the contents of the page-cache may be left in an inconsistent state.
34864 **    At this point it would be dangerous to change back to READER state
34865 **    (as usually happens after a rollback). Any subsequent readers might
34866 **    report database corruption (due to the inconsistent cache), and if
34867 **    they upgrade to writers, they may inadvertently corrupt the database
34868 **    file. To avoid this hazard, the pager switches into the ERROR state
34869 **    instead of READER following such an error.
34870 **
34871 **    Once it has entered the ERROR state, any attempt to use the pager
34872 **    to read or write data returns an error. Eventually, once all 
34873 **    outstanding transactions have been abandoned, the pager is able to
34874 **    transition back to OPEN state, discarding the contents of the 
34875 **    page-cache and any other in-memory state at the same time. Everything
34876 **    is reloaded from disk (and, if necessary, hot-journal rollback peformed)
34877 **    when a read-transaction is next opened on the pager (transitioning
34878 **    the pager into READER state). At that point the system has recovered 
34879 **    from the error.
34880 **
34881 **    Specifically, the pager jumps into the ERROR state if:
34882 **
34883 **      1. An error occurs while attempting a rollback. This happens in
34884 **         function sqlite3PagerRollback().
34885 **
34886 **      2. An error occurs while attempting to finalize a journal file
34887 **         following a commit in function sqlite3PagerCommitPhaseTwo().
34888 **
34889 **      3. An error occurs while attempting to write to the journal or
34890 **         database file in function pagerStress() in order to free up
34891 **         memory.
34892 **
34893 **    In other cases, the error is returned to the b-tree layer. The b-tree
34894 **    layer then attempts a rollback operation. If the error condition 
34895 **    persists, the pager enters the ERROR state via condition (1) above.
34896 **
34897 **    Condition (3) is necessary because it can be triggered by a read-only
34898 **    statement executed within a transaction. In this case, if the error
34899 **    code were simply returned to the user, the b-tree layer would not
34900 **    automatically attempt a rollback, as it assumes that an error in a
34901 **    read-only statement cannot leave the pager in an internally inconsistent 
34902 **    state.
34903 **
34904 **    * The Pager.errCode variable is set to something other than SQLITE_OK.
34905 **    * There are one or more outstanding references to pages (after the
34906 **      last reference is dropped the pager should move back to OPEN state).
34907 **    * The pager is not an in-memory pager.
34908 **    
34909 **
34910 ** Notes:
34911 **
34912 **   * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
34913 **     connection is open in WAL mode. A WAL connection is always in one
34914 **     of the first four states.
34915 **
34916 **   * Normally, a connection open in exclusive mode is never in PAGER_OPEN
34917 **     state. There are two exceptions: immediately after exclusive-mode has
34918 **     been turned on (and before any read or write transactions are 
34919 **     executed), and when the pager is leaving the "error state".
34920 **
34921 **   * See also: assert_pager_state().
34922 */
34923 #define PAGER_OPEN                  0
34924 #define PAGER_READER                1
34925 #define PAGER_WRITER_LOCKED         2
34926 #define PAGER_WRITER_CACHEMOD       3
34927 #define PAGER_WRITER_DBMOD          4
34928 #define PAGER_WRITER_FINISHED       5
34929 #define PAGER_ERROR                 6
34930
34931 /*
34932 ** The Pager.eLock variable is almost always set to one of the 
34933 ** following locking-states, according to the lock currently held on
34934 ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
34935 ** This variable is kept up to date as locks are taken and released by
34936 ** the pagerLockDb() and pagerUnlockDb() wrappers.
34937 **
34938 ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
34939 ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
34940 ** the operation was successful. In these circumstances pagerLockDb() and
34941 ** pagerUnlockDb() take a conservative approach - eLock is always updated
34942 ** when unlocking the file, and only updated when locking the file if the
34943 ** VFS call is successful. This way, the Pager.eLock variable may be set
34944 ** to a less exclusive (lower) value than the lock that is actually held
34945 ** at the system level, but it is never set to a more exclusive value.
34946 **
34947 ** This is usually safe. If an xUnlock fails or appears to fail, there may 
34948 ** be a few redundant xLock() calls or a lock may be held for longer than
34949 ** required, but nothing really goes wrong.
34950 **
34951 ** The exception is when the database file is unlocked as the pager moves
34952 ** from ERROR to OPEN state. At this point there may be a hot-journal file 
34953 ** in the file-system that needs to be rolled back (as part of a OPEN->SHARED
34954 ** transition, by the same pager or any other). If the call to xUnlock()
34955 ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
34956 ** can confuse the call to xCheckReservedLock() call made later as part
34957 ** of hot-journal detection.
34958 **
34959 ** xCheckReservedLock() is defined as returning true "if there is a RESERVED 
34960 ** lock held by this process or any others". So xCheckReservedLock may 
34961 ** return true because the caller itself is holding an EXCLUSIVE lock (but
34962 ** doesn't know it because of a previous error in xUnlock). If this happens
34963 ** a hot-journal may be mistaken for a journal being created by an active
34964 ** transaction in another process, causing SQLite to read from the database
34965 ** without rolling it back.
34966 **
34967 ** To work around this, if a call to xUnlock() fails when unlocking the
34968 ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
34969 ** is only changed back to a real locking state after a successful call
34970 ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
34971 ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK 
34972 ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
34973 ** lock on the database file before attempting to roll it back. See function
34974 ** PagerSharedLock() for more detail.
34975 **
34976 ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in 
34977 ** PAGER_OPEN state.
34978 */
34979 #define UNKNOWN_LOCK                (EXCLUSIVE_LOCK+1)
34980
34981 /*
34982 ** A macro used for invoking the codec if there is one
34983 */
34984 #ifdef SQLITE_HAS_CODEC
34985 # define CODEC1(P,D,N,X,E) \
34986     if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
34987 # define CODEC2(P,D,N,X,E,O) \
34988     if( P->xCodec==0 ){ O=(char*)D; }else \
34989     if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
34990 #else
34991 # define CODEC1(P,D,N,X,E)   /* NO-OP */
34992 # define CODEC2(P,D,N,X,E,O) O=(char*)D
34993 #endif
34994
34995 /*
34996 ** The maximum allowed sector size. 64KiB. If the xSectorsize() method 
34997 ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
34998 ** This could conceivably cause corruption following a power failure on
34999 ** such a system. This is currently an undocumented limit.
35000 */
35001 #define MAX_SECTOR_SIZE 0x10000
35002
35003 /*
35004 ** An instance of the following structure is allocated for each active
35005 ** savepoint and statement transaction in the system. All such structures
35006 ** are stored in the Pager.aSavepoint[] array, which is allocated and
35007 ** resized using sqlite3Realloc().
35008 **
35009 ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
35010 ** set to 0. If a journal-header is written into the main journal while
35011 ** the savepoint is active, then iHdrOffset is set to the byte offset 
35012 ** immediately following the last journal record written into the main
35013 ** journal before the journal-header. This is required during savepoint
35014 ** rollback (see pagerPlaybackSavepoint()).
35015 */
35016 typedef struct PagerSavepoint PagerSavepoint;
35017 struct PagerSavepoint {
35018   i64 iOffset;                 /* Starting offset in main journal */
35019   i64 iHdrOffset;              /* See above */
35020   Bitvec *pInSavepoint;        /* Set of pages in this savepoint */
35021   Pgno nOrig;                  /* Original number of pages in file */
35022   Pgno iSubRec;                /* Index of first record in sub-journal */
35023 #ifndef SQLITE_OMIT_WAL
35024   u32 aWalData[WAL_SAVEPOINT_NDATA];        /* WAL savepoint context */
35025 #endif
35026 };
35027
35028 /*
35029 ** A open page cache is an instance of struct Pager. A description of
35030 ** some of the more important member variables follows:
35031 **
35032 ** eState
35033 **
35034 **   The current 'state' of the pager object. See the comment and state
35035 **   diagram above for a description of the pager state.
35036 **
35037 ** eLock
35038 **
35039 **   For a real on-disk database, the current lock held on the database file -
35040 **   NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
35041 **
35042 **   For a temporary or in-memory database (neither of which require any
35043 **   locks), this variable is always set to EXCLUSIVE_LOCK. Since such
35044 **   databases always have Pager.exclusiveMode==1, this tricks the pager
35045 **   logic into thinking that it already has all the locks it will ever
35046 **   need (and no reason to release them).
35047 **
35048 **   In some (obscure) circumstances, this variable may also be set to
35049 **   UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
35050 **   details.
35051 **
35052 ** changeCountDone
35053 **
35054 **   This boolean variable is used to make sure that the change-counter 
35055 **   (the 4-byte header field at byte offset 24 of the database file) is 
35056 **   not updated more often than necessary. 
35057 **
35058 **   It is set to true when the change-counter field is updated, which 
35059 **   can only happen if an exclusive lock is held on the database file.
35060 **   It is cleared (set to false) whenever an exclusive lock is 
35061 **   relinquished on the database file. Each time a transaction is committed,
35062 **   The changeCountDone flag is inspected. If it is true, the work of
35063 **   updating the change-counter is omitted for the current transaction.
35064 **
35065 **   This mechanism means that when running in exclusive mode, a connection 
35066 **   need only update the change-counter once, for the first transaction
35067 **   committed.
35068 **
35069 ** setMaster
35070 **
35071 **   When PagerCommitPhaseOne() is called to commit a transaction, it may
35072 **   (or may not) specify a master-journal name to be written into the 
35073 **   journal file before it is synced to disk.
35074 **
35075 **   Whether or not a journal file contains a master-journal pointer affects 
35076 **   the way in which the journal file is finalized after the transaction is 
35077 **   committed or rolled back when running in "journal_mode=PERSIST" mode.
35078 **   If a journal file does not contain a master-journal pointer, it is
35079 **   finalized by overwriting the first journal header with zeroes. If
35080 **   it does contain a master-journal pointer the journal file is finalized 
35081 **   by truncating it to zero bytes, just as if the connection were 
35082 **   running in "journal_mode=truncate" mode.
35083 **
35084 **   Journal files that contain master journal pointers cannot be finalized
35085 **   simply by overwriting the first journal-header with zeroes, as the
35086 **   master journal pointer could interfere with hot-journal rollback of any
35087 **   subsequently interrupted transaction that reuses the journal file.
35088 **
35089 **   The flag is cleared as soon as the journal file is finalized (either
35090 **   by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
35091 **   journal file from being successfully finalized, the setMaster flag
35092 **   is cleared anyway (and the pager will move to ERROR state).
35093 **
35094 ** doNotSpill, doNotSyncSpill
35095 **
35096 **   These two boolean variables control the behaviour of cache-spills
35097 **   (calls made by the pcache module to the pagerStress() routine to
35098 **   write cached data to the file-system in order to free up memory).
35099 **
35100 **   When doNotSpill is non-zero, writing to the database from pagerStress()
35101 **   is disabled altogether. This is done in a very obscure case that
35102 **   comes up during savepoint rollback that requires the pcache module
35103 **   to allocate a new page to prevent the journal file from being written
35104 **   while it is being traversed by code in pager_playback().
35105 ** 
35106 **   If doNotSyncSpill is non-zero, writing to the database from pagerStress()
35107 **   is permitted, but syncing the journal file is not. This flag is set
35108 **   by sqlite3PagerWrite() when the file-system sector-size is larger than
35109 **   the database page-size in order to prevent a journal sync from happening 
35110 **   in between the journalling of two pages on the same sector. 
35111 **
35112 ** subjInMemory
35113 **
35114 **   This is a boolean variable. If true, then any required sub-journal
35115 **   is opened as an in-memory journal file. If false, then in-memory
35116 **   sub-journals are only used for in-memory pager files.
35117 **
35118 **   This variable is updated by the upper layer each time a new 
35119 **   write-transaction is opened.
35120 **
35121 ** dbSize, dbOrigSize, dbFileSize
35122 **
35123 **   Variable dbSize is set to the number of pages in the database file.
35124 **   It is valid in PAGER_READER and higher states (all states except for
35125 **   OPEN and ERROR). 
35126 **
35127 **   dbSize is set based on the size of the database file, which may be 
35128 **   larger than the size of the database (the value stored at offset
35129 **   28 of the database header by the btree). If the size of the file
35130 **   is not an integer multiple of the page-size, the value stored in
35131 **   dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
35132 **   Except, any file that is greater than 0 bytes in size is considered
35133 **   to have at least one page. (i.e. a 1KB file with 2K page-size leads
35134 **   to dbSize==1).
35135 **
35136 **   During a write-transaction, if pages with page-numbers greater than
35137 **   dbSize are modified in the cache, dbSize is updated accordingly.
35138 **   Similarly, if the database is truncated using PagerTruncateImage(), 
35139 **   dbSize is updated.
35140 **
35141 **   Variables dbOrigSize and dbFileSize are valid in states 
35142 **   PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
35143 **   variable at the start of the transaction. It is used during rollback,
35144 **   and to determine whether or not pages need to be journalled before
35145 **   being modified.
35146 **
35147 **   Throughout a write-transaction, dbFileSize contains the size of
35148 **   the file on disk in pages. It is set to a copy of dbSize when the
35149 **   write-transaction is first opened, and updated when VFS calls are made
35150 **   to write or truncate the database file on disk. 
35151 **
35152 **   The only reason the dbFileSize variable is required is to suppress 
35153 **   unnecessary calls to xTruncate() after committing a transaction. If, 
35154 **   when a transaction is committed, the dbFileSize variable indicates 
35155 **   that the database file is larger than the database image (Pager.dbSize), 
35156 **   pager_truncate() is called. The pager_truncate() call uses xFilesize()
35157 **   to measure the database file on disk, and then truncates it if required.
35158 **   dbFileSize is not used when rolling back a transaction. In this case
35159 **   pager_truncate() is called unconditionally (which means there may be
35160 **   a call to xFilesize() that is not strictly required). In either case,
35161 **   pager_truncate() may cause the file to become smaller or larger.
35162 **
35163 ** dbHintSize
35164 **
35165 **   The dbHintSize variable is used to limit the number of calls made to
35166 **   the VFS xFileControl(FCNTL_SIZE_HINT) method. 
35167 **
35168 **   dbHintSize is set to a copy of the dbSize variable when a
35169 **   write-transaction is opened (at the same time as dbFileSize and
35170 **   dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
35171 **   dbHintSize is increased to the number of pages that correspond to the
35172 **   size-hint passed to the method call. See pager_write_pagelist() for 
35173 **   details.
35174 **
35175 ** errCode
35176 **
35177 **   The Pager.errCode variable is only ever used in PAGER_ERROR state. It
35178 **   is set to zero in all other states. In PAGER_ERROR state, Pager.errCode 
35179 **   is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX 
35180 **   sub-codes.
35181 */
35182 struct Pager {
35183   sqlite3_vfs *pVfs;          /* OS functions to use for IO */
35184   u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
35185   u8 journalMode;             /* One of the PAGER_JOURNALMODE_* values */
35186   u8 useJournal;              /* Use a rollback journal on this file */
35187   u8 noReadlock;              /* Do not bother to obtain readlocks */
35188   u8 noSync;                  /* Do not sync the journal if true */
35189   u8 fullSync;                /* Do extra syncs of the journal for robustness */
35190   u8 sync_flags;              /* One of SYNC_NORMAL or SYNC_FULL */
35191   u8 tempFile;                /* zFilename is a temporary file */
35192   u8 readOnly;                /* True for a read-only database */
35193   u8 memDb;                   /* True to inhibit all file I/O */
35194
35195   /**************************************************************************
35196   ** The following block contains those class members that change during
35197   ** routine opertion.  Class members not in this block are either fixed
35198   ** when the pager is first created or else only change when there is a
35199   ** significant mode change (such as changing the page_size, locking_mode,
35200   ** or the journal_mode).  From another view, these class members describe
35201   ** the "state" of the pager, while other class members describe the
35202   ** "configuration" of the pager.
35203   */
35204   u8 eState;                  /* Pager state (OPEN, READER, WRITER_LOCKED..) */
35205   u8 eLock;                   /* Current lock held on database file */
35206   u8 changeCountDone;         /* Set after incrementing the change-counter */
35207   u8 setMaster;               /* True if a m-j name has been written to jrnl */
35208   u8 doNotSpill;              /* Do not spill the cache when non-zero */
35209   u8 doNotSyncSpill;          /* Do not do a spill that requires jrnl sync */
35210   u8 subjInMemory;            /* True to use in-memory sub-journals */
35211   Pgno dbSize;                /* Number of pages in the database */
35212   Pgno dbOrigSize;            /* dbSize before the current transaction */
35213   Pgno dbFileSize;            /* Number of pages in the database file */
35214   Pgno dbHintSize;            /* Value passed to FCNTL_SIZE_HINT call */
35215   int errCode;                /* One of several kinds of errors */
35216   int nRec;                   /* Pages journalled since last j-header written */
35217   u32 cksumInit;              /* Quasi-random value added to every checksum */
35218   u32 nSubRec;                /* Number of records written to sub-journal */
35219   Bitvec *pInJournal;         /* One bit for each page in the database file */
35220   sqlite3_file *fd;           /* File descriptor for database */
35221   sqlite3_file *jfd;          /* File descriptor for main journal */
35222   sqlite3_file *sjfd;         /* File descriptor for sub-journal */
35223   i64 journalOff;             /* Current write offset in the journal file */
35224   i64 journalHdr;             /* Byte offset to previous journal header */
35225   sqlite3_backup *pBackup;    /* Pointer to list of ongoing backup processes */
35226   PagerSavepoint *aSavepoint; /* Array of active savepoints */
35227   int nSavepoint;             /* Number of elements in aSavepoint[] */
35228   char dbFileVers[16];        /* Changes whenever database file changes */
35229   /*
35230   ** End of the routinely-changing class members
35231   ***************************************************************************/
35232
35233   u16 nExtra;                 /* Add this many bytes to each in-memory page */
35234   i16 nReserve;               /* Number of unused bytes at end of each page */
35235   u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
35236   u32 sectorSize;             /* Assumed sector size during rollback */
35237   int pageSize;               /* Number of bytes in a page */
35238   Pgno mxPgno;                /* Maximum allowed size of the database */
35239   i64 journalSizeLimit;       /* Size limit for persistent journal files */
35240   char *zFilename;            /* Name of the database file */
35241   char *zJournal;             /* Name of the journal file */
35242   int (*xBusyHandler)(void*); /* Function to call when busy */
35243   void *pBusyHandlerArg;      /* Context argument for xBusyHandler */
35244 #ifdef SQLITE_TEST
35245   int nHit, nMiss;            /* Cache hits and missing */
35246   int nRead, nWrite;          /* Database pages read/written */
35247 #endif
35248   void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
35249 #ifdef SQLITE_HAS_CODEC
35250   void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
35251   void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
35252   void (*xCodecFree)(void*);             /* Destructor for the codec */
35253   void *pCodec;               /* First argument to xCodec... methods */
35254 #endif
35255   char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
35256   PCache *pPCache;            /* Pointer to page cache object */
35257 #ifndef SQLITE_OMIT_WAL
35258   Wal *pWal;                  /* Write-ahead log used by "journal_mode=wal" */
35259   char *zWal;                 /* File name for write-ahead log */
35260 #endif
35261 };
35262
35263 /*
35264 ** The following global variables hold counters used for
35265 ** testing purposes only.  These variables do not exist in
35266 ** a non-testing build.  These variables are not thread-safe.
35267 */
35268 #ifdef SQLITE_TEST
35269 SQLITE_API int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */
35270 SQLITE_API int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */
35271 SQLITE_API int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */
35272 # define PAGER_INCR(v)  v++
35273 #else
35274 # define PAGER_INCR(v)
35275 #endif
35276
35277
35278
35279 /*
35280 ** Journal files begin with the following magic string.  The data
35281 ** was obtained from /dev/random.  It is used only as a sanity check.
35282 **
35283 ** Since version 2.8.0, the journal format contains additional sanity
35284 ** checking information.  If the power fails while the journal is being
35285 ** written, semi-random garbage data might appear in the journal
35286 ** file after power is restored.  If an attempt is then made
35287 ** to roll the journal back, the database could be corrupted.  The additional
35288 ** sanity checking data is an attempt to discover the garbage in the
35289 ** journal and ignore it.
35290 **
35291 ** The sanity checking information for the new journal format consists
35292 ** of a 32-bit checksum on each page of data.  The checksum covers both
35293 ** the page number and the pPager->pageSize bytes of data for the page.
35294 ** This cksum is initialized to a 32-bit random value that appears in the
35295 ** journal file right after the header.  The random initializer is important,
35296 ** because garbage data that appears at the end of a journal is likely
35297 ** data that was once in other files that have now been deleted.  If the
35298 ** garbage data came from an obsolete journal file, the checksums might
35299 ** be correct.  But by initializing the checksum to random value which
35300 ** is different for every journal, we minimize that risk.
35301 */
35302 static const unsigned char aJournalMagic[] = {
35303   0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
35304 };
35305
35306 /*
35307 ** The size of the of each page record in the journal is given by
35308 ** the following macro.
35309 */
35310 #define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
35311
35312 /*
35313 ** The journal header size for this pager. This is usually the same 
35314 ** size as a single disk sector. See also setSectorSize().
35315 */
35316 #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
35317
35318 /*
35319 ** The macro MEMDB is true if we are dealing with an in-memory database.
35320 ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
35321 ** the value of MEMDB will be a constant and the compiler will optimize
35322 ** out code that would never execute.
35323 */
35324 #ifdef SQLITE_OMIT_MEMORYDB
35325 # define MEMDB 0
35326 #else
35327 # define MEMDB pPager->memDb
35328 #endif
35329
35330 /*
35331 ** The maximum legal page number is (2^31 - 1).
35332 */
35333 #define PAGER_MAX_PGNO 2147483647
35334
35335 /*
35336 ** The argument to this macro is a file descriptor (type sqlite3_file*).
35337 ** Return 0 if it is not open, or non-zero (but not 1) if it is.
35338 **
35339 ** This is so that expressions can be written as:
35340 **
35341 **   if( isOpen(pPager->jfd) ){ ...
35342 **
35343 ** instead of
35344 **
35345 **   if( pPager->jfd->pMethods ){ ...
35346 */
35347 #define isOpen(pFd) ((pFd)->pMethods)
35348
35349 /*
35350 ** Return true if this pager uses a write-ahead log instead of the usual
35351 ** rollback journal. Otherwise false.
35352 */
35353 #ifndef SQLITE_OMIT_WAL
35354 static int pagerUseWal(Pager *pPager){
35355   return (pPager->pWal!=0);
35356 }
35357 #else
35358 # define pagerUseWal(x) 0
35359 # define pagerRollbackWal(x) 0
35360 # define pagerWalFrames(v,w,x,y,z) 0
35361 # define pagerOpenWalIfPresent(z) SQLITE_OK
35362 # define pagerBeginReadTransaction(z) SQLITE_OK
35363 #endif
35364
35365 #ifndef NDEBUG 
35366 /*
35367 ** Usage:
35368 **
35369 **   assert( assert_pager_state(pPager) );
35370 **
35371 ** This function runs many asserts to try to find inconsistencies in
35372 ** the internal state of the Pager object.
35373 */
35374 static int assert_pager_state(Pager *p){
35375   Pager *pPager = p;
35376
35377   /* State must be valid. */
35378   assert( p->eState==PAGER_OPEN
35379        || p->eState==PAGER_READER
35380        || p->eState==PAGER_WRITER_LOCKED
35381        || p->eState==PAGER_WRITER_CACHEMOD
35382        || p->eState==PAGER_WRITER_DBMOD
35383        || p->eState==PAGER_WRITER_FINISHED
35384        || p->eState==PAGER_ERROR
35385   );
35386
35387   /* Regardless of the current state, a temp-file connection always behaves
35388   ** as if it has an exclusive lock on the database file. It never updates
35389   ** the change-counter field, so the changeCountDone flag is always set.
35390   */
35391   assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
35392   assert( p->tempFile==0 || pPager->changeCountDone );
35393
35394   /* If the useJournal flag is clear, the journal-mode must be "OFF". 
35395   ** And if the journal-mode is "OFF", the journal file must not be open.
35396   */
35397   assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
35398   assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
35399
35400   /* Check that MEMDB implies noSync. And an in-memory journal. Since 
35401   ** this means an in-memory pager performs no IO at all, it cannot encounter 
35402   ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing 
35403   ** a journal file. (although the in-memory journal implementation may 
35404   ** return SQLITE_IOERR_NOMEM while the journal file is being written). It 
35405   ** is therefore not possible for an in-memory pager to enter the ERROR 
35406   ** state.
35407   */
35408   if( MEMDB ){
35409     assert( p->noSync );
35410     assert( p->journalMode==PAGER_JOURNALMODE_OFF 
35411          || p->journalMode==PAGER_JOURNALMODE_MEMORY 
35412     );
35413     assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
35414     assert( pagerUseWal(p)==0 );
35415   }
35416
35417   /* If changeCountDone is set, a RESERVED lock or greater must be held
35418   ** on the file.
35419   */
35420   assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
35421   assert( p->eLock!=PENDING_LOCK );
35422
35423   switch( p->eState ){
35424     case PAGER_OPEN:
35425       assert( !MEMDB );
35426       assert( pPager->errCode==SQLITE_OK );
35427       assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
35428       break;
35429
35430     case PAGER_READER:
35431       assert( pPager->errCode==SQLITE_OK );
35432       assert( p->eLock!=UNKNOWN_LOCK );
35433       assert( p->eLock>=SHARED_LOCK || p->noReadlock );
35434       break;
35435
35436     case PAGER_WRITER_LOCKED:
35437       assert( p->eLock!=UNKNOWN_LOCK );
35438       assert( pPager->errCode==SQLITE_OK );
35439       if( !pagerUseWal(pPager) ){
35440         assert( p->eLock>=RESERVED_LOCK );
35441       }
35442       assert( pPager->dbSize==pPager->dbOrigSize );
35443       assert( pPager->dbOrigSize==pPager->dbFileSize );
35444       assert( pPager->dbOrigSize==pPager->dbHintSize );
35445       assert( pPager->setMaster==0 );
35446       break;
35447
35448     case PAGER_WRITER_CACHEMOD:
35449       assert( p->eLock!=UNKNOWN_LOCK );
35450       assert( pPager->errCode==SQLITE_OK );
35451       if( !pagerUseWal(pPager) ){
35452         /* It is possible that if journal_mode=wal here that neither the
35453         ** journal file nor the WAL file are open. This happens during
35454         ** a rollback transaction that switches from journal_mode=off
35455         ** to journal_mode=wal.
35456         */
35457         assert( p->eLock>=RESERVED_LOCK );
35458         assert( isOpen(p->jfd) 
35459              || p->journalMode==PAGER_JOURNALMODE_OFF 
35460              || p->journalMode==PAGER_JOURNALMODE_WAL 
35461         );
35462       }
35463       assert( pPager->dbOrigSize==pPager->dbFileSize );
35464       assert( pPager->dbOrigSize==pPager->dbHintSize );
35465       break;
35466
35467     case PAGER_WRITER_DBMOD:
35468       assert( p->eLock==EXCLUSIVE_LOCK );
35469       assert( pPager->errCode==SQLITE_OK );
35470       assert( !pagerUseWal(pPager) );
35471       assert( p->eLock>=EXCLUSIVE_LOCK );
35472       assert( isOpen(p->jfd) 
35473            || p->journalMode==PAGER_JOURNALMODE_OFF 
35474            || p->journalMode==PAGER_JOURNALMODE_WAL 
35475       );
35476       assert( pPager->dbOrigSize<=pPager->dbHintSize );
35477       break;
35478
35479     case PAGER_WRITER_FINISHED:
35480       assert( p->eLock==EXCLUSIVE_LOCK );
35481       assert( pPager->errCode==SQLITE_OK );
35482       assert( !pagerUseWal(pPager) );
35483       assert( isOpen(p->jfd) 
35484            || p->journalMode==PAGER_JOURNALMODE_OFF 
35485            || p->journalMode==PAGER_JOURNALMODE_WAL 
35486       );
35487       break;
35488
35489     case PAGER_ERROR:
35490       /* There must be at least one outstanding reference to the pager if
35491       ** in ERROR state. Otherwise the pager should have already dropped
35492       ** back to OPEN state.
35493       */
35494       assert( pPager->errCode!=SQLITE_OK );
35495       assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
35496       break;
35497   }
35498
35499   return 1;
35500 }
35501
35502 /*
35503 ** Return a pointer to a human readable string in a static buffer
35504 ** containing the state of the Pager object passed as an argument. This
35505 ** is intended to be used within debuggers. For example, as an alternative
35506 ** to "print *pPager" in gdb:
35507 **
35508 ** (gdb) printf "%s", print_pager_state(pPager)
35509 */
35510 static char *print_pager_state(Pager *p){
35511   static char zRet[1024];
35512
35513   sqlite3_snprintf(1024, zRet,
35514       "Filename:      %s\n"
35515       "State:         %s errCode=%d\n"
35516       "Lock:          %s\n"
35517       "Locking mode:  locking_mode=%s\n"
35518       "Journal mode:  journal_mode=%s\n"
35519       "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
35520       "Journal:       journalOff=%lld journalHdr=%lld\n"
35521       "Size:          dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
35522       , p->zFilename
35523       , p->eState==PAGER_OPEN            ? "OPEN" :
35524         p->eState==PAGER_READER          ? "READER" :
35525         p->eState==PAGER_WRITER_LOCKED   ? "WRITER_LOCKED" :
35526         p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
35527         p->eState==PAGER_WRITER_DBMOD    ? "WRITER_DBMOD" :
35528         p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
35529         p->eState==PAGER_ERROR           ? "ERROR" : "?error?"
35530       , (int)p->errCode
35531       , p->eLock==NO_LOCK         ? "NO_LOCK" :
35532         p->eLock==RESERVED_LOCK   ? "RESERVED" :
35533         p->eLock==EXCLUSIVE_LOCK  ? "EXCLUSIVE" :
35534         p->eLock==SHARED_LOCK     ? "SHARED" :
35535         p->eLock==UNKNOWN_LOCK    ? "UNKNOWN" : "?error?"
35536       , p->exclusiveMode ? "exclusive" : "normal"
35537       , p->journalMode==PAGER_JOURNALMODE_MEMORY   ? "memory" :
35538         p->journalMode==PAGER_JOURNALMODE_OFF      ? "off" :
35539         p->journalMode==PAGER_JOURNALMODE_DELETE   ? "delete" :
35540         p->journalMode==PAGER_JOURNALMODE_PERSIST  ? "persist" :
35541         p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
35542         p->journalMode==PAGER_JOURNALMODE_WAL      ? "wal" : "?error?"
35543       , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
35544       , p->journalOff, p->journalHdr
35545       , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
35546   );
35547
35548   return zRet;
35549 }
35550 #endif
35551
35552 /*
35553 ** Return true if it is necessary to write page *pPg into the sub-journal.
35554 ** A page needs to be written into the sub-journal if there exists one
35555 ** or more open savepoints for which:
35556 **
35557 **   * The page-number is less than or equal to PagerSavepoint.nOrig, and
35558 **   * The bit corresponding to the page-number is not set in
35559 **     PagerSavepoint.pInSavepoint.
35560 */
35561 static int subjRequiresPage(PgHdr *pPg){
35562   Pgno pgno = pPg->pgno;
35563   Pager *pPager = pPg->pPager;
35564   int i;
35565   for(i=0; i<pPager->nSavepoint; i++){
35566     PagerSavepoint *p = &pPager->aSavepoint[i];
35567     if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){
35568       return 1;
35569     }
35570   }
35571   return 0;
35572 }
35573
35574 /*
35575 ** Return true if the page is already in the journal file.
35576 */
35577 static int pageInJournal(PgHdr *pPg){
35578   return sqlite3BitvecTest(pPg->pPager->pInJournal, pPg->pgno);
35579 }
35580
35581 /*
35582 ** Read a 32-bit integer from the given file descriptor.  Store the integer
35583 ** that is read in *pRes.  Return SQLITE_OK if everything worked, or an
35584 ** error code is something goes wrong.
35585 **
35586 ** All values are stored on disk as big-endian.
35587 */
35588 static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
35589   unsigned char ac[4];
35590   int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
35591   if( rc==SQLITE_OK ){
35592     *pRes = sqlite3Get4byte(ac);
35593   }
35594   return rc;
35595 }
35596
35597 /*
35598 ** Write a 32-bit integer into a string buffer in big-endian byte order.
35599 */
35600 #define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)
35601
35602
35603 /*
35604 ** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
35605 ** on success or an error code is something goes wrong.
35606 */
35607 static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
35608   char ac[4];
35609   put32bits(ac, val);
35610   return sqlite3OsWrite(fd, ac, 4, offset);
35611 }
35612
35613 /*
35614 ** Unlock the database file to level eLock, which must be either NO_LOCK
35615 ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
35616 ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
35617 **
35618 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
35619 ** called, do not modify it. See the comment above the #define of 
35620 ** UNKNOWN_LOCK for an explanation of this.
35621 */
35622 static int pagerUnlockDb(Pager *pPager, int eLock){
35623   int rc = SQLITE_OK;
35624
35625   assert( !pPager->exclusiveMode );
35626   assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
35627   assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
35628   if( isOpen(pPager->fd) ){
35629     assert( pPager->eLock>=eLock );
35630     rc = sqlite3OsUnlock(pPager->fd, eLock);
35631     if( pPager->eLock!=UNKNOWN_LOCK ){
35632       pPager->eLock = (u8)eLock;
35633     }
35634     IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
35635   }
35636   return rc;
35637 }
35638
35639 /*
35640 ** Lock the database file to level eLock, which must be either SHARED_LOCK,
35641 ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
35642 ** Pager.eLock variable to the new locking state. 
35643 **
35644 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is 
35645 ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK. 
35646 ** See the comment above the #define of UNKNOWN_LOCK for an explanation 
35647 ** of this.
35648 */
35649 static int pagerLockDb(Pager *pPager, int eLock){
35650   int rc = SQLITE_OK;
35651
35652   assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
35653   if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
35654     rc = sqlite3OsLock(pPager->fd, eLock);
35655     if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
35656       pPager->eLock = (u8)eLock;
35657       IOTRACE(("LOCK %p %d\n", pPager, eLock))
35658     }
35659   }
35660   return rc;
35661 }
35662
35663 /*
35664 ** This function determines whether or not the atomic-write optimization
35665 ** can be used with this pager. The optimization can be used if:
35666 **
35667 **  (a) the value returned by OsDeviceCharacteristics() indicates that
35668 **      a database page may be written atomically, and
35669 **  (b) the value returned by OsSectorSize() is less than or equal
35670 **      to the page size.
35671 **
35672 ** The optimization is also always enabled for temporary files. It is
35673 ** an error to call this function if pPager is opened on an in-memory
35674 ** database.
35675 **
35676 ** If the optimization cannot be used, 0 is returned. If it can be used,
35677 ** then the value returned is the size of the journal file when it
35678 ** contains rollback data for exactly one page.
35679 */
35680 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
35681 static int jrnlBufferSize(Pager *pPager){
35682   assert( !MEMDB );
35683   if( !pPager->tempFile ){
35684     int dc;                           /* Device characteristics */
35685     int nSector;                      /* Sector size */
35686     int szPage;                       /* Page size */
35687
35688     assert( isOpen(pPager->fd) );
35689     dc = sqlite3OsDeviceCharacteristics(pPager->fd);
35690     nSector = pPager->sectorSize;
35691     szPage = pPager->pageSize;
35692
35693     assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
35694     assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
35695     if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
35696       return 0;
35697     }
35698   }
35699
35700   return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
35701 }
35702 #endif
35703
35704 /*
35705 ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
35706 ** on the cache using a hash function.  This is used for testing
35707 ** and debugging only.
35708 */
35709 #ifdef SQLITE_CHECK_PAGES
35710 /*
35711 ** Return a 32-bit hash of the page data for pPage.
35712 */
35713 static u32 pager_datahash(int nByte, unsigned char *pData){
35714   u32 hash = 0;
35715   int i;
35716   for(i=0; i<nByte; i++){
35717     hash = (hash*1039) + pData[i];
35718   }
35719   return hash;
35720 }
35721 static u32 pager_pagehash(PgHdr *pPage){
35722   return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
35723 }
35724 static void pager_set_pagehash(PgHdr *pPage){
35725   pPage->pageHash = pager_pagehash(pPage);
35726 }
35727
35728 /*
35729 ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
35730 ** is defined, and NDEBUG is not defined, an assert() statement checks
35731 ** that the page is either dirty or still matches the calculated page-hash.
35732 */
35733 #define CHECK_PAGE(x) checkPage(x)
35734 static void checkPage(PgHdr *pPg){
35735   Pager *pPager = pPg->pPager;
35736   assert( pPager->eState!=PAGER_ERROR );
35737   assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
35738 }
35739
35740 #else
35741 #define pager_datahash(X,Y)  0
35742 #define pager_pagehash(X)  0
35743 #define pager_set_pagehash(X)
35744 #define CHECK_PAGE(x)
35745 #endif  /* SQLITE_CHECK_PAGES */
35746
35747 /*
35748 ** When this is called the journal file for pager pPager must be open.
35749 ** This function attempts to read a master journal file name from the 
35750 ** end of the file and, if successful, copies it into memory supplied 
35751 ** by the caller. See comments above writeMasterJournal() for the format
35752 ** used to store a master journal file name at the end of a journal file.
35753 **
35754 ** zMaster must point to a buffer of at least nMaster bytes allocated by
35755 ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
35756 ** enough space to write the master journal name). If the master journal
35757 ** name in the journal is longer than nMaster bytes (including a
35758 ** nul-terminator), then this is handled as if no master journal name
35759 ** were present in the journal.
35760 **
35761 ** If a master journal file name is present at the end of the journal
35762 ** file, then it is copied into the buffer pointed to by zMaster. A
35763 ** nul-terminator byte is appended to the buffer following the master
35764 ** journal file name.
35765 **
35766 ** If it is determined that no master journal file name is present 
35767 ** zMaster[0] is set to 0 and SQLITE_OK returned.
35768 **
35769 ** If an error occurs while reading from the journal file, an SQLite
35770 ** error code is returned.
35771 */
35772 static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
35773   int rc;                    /* Return code */
35774   u32 len;                   /* Length in bytes of master journal name */
35775   i64 szJ;                   /* Total size in bytes of journal file pJrnl */
35776   u32 cksum;                 /* MJ checksum value read from journal */
35777   u32 u;                     /* Unsigned loop counter */
35778   unsigned char aMagic[8];   /* A buffer to hold the magic header */
35779   zMaster[0] = '\0';
35780
35781   if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
35782    || szJ<16
35783    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
35784    || len>=nMaster 
35785    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
35786    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
35787    || memcmp(aMagic, aJournalMagic, 8)
35788    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
35789   ){
35790     return rc;
35791   }
35792
35793   /* See if the checksum matches the master journal name */
35794   for(u=0; u<len; u++){
35795     cksum -= zMaster[u];
35796   }
35797   if( cksum ){
35798     /* If the checksum doesn't add up, then one or more of the disk sectors
35799     ** containing the master journal filename is corrupted. This means
35800     ** definitely roll back, so just return SQLITE_OK and report a (nul)
35801     ** master-journal filename.
35802     */
35803     len = 0;
35804   }
35805   zMaster[len] = '\0';
35806    
35807   return SQLITE_OK;
35808 }
35809
35810 /*
35811 ** Return the offset of the sector boundary at or immediately 
35812 ** following the value in pPager->journalOff, assuming a sector 
35813 ** size of pPager->sectorSize bytes.
35814 **
35815 ** i.e for a sector size of 512:
35816 **
35817 **   Pager.journalOff          Return value
35818 **   ---------------------------------------
35819 **   0                         0
35820 **   512                       512
35821 **   100                       512
35822 **   2000                      2048
35823 ** 
35824 */
35825 static i64 journalHdrOffset(Pager *pPager){
35826   i64 offset = 0;
35827   i64 c = pPager->journalOff;
35828   if( c ){
35829     offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
35830   }
35831   assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
35832   assert( offset>=c );
35833   assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
35834   return offset;
35835 }
35836
35837 /*
35838 ** The journal file must be open when this function is called.
35839 **
35840 ** This function is a no-op if the journal file has not been written to
35841 ** within the current transaction (i.e. if Pager.journalOff==0).
35842 **
35843 ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
35844 ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
35845 ** zero the 28-byte header at the start of the journal file. In either case, 
35846 ** if the pager is not in no-sync mode, sync the journal file immediately 
35847 ** after writing or truncating it.
35848 **
35849 ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
35850 ** following the truncation or zeroing described above the size of the 
35851 ** journal file in bytes is larger than this value, then truncate the
35852 ** journal file to Pager.journalSizeLimit bytes. The journal file does
35853 ** not need to be synced following this operation.
35854 **
35855 ** If an IO error occurs, abandon processing and return the IO error code.
35856 ** Otherwise, return SQLITE_OK.
35857 */
35858 static int zeroJournalHdr(Pager *pPager, int doTruncate){
35859   int rc = SQLITE_OK;                               /* Return code */
35860   assert( isOpen(pPager->jfd) );
35861   if( pPager->journalOff ){
35862     const i64 iLimit = pPager->journalSizeLimit;    /* Local cache of jsl */
35863
35864     IOTRACE(("JZEROHDR %p\n", pPager))
35865     if( doTruncate || iLimit==0 ){
35866       rc = sqlite3OsTruncate(pPager->jfd, 0);
35867     }else{
35868       static const char zeroHdr[28] = {0};
35869       rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
35870     }
35871     if( rc==SQLITE_OK && !pPager->noSync ){
35872       rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->sync_flags);
35873     }
35874
35875     /* At this point the transaction is committed but the write lock 
35876     ** is still held on the file. If there is a size limit configured for 
35877     ** the persistent journal and the journal file currently consumes more
35878     ** space than that limit allows for, truncate it now. There is no need
35879     ** to sync the file following this operation.
35880     */
35881     if( rc==SQLITE_OK && iLimit>0 ){
35882       i64 sz;
35883       rc = sqlite3OsFileSize(pPager->jfd, &sz);
35884       if( rc==SQLITE_OK && sz>iLimit ){
35885         rc = sqlite3OsTruncate(pPager->jfd, iLimit);
35886       }
35887     }
35888   }
35889   return rc;
35890 }
35891
35892 /*
35893 ** The journal file must be open when this routine is called. A journal
35894 ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
35895 ** current location.
35896 **
35897 ** The format for the journal header is as follows:
35898 ** - 8 bytes: Magic identifying journal format.
35899 ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
35900 ** - 4 bytes: Random number used for page hash.
35901 ** - 4 bytes: Initial database page count.
35902 ** - 4 bytes: Sector size used by the process that wrote this journal.
35903 ** - 4 bytes: Database page size.
35904 ** 
35905 ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
35906 */
35907 static int writeJournalHdr(Pager *pPager){
35908   int rc = SQLITE_OK;                 /* Return code */
35909   char *zHeader = pPager->pTmpSpace;  /* Temporary space used to build header */
35910   u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
35911   u32 nWrite;                         /* Bytes of header sector written */
35912   int ii;                             /* Loop counter */
35913
35914   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
35915
35916   if( nHeader>JOURNAL_HDR_SZ(pPager) ){
35917     nHeader = JOURNAL_HDR_SZ(pPager);
35918   }
35919
35920   /* If there are active savepoints and any of them were created 
35921   ** since the most recent journal header was written, update the 
35922   ** PagerSavepoint.iHdrOffset fields now.
35923   */
35924   for(ii=0; ii<pPager->nSavepoint; ii++){
35925     if( pPager->aSavepoint[ii].iHdrOffset==0 ){
35926       pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
35927     }
35928   }
35929
35930   pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
35931
35932   /* 
35933   ** Write the nRec Field - the number of page records that follow this
35934   ** journal header. Normally, zero is written to this value at this time.
35935   ** After the records are added to the journal (and the journal synced, 
35936   ** if in full-sync mode), the zero is overwritten with the true number
35937   ** of records (see syncJournal()).
35938   **
35939   ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
35940   ** reading the journal this value tells SQLite to assume that the
35941   ** rest of the journal file contains valid page records. This assumption
35942   ** is dangerous, as if a failure occurred whilst writing to the journal
35943   ** file it may contain some garbage data. There are two scenarios
35944   ** where this risk can be ignored:
35945   **
35946   **   * When the pager is in no-sync mode. Corruption can follow a
35947   **     power failure in this case anyway.
35948   **
35949   **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
35950   **     that garbage data is never appended to the journal file.
35951   */
35952   assert( isOpen(pPager->fd) || pPager->noSync );
35953   if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
35954    || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND) 
35955   ){
35956     memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
35957     put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
35958   }else{
35959     memset(zHeader, 0, sizeof(aJournalMagic)+4);
35960   }
35961
35962   /* The random check-hash initialiser */ 
35963   sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
35964   put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
35965   /* The initial database size */
35966   put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
35967   /* The assumed sector size for this process */
35968   put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
35969
35970   /* The page size */
35971   put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
35972
35973   /* Initializing the tail of the buffer is not necessary.  Everything
35974   ** works find if the following memset() is omitted.  But initializing
35975   ** the memory prevents valgrind from complaining, so we are willing to
35976   ** take the performance hit.
35977   */
35978   memset(&zHeader[sizeof(aJournalMagic)+20], 0,
35979          nHeader-(sizeof(aJournalMagic)+20));
35980
35981   /* In theory, it is only necessary to write the 28 bytes that the 
35982   ** journal header consumes to the journal file here. Then increment the 
35983   ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next 
35984   ** record is written to the following sector (leaving a gap in the file
35985   ** that will be implicitly filled in by the OS).
35986   **
35987   ** However it has been discovered that on some systems this pattern can 
35988   ** be significantly slower than contiguously writing data to the file,
35989   ** even if that means explicitly writing data to the block of 
35990   ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
35991   ** is done. 
35992   **
35993   ** The loop is required here in case the sector-size is larger than the 
35994   ** database page size. Since the zHeader buffer is only Pager.pageSize
35995   ** bytes in size, more than one call to sqlite3OsWrite() may be required
35996   ** to populate the entire journal header sector.
35997   */ 
35998   for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
35999     IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
36000     rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
36001     assert( pPager->journalHdr <= pPager->journalOff );
36002     pPager->journalOff += nHeader;
36003   }
36004
36005   return rc;
36006 }
36007
36008 /*
36009 ** The journal file must be open when this is called. A journal header file
36010 ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
36011 ** file. The current location in the journal file is given by
36012 ** pPager->journalOff. See comments above function writeJournalHdr() for
36013 ** a description of the journal header format.
36014 **
36015 ** If the header is read successfully, *pNRec is set to the number of
36016 ** page records following this header and *pDbSize is set to the size of the
36017 ** database before the transaction began, in pages. Also, pPager->cksumInit
36018 ** is set to the value read from the journal header. SQLITE_OK is returned
36019 ** in this case.
36020 **
36021 ** If the journal header file appears to be corrupted, SQLITE_DONE is
36022 ** returned and *pNRec and *PDbSize are undefined.  If JOURNAL_HDR_SZ bytes
36023 ** cannot be read from the journal file an error code is returned.
36024 */
36025 static int readJournalHdr(
36026   Pager *pPager,               /* Pager object */
36027   int isHot,
36028   i64 journalSize,             /* Size of the open journal file in bytes */
36029   u32 *pNRec,                  /* OUT: Value read from the nRec field */
36030   u32 *pDbSize                 /* OUT: Value of original database size field */
36031 ){
36032   int rc;                      /* Return code */
36033   unsigned char aMagic[8];     /* A buffer to hold the magic header */
36034   i64 iHdrOff;                 /* Offset of journal header being read */
36035
36036   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
36037
36038   /* Advance Pager.journalOff to the start of the next sector. If the
36039   ** journal file is too small for there to be a header stored at this
36040   ** point, return SQLITE_DONE.
36041   */
36042   pPager->journalOff = journalHdrOffset(pPager);
36043   if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
36044     return SQLITE_DONE;
36045   }
36046   iHdrOff = pPager->journalOff;
36047
36048   /* Read in the first 8 bytes of the journal header. If they do not match
36049   ** the  magic string found at the start of each journal header, return
36050   ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
36051   ** proceed.
36052   */
36053   if( isHot || iHdrOff!=pPager->journalHdr ){
36054     rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
36055     if( rc ){
36056       return rc;
36057     }
36058     if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
36059       return SQLITE_DONE;
36060     }
36061   }
36062
36063   /* Read the first three 32-bit fields of the journal header: The nRec
36064   ** field, the checksum-initializer and the database size at the start
36065   ** of the transaction. Return an error code if anything goes wrong.
36066   */
36067   if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
36068    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
36069    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
36070   ){
36071     return rc;
36072   }
36073
36074   if( pPager->journalOff==0 ){
36075     u32 iPageSize;               /* Page-size field of journal header */
36076     u32 iSectorSize;             /* Sector-size field of journal header */
36077
36078     /* Read the page-size and sector-size journal header fields. */
36079     if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
36080      || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
36081     ){
36082       return rc;
36083     }
36084
36085     /* Versions of SQLite prior to 3.5.8 set the page-size field of the
36086     ** journal header to zero. In this case, assume that the Pager.pageSize
36087     ** variable is already set to the correct page size.
36088     */
36089     if( iPageSize==0 ){
36090       iPageSize = pPager->pageSize;
36091     }
36092
36093     /* Check that the values read from the page-size and sector-size fields
36094     ** are within range. To be 'in range', both values need to be a power
36095     ** of two greater than or equal to 512 or 32, and not greater than their 
36096     ** respective compile time maximum limits.
36097     */
36098     if( iPageSize<512                  || iSectorSize<32
36099      || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
36100      || ((iPageSize-1)&iPageSize)!=0   || ((iSectorSize-1)&iSectorSize)!=0 
36101     ){
36102       /* If the either the page-size or sector-size in the journal-header is 
36103       ** invalid, then the process that wrote the journal-header must have 
36104       ** crashed before the header was synced. In this case stop reading 
36105       ** the journal file here.
36106       */
36107       return SQLITE_DONE;
36108     }
36109
36110     /* Update the page-size to match the value read from the journal. 
36111     ** Use a testcase() macro to make sure that malloc failure within 
36112     ** PagerSetPagesize() is tested.
36113     */
36114     rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
36115     testcase( rc!=SQLITE_OK );
36116
36117     /* Update the assumed sector-size to match the value used by 
36118     ** the process that created this journal. If this journal was
36119     ** created by a process other than this one, then this routine
36120     ** is being called from within pager_playback(). The local value
36121     ** of Pager.sectorSize is restored at the end of that routine.
36122     */
36123     pPager->sectorSize = iSectorSize;
36124   }
36125
36126   pPager->journalOff += JOURNAL_HDR_SZ(pPager);
36127   return rc;
36128 }
36129
36130
36131 /*
36132 ** Write the supplied master journal name into the journal file for pager
36133 ** pPager at the current location. The master journal name must be the last
36134 ** thing written to a journal file. If the pager is in full-sync mode, the
36135 ** journal file descriptor is advanced to the next sector boundary before
36136 ** anything is written. The format is:
36137 **
36138 **   + 4 bytes: PAGER_MJ_PGNO.
36139 **   + N bytes: Master journal filename in utf-8.
36140 **   + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
36141 **   + 4 bytes: Master journal name checksum.
36142 **   + 8 bytes: aJournalMagic[].
36143 **
36144 ** The master journal page checksum is the sum of the bytes in the master
36145 ** journal name, where each byte is interpreted as a signed 8-bit integer.
36146 **
36147 ** If zMaster is a NULL pointer (occurs for a single database transaction), 
36148 ** this call is a no-op.
36149 */
36150 static int writeMasterJournal(Pager *pPager, const char *zMaster){
36151   int rc;                          /* Return code */
36152   int nMaster;                     /* Length of string zMaster */
36153   i64 iHdrOff;                     /* Offset of header in journal file */
36154   i64 jrnlSize;                    /* Size of journal file on disk */
36155   u32 cksum = 0;                   /* Checksum of string zMaster */
36156
36157   assert( pPager->setMaster==0 );
36158   assert( !pagerUseWal(pPager) );
36159
36160   if( !zMaster 
36161    || pPager->journalMode==PAGER_JOURNALMODE_MEMORY 
36162    || pPager->journalMode==PAGER_JOURNALMODE_OFF 
36163   ){
36164     return SQLITE_OK;
36165   }
36166   pPager->setMaster = 1;
36167   assert( isOpen(pPager->jfd) );
36168   assert( pPager->journalHdr <= pPager->journalOff );
36169
36170   /* Calculate the length in bytes and the checksum of zMaster */
36171   for(nMaster=0; zMaster[nMaster]; nMaster++){
36172     cksum += zMaster[nMaster];
36173   }
36174
36175   /* If in full-sync mode, advance to the next disk sector before writing
36176   ** the master journal name. This is in case the previous page written to
36177   ** the journal has already been synced.
36178   */
36179   if( pPager->fullSync ){
36180     pPager->journalOff = journalHdrOffset(pPager);
36181   }
36182   iHdrOff = pPager->journalOff;
36183
36184   /* Write the master journal data to the end of the journal file. If
36185   ** an error occurs, return the error code to the caller.
36186   */
36187   if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
36188    || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
36189    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
36190    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
36191    || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))
36192   ){
36193     return rc;
36194   }
36195   pPager->journalOff += (nMaster+20);
36196
36197   /* If the pager is in peristent-journal mode, then the physical 
36198   ** journal-file may extend past the end of the master-journal name
36199   ** and 8 bytes of magic data just written to the file. This is 
36200   ** dangerous because the code to rollback a hot-journal file
36201   ** will not be able to find the master-journal name to determine 
36202   ** whether or not the journal is hot. 
36203   **
36204   ** Easiest thing to do in this scenario is to truncate the journal 
36205   ** file to the required size.
36206   */ 
36207   if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
36208    && jrnlSize>pPager->journalOff
36209   ){
36210     rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
36211   }
36212   return rc;
36213 }
36214
36215 /*
36216 ** Find a page in the hash table given its page number. Return
36217 ** a pointer to the page or NULL if the requested page is not 
36218 ** already in memory.
36219 */
36220 static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
36221   PgHdr *p;                         /* Return value */
36222
36223   /* It is not possible for a call to PcacheFetch() with createFlag==0 to
36224   ** fail, since no attempt to allocate dynamic memory will be made.
36225   */
36226   (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &p);
36227   return p;
36228 }
36229
36230 /*
36231 ** Discard the entire contents of the in-memory page-cache.
36232 */
36233 static void pager_reset(Pager *pPager){
36234   sqlite3BackupRestart(pPager->pBackup);
36235   sqlite3PcacheClear(pPager->pPCache);
36236 }
36237
36238 /*
36239 ** Free all structures in the Pager.aSavepoint[] array and set both
36240 ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
36241 ** if it is open and the pager is not in exclusive mode.
36242 */
36243 static void releaseAllSavepoints(Pager *pPager){
36244   int ii;               /* Iterator for looping through Pager.aSavepoint */
36245   for(ii=0; ii<pPager->nSavepoint; ii++){
36246     sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
36247   }
36248   if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
36249     sqlite3OsClose(pPager->sjfd);
36250   }
36251   sqlite3_free(pPager->aSavepoint);
36252   pPager->aSavepoint = 0;
36253   pPager->nSavepoint = 0;
36254   pPager->nSubRec = 0;
36255 }
36256
36257 /*
36258 ** Set the bit number pgno in the PagerSavepoint.pInSavepoint 
36259 ** bitvecs of all open savepoints. Return SQLITE_OK if successful
36260 ** or SQLITE_NOMEM if a malloc failure occurs.
36261 */
36262 static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
36263   int ii;                   /* Loop counter */
36264   int rc = SQLITE_OK;       /* Result code */
36265
36266   for(ii=0; ii<pPager->nSavepoint; ii++){
36267     PagerSavepoint *p = &pPager->aSavepoint[ii];
36268     if( pgno<=p->nOrig ){
36269       rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
36270       testcase( rc==SQLITE_NOMEM );
36271       assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
36272     }
36273   }
36274   return rc;
36275 }
36276
36277 /*
36278 ** This function is a no-op if the pager is in exclusive mode and not
36279 ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
36280 ** state.
36281 **
36282 ** If the pager is not in exclusive-access mode, the database file is
36283 ** completely unlocked. If the file is unlocked and the file-system does
36284 ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
36285 ** closed (if it is open).
36286 **
36287 ** If the pager is in ERROR state when this function is called, the 
36288 ** contents of the pager cache are discarded before switching back to 
36289 ** the OPEN state. Regardless of whether the pager is in exclusive-mode
36290 ** or not, any journal file left in the file-system will be treated
36291 ** as a hot-journal and rolled back the next time a read-transaction
36292 ** is opened (by this or by any other connection).
36293 */
36294 static void pager_unlock(Pager *pPager){
36295
36296   assert( pPager->eState==PAGER_READER 
36297        || pPager->eState==PAGER_OPEN 
36298        || pPager->eState==PAGER_ERROR 
36299   );
36300
36301   sqlite3BitvecDestroy(pPager->pInJournal);
36302   pPager->pInJournal = 0;
36303   releaseAllSavepoints(pPager);
36304
36305   if( pagerUseWal(pPager) ){
36306     assert( !isOpen(pPager->jfd) );
36307     sqlite3WalEndReadTransaction(pPager->pWal);
36308     pPager->eState = PAGER_OPEN;
36309   }else if( !pPager->exclusiveMode ){
36310     int rc;                       /* Error code returned by pagerUnlockDb() */
36311     int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
36312
36313     /* If the operating system support deletion of open files, then
36314     ** close the journal file when dropping the database lock.  Otherwise
36315     ** another connection with journal_mode=delete might delete the file
36316     ** out from under us.
36317     */
36318     assert( (PAGER_JOURNALMODE_MEMORY   & 5)!=1 );
36319     assert( (PAGER_JOURNALMODE_OFF      & 5)!=1 );
36320     assert( (PAGER_JOURNALMODE_WAL      & 5)!=1 );
36321     assert( (PAGER_JOURNALMODE_DELETE   & 5)!=1 );
36322     assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
36323     assert( (PAGER_JOURNALMODE_PERSIST  & 5)==1 );
36324     if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
36325      || 1!=(pPager->journalMode & 5)
36326     ){
36327       sqlite3OsClose(pPager->jfd);
36328     }
36329
36330     /* If the pager is in the ERROR state and the call to unlock the database
36331     ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
36332     ** above the #define for UNKNOWN_LOCK for an explanation of why this
36333     ** is necessary.
36334     */
36335     rc = pagerUnlockDb(pPager, NO_LOCK);
36336     if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
36337       pPager->eLock = UNKNOWN_LOCK;
36338     }
36339
36340     /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
36341     ** without clearing the error code. This is intentional - the error
36342     ** code is cleared and the cache reset in the block below.
36343     */
36344     assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
36345     pPager->changeCountDone = 0;
36346     pPager->eState = PAGER_OPEN;
36347   }
36348
36349   /* If Pager.errCode is set, the contents of the pager cache cannot be
36350   ** trusted. Now that there are no outstanding references to the pager,
36351   ** it can safely move back to PAGER_OPEN state. This happens in both
36352   ** normal and exclusive-locking mode.
36353   */
36354   if( pPager->errCode ){
36355     assert( !MEMDB );
36356     pager_reset(pPager);
36357     pPager->changeCountDone = pPager->tempFile;
36358     pPager->eState = PAGER_OPEN;
36359     pPager->errCode = SQLITE_OK;
36360   }
36361
36362   pPager->journalOff = 0;
36363   pPager->journalHdr = 0;
36364   pPager->setMaster = 0;
36365 }
36366
36367 /*
36368 ** This function is called whenever an IOERR or FULL error that requires
36369 ** the pager to transition into the ERROR state may ahve occurred.
36370 ** The first argument is a pointer to the pager structure, the second 
36371 ** the error-code about to be returned by a pager API function. The 
36372 ** value returned is a copy of the second argument to this function. 
36373 **
36374 ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
36375 ** IOERR sub-codes, the pager enters the ERROR state and the error code
36376 ** is stored in Pager.errCode. While the pager remains in the ERROR state,
36377 ** all major API calls on the Pager will immediately return Pager.errCode.
36378 **
36379 ** The ERROR state indicates that the contents of the pager-cache 
36380 ** cannot be trusted. This state can be cleared by completely discarding 
36381 ** the contents of the pager-cache. If a transaction was active when
36382 ** the persistent error occurred, then the rollback journal may need
36383 ** to be replayed to restore the contents of the database file (as if
36384 ** it were a hot-journal).
36385 */
36386 static int pager_error(Pager *pPager, int rc){
36387   int rc2 = rc & 0xff;
36388   assert( rc==SQLITE_OK || !MEMDB );
36389   assert(
36390        pPager->errCode==SQLITE_FULL ||
36391        pPager->errCode==SQLITE_OK ||
36392        (pPager->errCode & 0xff)==SQLITE_IOERR
36393   );
36394   if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
36395     pPager->errCode = rc;
36396     pPager->eState = PAGER_ERROR;
36397   }
36398   return rc;
36399 }
36400
36401 /*
36402 ** This routine ends a transaction. A transaction is usually ended by 
36403 ** either a COMMIT or a ROLLBACK operation. This routine may be called 
36404 ** after rollback of a hot-journal, or if an error occurs while opening
36405 ** the journal file or writing the very first journal-header of a
36406 ** database transaction.
36407 ** 
36408 ** This routine is never called in PAGER_ERROR state. If it is called
36409 ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
36410 ** exclusive than a RESERVED lock, it is a no-op.
36411 **
36412 ** Otherwise, any active savepoints are released.
36413 **
36414 ** If the journal file is open, then it is "finalized". Once a journal 
36415 ** file has been finalized it is not possible to use it to roll back a 
36416 ** transaction. Nor will it be considered to be a hot-journal by this
36417 ** or any other database connection. Exactly how a journal is finalized
36418 ** depends on whether or not the pager is running in exclusive mode and
36419 ** the current journal-mode (Pager.journalMode value), as follows:
36420 **
36421 **   journalMode==MEMORY
36422 **     Journal file descriptor is simply closed. This destroys an 
36423 **     in-memory journal.
36424 **
36425 **   journalMode==TRUNCATE
36426 **     Journal file is truncated to zero bytes in size.
36427 **
36428 **   journalMode==PERSIST
36429 **     The first 28 bytes of the journal file are zeroed. This invalidates
36430 **     the first journal header in the file, and hence the entire journal
36431 **     file. An invalid journal file cannot be rolled back.
36432 **
36433 **   journalMode==DELETE
36434 **     The journal file is closed and deleted using sqlite3OsDelete().
36435 **
36436 **     If the pager is running in exclusive mode, this method of finalizing
36437 **     the journal file is never used. Instead, if the journalMode is
36438 **     DELETE and the pager is in exclusive mode, the method described under
36439 **     journalMode==PERSIST is used instead.
36440 **
36441 ** After the journal is finalized, the pager moves to PAGER_READER state.
36442 ** If running in non-exclusive rollback mode, the lock on the file is 
36443 ** downgraded to a SHARED_LOCK.
36444 **
36445 ** SQLITE_OK is returned if no error occurs. If an error occurs during
36446 ** any of the IO operations to finalize the journal file or unlock the
36447 ** database then the IO error code is returned to the user. If the 
36448 ** operation to finalize the journal file fails, then the code still
36449 ** tries to unlock the database file if not in exclusive mode. If the
36450 ** unlock operation fails as well, then the first error code related
36451 ** to the first error encountered (the journal finalization one) is
36452 ** returned.
36453 */
36454 static int pager_end_transaction(Pager *pPager, int hasMaster){
36455   int rc = SQLITE_OK;      /* Error code from journal finalization operation */
36456   int rc2 = SQLITE_OK;     /* Error code from db file unlock operation */
36457
36458   /* Do nothing if the pager does not have an open write transaction
36459   ** or at least a RESERVED lock. This function may be called when there
36460   ** is no write-transaction active but a RESERVED or greater lock is
36461   ** held under two circumstances:
36462   **
36463   **   1. After a successful hot-journal rollback, it is called with
36464   **      eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
36465   **
36466   **   2. If a connection with locking_mode=exclusive holding an EXCLUSIVE 
36467   **      lock switches back to locking_mode=normal and then executes a
36468   **      read-transaction, this function is called with eState==PAGER_READER 
36469   **      and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
36470   */
36471   assert( assert_pager_state(pPager) );
36472   assert( pPager->eState!=PAGER_ERROR );
36473   if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
36474     return SQLITE_OK;
36475   }
36476
36477   releaseAllSavepoints(pPager);
36478   assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
36479   if( isOpen(pPager->jfd) ){
36480     assert( !pagerUseWal(pPager) );
36481
36482     /* Finalize the journal file. */
36483     if( sqlite3IsMemJournal(pPager->jfd) ){
36484       assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
36485       sqlite3OsClose(pPager->jfd);
36486     }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
36487       if( pPager->journalOff==0 ){
36488         rc = SQLITE_OK;
36489       }else{
36490         rc = sqlite3OsTruncate(pPager->jfd, 0);
36491       }
36492       pPager->journalOff = 0;
36493     }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
36494       || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
36495     ){
36496       rc = zeroJournalHdr(pPager, hasMaster);
36497       pPager->journalOff = 0;
36498     }else{
36499       /* This branch may be executed with Pager.journalMode==MEMORY if
36500       ** a hot-journal was just rolled back. In this case the journal
36501       ** file should be closed and deleted. If this connection writes to
36502       ** the database file, it will do so using an in-memory journal. 
36503       */
36504       assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE 
36505            || pPager->journalMode==PAGER_JOURNALMODE_MEMORY 
36506            || pPager->journalMode==PAGER_JOURNALMODE_WAL 
36507       );
36508       sqlite3OsClose(pPager->jfd);
36509       if( !pPager->tempFile ){
36510         rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
36511       }
36512     }
36513   }
36514
36515 #ifdef SQLITE_CHECK_PAGES
36516   sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
36517   if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
36518     PgHdr *p = pager_lookup(pPager, 1);
36519     if( p ){
36520       p->pageHash = 0;
36521       sqlite3PagerUnref(p);
36522     }
36523   }
36524 #endif
36525
36526   sqlite3BitvecDestroy(pPager->pInJournal);
36527   pPager->pInJournal = 0;
36528   pPager->nRec = 0;
36529   sqlite3PcacheCleanAll(pPager->pPCache);
36530   sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
36531
36532   if( pagerUseWal(pPager) ){
36533     /* Drop the WAL write-lock, if any. Also, if the connection was in 
36534     ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE 
36535     ** lock held on the database file.
36536     */
36537     rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
36538     assert( rc2==SQLITE_OK );
36539   }
36540   if( !pPager->exclusiveMode 
36541    && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
36542   ){
36543     rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
36544     pPager->changeCountDone = 0;
36545   }
36546   pPager->eState = PAGER_READER;
36547   pPager->setMaster = 0;
36548
36549   return (rc==SQLITE_OK?rc2:rc);
36550 }
36551
36552 /*
36553 ** Execute a rollback if a transaction is active and unlock the 
36554 ** database file. 
36555 **
36556 ** If the pager has already entered the ERROR state, do not attempt 
36557 ** the rollback at this time. Instead, pager_unlock() is called. The
36558 ** call to pager_unlock() will discard all in-memory pages, unlock
36559 ** the database file and move the pager back to OPEN state. If this 
36560 ** means that there is a hot-journal left in the file-system, the next 
36561 ** connection to obtain a shared lock on the pager (which may be this one) 
36562 ** will roll it back.
36563 **
36564 ** If the pager has not already entered the ERROR state, but an IO or
36565 ** malloc error occurs during a rollback, then this will itself cause 
36566 ** the pager to enter the ERROR state. Which will be cleared by the
36567 ** call to pager_unlock(), as described above.
36568 */
36569 static void pagerUnlockAndRollback(Pager *pPager){
36570   if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
36571     assert( assert_pager_state(pPager) );
36572     if( pPager->eState>=PAGER_WRITER_LOCKED ){
36573       sqlite3BeginBenignMalloc();
36574       sqlite3PagerRollback(pPager);
36575       sqlite3EndBenignMalloc();
36576     }else if( !pPager->exclusiveMode ){
36577       assert( pPager->eState==PAGER_READER );
36578       pager_end_transaction(pPager, 0);
36579     }
36580   }
36581   pager_unlock(pPager);
36582 }
36583
36584 /*
36585 ** Parameter aData must point to a buffer of pPager->pageSize bytes
36586 ** of data. Compute and return a checksum based ont the contents of the 
36587 ** page of data and the current value of pPager->cksumInit.
36588 **
36589 ** This is not a real checksum. It is really just the sum of the 
36590 ** random initial value (pPager->cksumInit) and every 200th byte
36591 ** of the page data, starting with byte offset (pPager->pageSize%200).
36592 ** Each byte is interpreted as an 8-bit unsigned integer.
36593 **
36594 ** Changing the formula used to compute this checksum results in an
36595 ** incompatible journal file format.
36596 **
36597 ** If journal corruption occurs due to a power failure, the most likely 
36598 ** scenario is that one end or the other of the record will be changed. 
36599 ** It is much less likely that the two ends of the journal record will be
36600 ** correct and the middle be corrupt.  Thus, this "checksum" scheme,
36601 ** though fast and simple, catches the mostly likely kind of corruption.
36602 */
36603 static u32 pager_cksum(Pager *pPager, const u8 *aData){
36604   u32 cksum = pPager->cksumInit;         /* Checksum value to return */
36605   int i = pPager->pageSize-200;          /* Loop counter */
36606   while( i>0 ){
36607     cksum += aData[i];
36608     i -= 200;
36609   }
36610   return cksum;
36611 }
36612
36613 /*
36614 ** Report the current page size and number of reserved bytes back
36615 ** to the codec.
36616 */
36617 #ifdef SQLITE_HAS_CODEC
36618 static void pagerReportSize(Pager *pPager){
36619   if( pPager->xCodecSizeChng ){
36620     pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
36621                            (int)pPager->nReserve);
36622   }
36623 }
36624 #else
36625 # define pagerReportSize(X)     /* No-op if we do not support a codec */
36626 #endif
36627
36628 /*
36629 ** Read a single page from either the journal file (if isMainJrnl==1) or
36630 ** from the sub-journal (if isMainJrnl==0) and playback that page.
36631 ** The page begins at offset *pOffset into the file. The *pOffset
36632 ** value is increased to the start of the next page in the journal.
36633 **
36634 ** The main rollback journal uses checksums - the statement journal does 
36635 ** not.
36636 **
36637 ** If the page number of the page record read from the (sub-)journal file
36638 ** is greater than the current value of Pager.dbSize, then playback is
36639 ** skipped and SQLITE_OK is returned.
36640 **
36641 ** If pDone is not NULL, then it is a record of pages that have already
36642 ** been played back.  If the page at *pOffset has already been played back
36643 ** (if the corresponding pDone bit is set) then skip the playback.
36644 ** Make sure the pDone bit corresponding to the *pOffset page is set
36645 ** prior to returning.
36646 **
36647 ** If the page record is successfully read from the (sub-)journal file
36648 ** and played back, then SQLITE_OK is returned. If an IO error occurs
36649 ** while reading the record from the (sub-)journal file or while writing
36650 ** to the database file, then the IO error code is returned. If data
36651 ** is successfully read from the (sub-)journal file but appears to be
36652 ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
36653 ** two circumstances:
36654 ** 
36655 **   * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
36656 **   * If the record is being rolled back from the main journal file
36657 **     and the checksum field does not match the record content.
36658 **
36659 ** Neither of these two scenarios are possible during a savepoint rollback.
36660 **
36661 ** If this is a savepoint rollback, then memory may have to be dynamically
36662 ** allocated by this function. If this is the case and an allocation fails,
36663 ** SQLITE_NOMEM is returned.
36664 */
36665 static int pager_playback_one_page(
36666   Pager *pPager,                /* The pager being played back */
36667   i64 *pOffset,                 /* Offset of record to playback */
36668   Bitvec *pDone,                /* Bitvec of pages already played back */
36669   int isMainJrnl,               /* 1 -> main journal. 0 -> sub-journal. */
36670   int isSavepnt                 /* True for a savepoint rollback */
36671 ){
36672   int rc;
36673   PgHdr *pPg;                   /* An existing page in the cache */
36674   Pgno pgno;                    /* The page number of a page in journal */
36675   u32 cksum;                    /* Checksum used for sanity checking */
36676   char *aData;                  /* Temporary storage for the page */
36677   sqlite3_file *jfd;            /* The file descriptor for the journal file */
36678   int isSynced;                 /* True if journal page is synced */
36679
36680   assert( (isMainJrnl&~1)==0 );      /* isMainJrnl is 0 or 1 */
36681   assert( (isSavepnt&~1)==0 );       /* isSavepnt is 0 or 1 */
36682   assert( isMainJrnl || pDone );     /* pDone always used on sub-journals */
36683   assert( isSavepnt || pDone==0 );   /* pDone never used on non-savepoint */
36684
36685   aData = pPager->pTmpSpace;
36686   assert( aData );         /* Temp storage must have already been allocated */
36687   assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
36688
36689   /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction 
36690   ** or savepoint rollback done at the request of the caller) or this is
36691   ** a hot-journal rollback. If it is a hot-journal rollback, the pager
36692   ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
36693   ** only reads from the main journal, not the sub-journal.
36694   */
36695   assert( pPager->eState>=PAGER_WRITER_CACHEMOD
36696        || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
36697   );
36698   assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
36699
36700   /* Read the page number and page data from the journal or sub-journal
36701   ** file. Return an error code to the caller if an IO error occurs.
36702   */
36703   jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
36704   rc = read32bits(jfd, *pOffset, &pgno);
36705   if( rc!=SQLITE_OK ) return rc;
36706   rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
36707   if( rc!=SQLITE_OK ) return rc;
36708   *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
36709
36710   /* Sanity checking on the page.  This is more important that I originally
36711   ** thought.  If a power failure occurs while the journal is being written,
36712   ** it could cause invalid data to be written into the journal.  We need to
36713   ** detect this invalid data (with high probability) and ignore it.
36714   */
36715   if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
36716     assert( !isSavepnt );
36717     return SQLITE_DONE;
36718   }
36719   if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
36720     return SQLITE_OK;
36721   }
36722   if( isMainJrnl ){
36723     rc = read32bits(jfd, (*pOffset)-4, &cksum);
36724     if( rc ) return rc;
36725     if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
36726       return SQLITE_DONE;
36727     }
36728   }
36729
36730   /* If this page has already been played by before during the current
36731   ** rollback, then don't bother to play it back again.
36732   */
36733   if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
36734     return rc;
36735   }
36736
36737   /* When playing back page 1, restore the nReserve setting
36738   */
36739   if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
36740     pPager->nReserve = ((u8*)aData)[20];
36741     pagerReportSize(pPager);
36742   }
36743
36744   /* If the pager is in CACHEMOD state, then there must be a copy of this
36745   ** page in the pager cache. In this case just update the pager cache,
36746   ** not the database file. The page is left marked dirty in this case.
36747   **
36748   ** An exception to the above rule: If the database is in no-sync mode
36749   ** and a page is moved during an incremental vacuum then the page may
36750   ** not be in the pager cache. Later: if a malloc() or IO error occurs
36751   ** during a Movepage() call, then the page may not be in the cache
36752   ** either. So the condition described in the above paragraph is not
36753   ** assert()able.
36754   **
36755   ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
36756   ** pager cache if it exists and the main file. The page is then marked 
36757   ** not dirty. Since this code is only executed in PAGER_OPEN state for
36758   ** a hot-journal rollback, it is guaranteed that the page-cache is empty
36759   ** if the pager is in OPEN state.
36760   **
36761   ** Ticket #1171:  The statement journal might contain page content that is
36762   ** different from the page content at the start of the transaction.
36763   ** This occurs when a page is changed prior to the start of a statement
36764   ** then changed again within the statement.  When rolling back such a
36765   ** statement we must not write to the original database unless we know
36766   ** for certain that original page contents are synced into the main rollback
36767   ** journal.  Otherwise, a power loss might leave modified data in the
36768   ** database file without an entry in the rollback journal that can
36769   ** restore the database to its original form.  Two conditions must be
36770   ** met before writing to the database files. (1) the database must be
36771   ** locked.  (2) we know that the original page content is fully synced
36772   ** in the main journal either because the page is not in cache or else
36773   ** the page is marked as needSync==0.
36774   **
36775   ** 2008-04-14:  When attempting to vacuum a corrupt database file, it
36776   ** is possible to fail a statement on a database that does not yet exist.
36777   ** Do not attempt to write if database file has never been opened.
36778   */
36779   if( pagerUseWal(pPager) ){
36780     pPg = 0;
36781   }else{
36782     pPg = pager_lookup(pPager, pgno);
36783   }
36784   assert( pPg || !MEMDB );
36785   assert( pPager->eState!=PAGER_OPEN || pPg==0 );
36786   PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
36787            PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
36788            (isMainJrnl?"main-journal":"sub-journal")
36789   ));
36790   if( isMainJrnl ){
36791     isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
36792   }else{
36793     isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
36794   }
36795   if( isOpen(pPager->fd)
36796    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
36797    && isSynced
36798   ){
36799     i64 ofst = (pgno-1)*(i64)pPager->pageSize;
36800     testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
36801     assert( !pagerUseWal(pPager) );
36802     rc = sqlite3OsWrite(pPager->fd, (u8*)aData, pPager->pageSize, ofst);
36803     if( pgno>pPager->dbFileSize ){
36804       pPager->dbFileSize = pgno;
36805     }
36806     if( pPager->pBackup ){
36807       CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
36808       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
36809       CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
36810     }
36811   }else if( !isMainJrnl && pPg==0 ){
36812     /* If this is a rollback of a savepoint and data was not written to
36813     ** the database and the page is not in-memory, there is a potential
36814     ** problem. When the page is next fetched by the b-tree layer, it 
36815     ** will be read from the database file, which may or may not be 
36816     ** current. 
36817     **
36818     ** There are a couple of different ways this can happen. All are quite
36819     ** obscure. When running in synchronous mode, this can only happen 
36820     ** if the page is on the free-list at the start of the transaction, then
36821     ** populated, then moved using sqlite3PagerMovepage().
36822     **
36823     ** The solution is to add an in-memory page to the cache containing
36824     ** the data just read from the sub-journal. Mark the page as dirty 
36825     ** and if the pager requires a journal-sync, then mark the page as 
36826     ** requiring a journal-sync before it is written.
36827     */
36828     assert( isSavepnt );
36829     assert( pPager->doNotSpill==0 );
36830     pPager->doNotSpill++;
36831     rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1);
36832     assert( pPager->doNotSpill==1 );
36833     pPager->doNotSpill--;
36834     if( rc!=SQLITE_OK ) return rc;
36835     pPg->flags &= ~PGHDR_NEED_READ;
36836     sqlite3PcacheMakeDirty(pPg);
36837   }
36838   if( pPg ){
36839     /* No page should ever be explicitly rolled back that is in use, except
36840     ** for page 1 which is held in use in order to keep the lock on the
36841     ** database active. However such a page may be rolled back as a result
36842     ** of an internal error resulting in an automatic call to
36843     ** sqlite3PagerRollback().
36844     */
36845     void *pData;
36846     pData = pPg->pData;
36847     memcpy(pData, (u8*)aData, pPager->pageSize);
36848     pPager->xReiniter(pPg);
36849     if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
36850       /* If the contents of this page were just restored from the main 
36851       ** journal file, then its content must be as they were when the 
36852       ** transaction was first opened. In this case we can mark the page
36853       ** as clean, since there will be no need to write it out to the
36854       ** database.
36855       **
36856       ** There is one exception to this rule. If the page is being rolled
36857       ** back as part of a savepoint (or statement) rollback from an 
36858       ** unsynced portion of the main journal file, then it is not safe
36859       ** to mark the page as clean. This is because marking the page as
36860       ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
36861       ** already in the journal file (recorded in Pager.pInJournal) and
36862       ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
36863       ** again within this transaction, it will be marked as dirty but
36864       ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
36865       ** be written out into the database file before its journal file
36866       ** segment is synced. If a crash occurs during or following this,
36867       ** database corruption may ensue.
36868       */
36869       assert( !pagerUseWal(pPager) );
36870       sqlite3PcacheMakeClean(pPg);
36871     }
36872     pager_set_pagehash(pPg);
36873
36874     /* If this was page 1, then restore the value of Pager.dbFileVers.
36875     ** Do this before any decoding. */
36876     if( pgno==1 ){
36877       memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
36878     }
36879
36880     /* Decode the page just read from disk */
36881     CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
36882     sqlite3PcacheRelease(pPg);
36883   }
36884   return rc;
36885 }
36886
36887 /*
36888 ** Parameter zMaster is the name of a master journal file. A single journal
36889 ** file that referred to the master journal file has just been rolled back.
36890 ** This routine checks if it is possible to delete the master journal file,
36891 ** and does so if it is.
36892 **
36893 ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not 
36894 ** available for use within this function.
36895 **
36896 ** When a master journal file is created, it is populated with the names 
36897 ** of all of its child journals, one after another, formatted as utf-8 
36898 ** encoded text. The end of each child journal file is marked with a 
36899 ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
36900 ** file for a transaction involving two databases might be:
36901 **
36902 **   "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
36903 **
36904 ** A master journal file may only be deleted once all of its child 
36905 ** journals have been rolled back.
36906 **
36907 ** This function reads the contents of the master-journal file into 
36908 ** memory and loops through each of the child journal names. For
36909 ** each child journal, it checks if:
36910 **
36911 **   * if the child journal exists, and if so
36912 **   * if the child journal contains a reference to master journal 
36913 **     file zMaster
36914 **
36915 ** If a child journal can be found that matches both of the criteria
36916 ** above, this function returns without doing anything. Otherwise, if
36917 ** no such child journal can be found, file zMaster is deleted from
36918 ** the file-system using sqlite3OsDelete().
36919 **
36920 ** If an IO error within this function, an error code is returned. This
36921 ** function allocates memory by calling sqlite3Malloc(). If an allocation
36922 ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors 
36923 ** occur, SQLITE_OK is returned.
36924 **
36925 ** TODO: This function allocates a single block of memory to load
36926 ** the entire contents of the master journal file. This could be
36927 ** a couple of kilobytes or so - potentially larger than the page 
36928 ** size.
36929 */
36930 static int pager_delmaster(Pager *pPager, const char *zMaster){
36931   sqlite3_vfs *pVfs = pPager->pVfs;
36932   int rc;                   /* Return code */
36933   sqlite3_file *pMaster;    /* Malloc'd master-journal file descriptor */
36934   sqlite3_file *pJournal;   /* Malloc'd child-journal file descriptor */
36935   char *zMasterJournal = 0; /* Contents of master journal file */
36936   i64 nMasterJournal;       /* Size of master journal file */
36937   char *zJournal;           /* Pointer to one journal within MJ file */
36938   char *zMasterPtr;         /* Space to hold MJ filename from a journal file */
36939   int nMasterPtr;           /* Amount of space allocated to zMasterPtr[] */
36940
36941   /* Allocate space for both the pJournal and pMaster file descriptors.
36942   ** If successful, open the master journal file for reading.
36943   */
36944   pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
36945   pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
36946   if( !pMaster ){
36947     rc = SQLITE_NOMEM;
36948   }else{
36949     const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
36950     rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
36951   }
36952   if( rc!=SQLITE_OK ) goto delmaster_out;
36953
36954   /* Load the entire master journal file into space obtained from
36955   ** sqlite3_malloc() and pointed to by zMasterJournal.   Also obtain
36956   ** sufficient space (in zMasterPtr) to hold the names of master
36957   ** journal files extracted from regular rollback-journals.
36958   */
36959   rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
36960   if( rc!=SQLITE_OK ) goto delmaster_out;
36961   nMasterPtr = pVfs->mxPathname+1;
36962   zMasterJournal = sqlite3Malloc((int)nMasterJournal + nMasterPtr + 1);
36963   if( !zMasterJournal ){
36964     rc = SQLITE_NOMEM;
36965     goto delmaster_out;
36966   }
36967   zMasterPtr = &zMasterJournal[nMasterJournal+1];
36968   rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
36969   if( rc!=SQLITE_OK ) goto delmaster_out;
36970   zMasterJournal[nMasterJournal] = 0;
36971
36972   zJournal = zMasterJournal;
36973   while( (zJournal-zMasterJournal)<nMasterJournal ){
36974     int exists;
36975     rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
36976     if( rc!=SQLITE_OK ){
36977       goto delmaster_out;
36978     }
36979     if( exists ){
36980       /* One of the journals pointed to by the master journal exists.
36981       ** Open it and check if it points at the master journal. If
36982       ** so, return without deleting the master journal file.
36983       */
36984       int c;
36985       int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
36986       rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
36987       if( rc!=SQLITE_OK ){
36988         goto delmaster_out;
36989       }
36990
36991       rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
36992       sqlite3OsClose(pJournal);
36993       if( rc!=SQLITE_OK ){
36994         goto delmaster_out;
36995       }
36996
36997       c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
36998       if( c ){
36999         /* We have a match. Do not delete the master journal file. */
37000         goto delmaster_out;
37001       }
37002     }
37003     zJournal += (sqlite3Strlen30(zJournal)+1);
37004   }
37005  
37006   sqlite3OsClose(pMaster);
37007   rc = sqlite3OsDelete(pVfs, zMaster, 0);
37008
37009 delmaster_out:
37010   sqlite3_free(zMasterJournal);
37011   if( pMaster ){
37012     sqlite3OsClose(pMaster);
37013     assert( !isOpen(pJournal) );
37014     sqlite3_free(pMaster);
37015   }
37016   return rc;
37017 }
37018
37019
37020 /*
37021 ** This function is used to change the actual size of the database 
37022 ** file in the file-system. This only happens when committing a transaction,
37023 ** or rolling back a transaction (including rolling back a hot-journal).
37024 **
37025 ** If the main database file is not open, or the pager is not in either
37026 ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size 
37027 ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes). 
37028 ** If the file on disk is currently larger than nPage pages, then use the VFS
37029 ** xTruncate() method to truncate it.
37030 **
37031 ** Or, it might might be the case that the file on disk is smaller than 
37032 ** nPage pages. Some operating system implementations can get confused if 
37033 ** you try to truncate a file to some size that is larger than it 
37034 ** currently is, so detect this case and write a single zero byte to 
37035 ** the end of the new file instead.
37036 **
37037 ** If successful, return SQLITE_OK. If an IO error occurs while modifying
37038 ** the database file, return the error code to the caller.
37039 */
37040 static int pager_truncate(Pager *pPager, Pgno nPage){
37041   int rc = SQLITE_OK;
37042   assert( pPager->eState!=PAGER_ERROR );
37043   assert( pPager->eState!=PAGER_READER );
37044   
37045   if( isOpen(pPager->fd) 
37046    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN) 
37047   ){
37048     i64 currentSize, newSize;
37049     assert( pPager->eLock==EXCLUSIVE_LOCK );
37050     /* TODO: Is it safe to use Pager.dbFileSize here? */
37051     rc = sqlite3OsFileSize(pPager->fd, &currentSize);
37052     newSize = pPager->pageSize*(i64)nPage;
37053     if( rc==SQLITE_OK && currentSize!=newSize ){
37054       if( currentSize>newSize ){
37055         rc = sqlite3OsTruncate(pPager->fd, newSize);
37056       }else{
37057         rc = sqlite3OsWrite(pPager->fd, "", 1, newSize-1);
37058       }
37059       if( rc==SQLITE_OK ){
37060         pPager->dbFileSize = nPage;
37061       }
37062     }
37063   }
37064   return rc;
37065 }
37066
37067 /*
37068 ** Set the value of the Pager.sectorSize variable for the given
37069 ** pager based on the value returned by the xSectorSize method
37070 ** of the open database file. The sector size will be used used 
37071 ** to determine the size and alignment of journal header and 
37072 ** master journal pointers within created journal files.
37073 **
37074 ** For temporary files the effective sector size is always 512 bytes.
37075 **
37076 ** Otherwise, for non-temporary files, the effective sector size is
37077 ** the value returned by the xSectorSize() method rounded up to 32 if
37078 ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
37079 ** is greater than MAX_SECTOR_SIZE.
37080 */
37081 static void setSectorSize(Pager *pPager){
37082   assert( isOpen(pPager->fd) || pPager->tempFile );
37083
37084   if( !pPager->tempFile ){
37085     /* Sector size doesn't matter for temporary files. Also, the file
37086     ** may not have been opened yet, in which case the OsSectorSize()
37087     ** call will segfault.
37088     */
37089     pPager->sectorSize = sqlite3OsSectorSize(pPager->fd);
37090   }
37091   if( pPager->sectorSize<32 ){
37092     pPager->sectorSize = 512;
37093   }
37094   if( pPager->sectorSize>MAX_SECTOR_SIZE ){
37095     assert( MAX_SECTOR_SIZE>=512 );
37096     pPager->sectorSize = MAX_SECTOR_SIZE;
37097   }
37098 }
37099
37100 /*
37101 ** Playback the journal and thus restore the database file to
37102 ** the state it was in before we started making changes.  
37103 **
37104 ** The journal file format is as follows: 
37105 **
37106 **  (1)  8 byte prefix.  A copy of aJournalMagic[].
37107 **  (2)  4 byte big-endian integer which is the number of valid page records
37108 **       in the journal.  If this value is 0xffffffff, then compute the
37109 **       number of page records from the journal size.
37110 **  (3)  4 byte big-endian integer which is the initial value for the 
37111 **       sanity checksum.
37112 **  (4)  4 byte integer which is the number of pages to truncate the
37113 **       database to during a rollback.
37114 **  (5)  4 byte big-endian integer which is the sector size.  The header
37115 **       is this many bytes in size.
37116 **  (6)  4 byte big-endian integer which is the page size.
37117 **  (7)  zero padding out to the next sector size.
37118 **  (8)  Zero or more pages instances, each as follows:
37119 **        +  4 byte page number.
37120 **        +  pPager->pageSize bytes of data.
37121 **        +  4 byte checksum
37122 **
37123 ** When we speak of the journal header, we mean the first 7 items above.
37124 ** Each entry in the journal is an instance of the 8th item.
37125 **
37126 ** Call the value from the second bullet "nRec".  nRec is the number of
37127 ** valid page entries in the journal.  In most cases, you can compute the
37128 ** value of nRec from the size of the journal file.  But if a power
37129 ** failure occurred while the journal was being written, it could be the
37130 ** case that the size of the journal file had already been increased but
37131 ** the extra entries had not yet made it safely to disk.  In such a case,
37132 ** the value of nRec computed from the file size would be too large.  For
37133 ** that reason, we always use the nRec value in the header.
37134 **
37135 ** If the nRec value is 0xffffffff it means that nRec should be computed
37136 ** from the file size.  This value is used when the user selects the
37137 ** no-sync option for the journal.  A power failure could lead to corruption
37138 ** in this case.  But for things like temporary table (which will be
37139 ** deleted when the power is restored) we don't care.  
37140 **
37141 ** If the file opened as the journal file is not a well-formed
37142 ** journal file then all pages up to the first corrupted page are rolled
37143 ** back (or no pages if the journal header is corrupted). The journal file
37144 ** is then deleted and SQLITE_OK returned, just as if no corruption had
37145 ** been encountered.
37146 **
37147 ** If an I/O or malloc() error occurs, the journal-file is not deleted
37148 ** and an error code is returned.
37149 **
37150 ** The isHot parameter indicates that we are trying to rollback a journal
37151 ** that might be a hot journal.  Or, it could be that the journal is 
37152 ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
37153 ** If the journal really is hot, reset the pager cache prior rolling
37154 ** back any content.  If the journal is merely persistent, no reset is
37155 ** needed.
37156 */
37157 static int pager_playback(Pager *pPager, int isHot){
37158   sqlite3_vfs *pVfs = pPager->pVfs;
37159   i64 szJ;                 /* Size of the journal file in bytes */
37160   u32 nRec;                /* Number of Records in the journal */
37161   u32 u;                   /* Unsigned loop counter */
37162   Pgno mxPg = 0;           /* Size of the original file in pages */
37163   int rc;                  /* Result code of a subroutine */
37164   int res = 1;             /* Value returned by sqlite3OsAccess() */
37165   char *zMaster = 0;       /* Name of master journal file if any */
37166   int needPagerReset;      /* True to reset page prior to first page rollback */
37167
37168   /* Figure out how many records are in the journal.  Abort early if
37169   ** the journal is empty.
37170   */
37171   assert( isOpen(pPager->jfd) );
37172   rc = sqlite3OsFileSize(pPager->jfd, &szJ);
37173   if( rc!=SQLITE_OK ){
37174     goto end_playback;
37175   }
37176
37177   /* Read the master journal name from the journal, if it is present.
37178   ** If a master journal file name is specified, but the file is not
37179   ** present on disk, then the journal is not hot and does not need to be
37180   ** played back.
37181   **
37182   ** TODO: Technically the following is an error because it assumes that
37183   ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
37184   ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
37185   **  mxPathname is 512, which is the same as the minimum allowable value
37186   ** for pageSize.
37187   */
37188   zMaster = pPager->pTmpSpace;
37189   rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
37190   if( rc==SQLITE_OK && zMaster[0] ){
37191     rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
37192   }
37193   zMaster = 0;
37194   if( rc!=SQLITE_OK || !res ){
37195     goto end_playback;
37196   }
37197   pPager->journalOff = 0;
37198   needPagerReset = isHot;
37199
37200   /* This loop terminates either when a readJournalHdr() or 
37201   ** pager_playback_one_page() call returns SQLITE_DONE or an IO error 
37202   ** occurs. 
37203   */
37204   while( 1 ){
37205     /* Read the next journal header from the journal file.  If there are
37206     ** not enough bytes left in the journal file for a complete header, or
37207     ** it is corrupted, then a process must have failed while writing it.
37208     ** This indicates nothing more needs to be rolled back.
37209     */
37210     rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
37211     if( rc!=SQLITE_OK ){ 
37212       if( rc==SQLITE_DONE ){
37213         rc = SQLITE_OK;
37214       }
37215       goto end_playback;
37216     }
37217
37218     /* If nRec is 0xffffffff, then this journal was created by a process
37219     ** working in no-sync mode. This means that the rest of the journal
37220     ** file consists of pages, there are no more journal headers. Compute
37221     ** the value of nRec based on this assumption.
37222     */
37223     if( nRec==0xffffffff ){
37224       assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
37225       nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
37226     }
37227
37228     /* If nRec is 0 and this rollback is of a transaction created by this
37229     ** process and if this is the final header in the journal, then it means
37230     ** that this part of the journal was being filled but has not yet been
37231     ** synced to disk.  Compute the number of pages based on the remaining
37232     ** size of the file.
37233     **
37234     ** The third term of the test was added to fix ticket #2565.
37235     ** When rolling back a hot journal, nRec==0 always means that the next
37236     ** chunk of the journal contains zero pages to be rolled back.  But
37237     ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
37238     ** the journal, it means that the journal might contain additional
37239     ** pages that need to be rolled back and that the number of pages 
37240     ** should be computed based on the journal file size.
37241     */
37242     if( nRec==0 && !isHot &&
37243         pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
37244       nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
37245     }
37246
37247     /* If this is the first header read from the journal, truncate the
37248     ** database file back to its original size.
37249     */
37250     if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
37251       rc = pager_truncate(pPager, mxPg);
37252       if( rc!=SQLITE_OK ){
37253         goto end_playback;
37254       }
37255       pPager->dbSize = mxPg;
37256     }
37257
37258     /* Copy original pages out of the journal and back into the 
37259     ** database file and/or page cache.
37260     */
37261     for(u=0; u<nRec; u++){
37262       if( needPagerReset ){
37263         pager_reset(pPager);
37264         needPagerReset = 0;
37265       }
37266       rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
37267       if( rc!=SQLITE_OK ){
37268         if( rc==SQLITE_DONE ){
37269           rc = SQLITE_OK;
37270           pPager->journalOff = szJ;
37271           break;
37272         }else if( rc==SQLITE_IOERR_SHORT_READ ){
37273           /* If the journal has been truncated, simply stop reading and
37274           ** processing the journal. This might happen if the journal was
37275           ** not completely written and synced prior to a crash.  In that
37276           ** case, the database should have never been written in the
37277           ** first place so it is OK to simply abandon the rollback. */
37278           rc = SQLITE_OK;
37279           goto end_playback;
37280         }else{
37281           /* If we are unable to rollback, quit and return the error
37282           ** code.  This will cause the pager to enter the error state
37283           ** so that no further harm will be done.  Perhaps the next
37284           ** process to come along will be able to rollback the database.
37285           */
37286           goto end_playback;
37287         }
37288       }
37289     }
37290   }
37291   /*NOTREACHED*/
37292   assert( 0 );
37293
37294 end_playback:
37295   /* Following a rollback, the database file should be back in its original
37296   ** state prior to the start of the transaction, so invoke the
37297   ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
37298   ** assertion that the transaction counter was modified.
37299   */
37300   assert(
37301     pPager->fd->pMethods==0 ||
37302     sqlite3OsFileControl(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0)>=SQLITE_OK
37303   );
37304
37305   /* If this playback is happening automatically as a result of an IO or 
37306   ** malloc error that occurred after the change-counter was updated but 
37307   ** before the transaction was committed, then the change-counter 
37308   ** modification may just have been reverted. If this happens in exclusive 
37309   ** mode, then subsequent transactions performed by the connection will not
37310   ** update the change-counter at all. This may lead to cache inconsistency
37311   ** problems for other processes at some point in the future. So, just
37312   ** in case this has happened, clear the changeCountDone flag now.
37313   */
37314   pPager->changeCountDone = pPager->tempFile;
37315
37316   if( rc==SQLITE_OK ){
37317     zMaster = pPager->pTmpSpace;
37318     rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
37319     testcase( rc!=SQLITE_OK );
37320   }
37321   if( rc==SQLITE_OK && !pPager->noSync 
37322    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
37323   ){
37324     rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
37325   }
37326   if( rc==SQLITE_OK ){
37327     rc = pager_end_transaction(pPager, zMaster[0]!='\0');
37328     testcase( rc!=SQLITE_OK );
37329   }
37330   if( rc==SQLITE_OK && zMaster[0] && res ){
37331     /* If there was a master journal and this routine will return success,
37332     ** see if it is possible to delete the master journal.
37333     */
37334     rc = pager_delmaster(pPager, zMaster);
37335     testcase( rc!=SQLITE_OK );
37336   }
37337
37338   /* The Pager.sectorSize variable may have been updated while rolling
37339   ** back a journal created by a process with a different sector size
37340   ** value. Reset it to the correct value for this process.
37341   */
37342   setSectorSize(pPager);
37343   return rc;
37344 }
37345
37346
37347 /*
37348 ** Read the content for page pPg out of the database file and into 
37349 ** pPg->pData. A shared lock or greater must be held on the database
37350 ** file before this function is called.
37351 **
37352 ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
37353 ** the value read from the database file.
37354 **
37355 ** If an IO error occurs, then the IO error is returned to the caller.
37356 ** Otherwise, SQLITE_OK is returned.
37357 */
37358 static int readDbPage(PgHdr *pPg){
37359   Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
37360   Pgno pgno = pPg->pgno;       /* Page number to read */
37361   int rc = SQLITE_OK;          /* Return code */
37362   int isInWal = 0;             /* True if page is in log file */
37363   int pgsz = pPager->pageSize; /* Number of bytes to read */
37364
37365   assert( pPager->eState>=PAGER_READER && !MEMDB );
37366   assert( isOpen(pPager->fd) );
37367
37368   if( NEVER(!isOpen(pPager->fd)) ){
37369     assert( pPager->tempFile );
37370     memset(pPg->pData, 0, pPager->pageSize);
37371     return SQLITE_OK;
37372   }
37373
37374   if( pagerUseWal(pPager) ){
37375     /* Try to pull the page from the write-ahead log. */
37376     rc = sqlite3WalRead(pPager->pWal, pgno, &isInWal, pgsz, pPg->pData);
37377   }
37378   if( rc==SQLITE_OK && !isInWal ){
37379     i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
37380     rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
37381     if( rc==SQLITE_IOERR_SHORT_READ ){
37382       rc = SQLITE_OK;
37383     }
37384   }
37385
37386   if( pgno==1 ){
37387     if( rc ){
37388       /* If the read is unsuccessful, set the dbFileVers[] to something
37389       ** that will never be a valid file version.  dbFileVers[] is a copy
37390       ** of bytes 24..39 of the database.  Bytes 28..31 should always be
37391       ** zero or the size of the database in page. Bytes 32..35 and 35..39
37392       ** should be page numbers which are never 0xffffffff.  So filling
37393       ** pPager->dbFileVers[] with all 0xff bytes should suffice.
37394       **
37395       ** For an encrypted database, the situation is more complex:  bytes
37396       ** 24..39 of the database are white noise.  But the probability of
37397       ** white noising equaling 16 bytes of 0xff is vanishingly small so
37398       ** we should still be ok.
37399       */
37400       memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
37401     }else{
37402       u8 *dbFileVers = &((u8*)pPg->pData)[24];
37403       memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
37404     }
37405   }
37406   CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
37407
37408   PAGER_INCR(sqlite3_pager_readdb_count);
37409   PAGER_INCR(pPager->nRead);
37410   IOTRACE(("PGIN %p %d\n", pPager, pgno));
37411   PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
37412                PAGERID(pPager), pgno, pager_pagehash(pPg)));
37413
37414   return rc;
37415 }
37416
37417 #ifndef SQLITE_OMIT_WAL
37418 /*
37419 ** This function is invoked once for each page that has already been 
37420 ** written into the log file when a WAL transaction is rolled back.
37421 ** Parameter iPg is the page number of said page. The pCtx argument 
37422 ** is actually a pointer to the Pager structure.
37423 **
37424 ** If page iPg is present in the cache, and has no outstanding references,
37425 ** it is discarded. Otherwise, if there are one or more outstanding
37426 ** references, the page content is reloaded from the database. If the
37427 ** attempt to reload content from the database is required and fails, 
37428 ** return an SQLite error code. Otherwise, SQLITE_OK.
37429 */
37430 static int pagerUndoCallback(void *pCtx, Pgno iPg){
37431   int rc = SQLITE_OK;
37432   Pager *pPager = (Pager *)pCtx;
37433   PgHdr *pPg;
37434
37435   pPg = sqlite3PagerLookup(pPager, iPg);
37436   if( pPg ){
37437     if( sqlite3PcachePageRefcount(pPg)==1 ){
37438       sqlite3PcacheDrop(pPg);
37439     }else{
37440       rc = readDbPage(pPg);
37441       if( rc==SQLITE_OK ){
37442         pPager->xReiniter(pPg);
37443       }
37444       sqlite3PagerUnref(pPg);
37445     }
37446   }
37447
37448   /* Normally, if a transaction is rolled back, any backup processes are
37449   ** updated as data is copied out of the rollback journal and into the
37450   ** database. This is not generally possible with a WAL database, as
37451   ** rollback involves simply truncating the log file. Therefore, if one
37452   ** or more frames have already been written to the log (and therefore 
37453   ** also copied into the backup databases) as part of this transaction,
37454   ** the backups must be restarted.
37455   */
37456   sqlite3BackupRestart(pPager->pBackup);
37457
37458   return rc;
37459 }
37460
37461 /*
37462 ** This function is called to rollback a transaction on a WAL database.
37463 */
37464 static int pagerRollbackWal(Pager *pPager){
37465   int rc;                         /* Return Code */
37466   PgHdr *pList;                   /* List of dirty pages to revert */
37467
37468   /* For all pages in the cache that are currently dirty or have already
37469   ** been written (but not committed) to the log file, do one of the 
37470   ** following:
37471   **
37472   **   + Discard the cached page (if refcount==0), or
37473   **   + Reload page content from the database (if refcount>0).
37474   */
37475   pPager->dbSize = pPager->dbOrigSize;
37476   rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
37477   pList = sqlite3PcacheDirtyList(pPager->pPCache);
37478   while( pList && rc==SQLITE_OK ){
37479     PgHdr *pNext = pList->pDirty;
37480     rc = pagerUndoCallback((void *)pPager, pList->pgno);
37481     pList = pNext;
37482   }
37483
37484   return rc;
37485 }
37486
37487 /*
37488 ** This function is a wrapper around sqlite3WalFrames(). As well as logging
37489 ** the contents of the list of pages headed by pList (connected by pDirty),
37490 ** this function notifies any active backup processes that the pages have
37491 ** changed. 
37492 */ 
37493 static int pagerWalFrames(
37494   Pager *pPager,                  /* Pager object */
37495   PgHdr *pList,                   /* List of frames to log */
37496   Pgno nTruncate,                 /* Database size after this commit */
37497   int isCommit,                   /* True if this is a commit */
37498   int sync_flags                  /* Flags to pass to OsSync() (or 0) */
37499 ){
37500   int rc;                         /* Return code */
37501
37502   assert( pPager->pWal );
37503   rc = sqlite3WalFrames(pPager->pWal, 
37504       pPager->pageSize, pList, nTruncate, isCommit, sync_flags
37505   );
37506   if( rc==SQLITE_OK && pPager->pBackup ){
37507     PgHdr *p;
37508     for(p=pList; p; p=p->pDirty){
37509       sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
37510     }
37511   }
37512
37513 #ifdef SQLITE_CHECK_PAGES
37514   {
37515     PgHdr *p;
37516     for(p=pList; p; p=p->pDirty) pager_set_pagehash(p);
37517   }
37518 #endif
37519
37520   return rc;
37521 }
37522
37523 /*
37524 ** Begin a read transaction on the WAL.
37525 **
37526 ** This routine used to be called "pagerOpenSnapshot()" because it essentially
37527 ** makes a snapshot of the database at the current point in time and preserves
37528 ** that snapshot for use by the reader in spite of concurrently changes by
37529 ** other writers or checkpointers.
37530 */
37531 static int pagerBeginReadTransaction(Pager *pPager){
37532   int rc;                         /* Return code */
37533   int changed = 0;                /* True if cache must be reset */
37534
37535   assert( pagerUseWal(pPager) );
37536   assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
37537
37538   /* sqlite3WalEndReadTransaction() was not called for the previous
37539   ** transaction in locking_mode=EXCLUSIVE.  So call it now.  If we
37540   ** are in locking_mode=NORMAL and EndRead() was previously called,
37541   ** the duplicate call is harmless.
37542   */
37543   sqlite3WalEndReadTransaction(pPager->pWal);
37544
37545   rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
37546   if( rc!=SQLITE_OK || changed ){
37547     pager_reset(pPager);
37548   }
37549
37550   return rc;
37551 }
37552 #endif
37553
37554 /*
37555 ** This function is called as part of the transition from PAGER_OPEN
37556 ** to PAGER_READER state to determine the size of the database file
37557 ** in pages (assuming the page size currently stored in Pager.pageSize).
37558 **
37559 ** If no error occurs, SQLITE_OK is returned and the size of the database
37560 ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
37561 ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
37562 */
37563 static int pagerPagecount(Pager *pPager, Pgno *pnPage){
37564   Pgno nPage;                     /* Value to return via *pnPage */
37565
37566   /* Query the WAL sub-system for the database size. The WalDbsize()
37567   ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
37568   ** if the database size is not available. The database size is not
37569   ** available from the WAL sub-system if the log file is empty or
37570   ** contains no valid committed transactions.
37571   */
37572   assert( pPager->eState==PAGER_OPEN );
37573   assert( pPager->eLock>=SHARED_LOCK || pPager->noReadlock );
37574   nPage = sqlite3WalDbsize(pPager->pWal);
37575
37576   /* If the database size was not available from the WAL sub-system,
37577   ** determine it based on the size of the database file. If the size
37578   ** of the database file is not an integer multiple of the page-size,
37579   ** round down to the nearest page. Except, any file larger than 0
37580   ** bytes in size is considered to contain at least one page.
37581   */
37582   if( nPage==0 ){
37583     i64 n = 0;                    /* Size of db file in bytes */
37584     assert( isOpen(pPager->fd) || pPager->tempFile );
37585     if( isOpen(pPager->fd) ){
37586       int rc = sqlite3OsFileSize(pPager->fd, &n);
37587       if( rc!=SQLITE_OK ){
37588         return rc;
37589       }
37590     }
37591     nPage = (Pgno)(n / pPager->pageSize);
37592     if( nPage==0 && n>0 ){
37593       nPage = 1;
37594     }
37595   }
37596
37597   /* If the current number of pages in the file is greater than the
37598   ** configured maximum pager number, increase the allowed limit so
37599   ** that the file can be read.
37600   */
37601   if( nPage>pPager->mxPgno ){
37602     pPager->mxPgno = (Pgno)nPage;
37603   }
37604
37605   *pnPage = nPage;
37606   return SQLITE_OK;
37607 }
37608
37609 #ifndef SQLITE_OMIT_WAL
37610 /*
37611 ** Check if the *-wal file that corresponds to the database opened by pPager
37612 ** exists if the database is not empy, or verify that the *-wal file does
37613 ** not exist (by deleting it) if the database file is empty.
37614 **
37615 ** If the database is not empty and the *-wal file exists, open the pager
37616 ** in WAL mode.  If the database is empty or if no *-wal file exists and
37617 ** if no error occurs, make sure Pager.journalMode is not set to
37618 ** PAGER_JOURNALMODE_WAL.
37619 **
37620 ** Return SQLITE_OK or an error code.
37621 **
37622 ** The caller must hold a SHARED lock on the database file to call this
37623 ** function. Because an EXCLUSIVE lock on the db file is required to delete 
37624 ** a WAL on a none-empty database, this ensures there is no race condition 
37625 ** between the xAccess() below and an xDelete() being executed by some 
37626 ** other connection.
37627 */
37628 static int pagerOpenWalIfPresent(Pager *pPager){
37629   int rc = SQLITE_OK;
37630   assert( pPager->eState==PAGER_OPEN );
37631   assert( pPager->eLock>=SHARED_LOCK || pPager->noReadlock );
37632
37633   if( !pPager->tempFile ){
37634     int isWal;                    /* True if WAL file exists */
37635     Pgno nPage;                   /* Size of the database file */
37636
37637     rc = pagerPagecount(pPager, &nPage);
37638     if( rc ) return rc;
37639     if( nPage==0 ){
37640       rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
37641       isWal = 0;
37642     }else{
37643       rc = sqlite3OsAccess(
37644           pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
37645       );
37646     }
37647     if( rc==SQLITE_OK ){
37648       if( isWal ){
37649         testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
37650         rc = sqlite3PagerOpenWal(pPager, 0);
37651       }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
37652         pPager->journalMode = PAGER_JOURNALMODE_DELETE;
37653       }
37654     }
37655   }
37656   return rc;
37657 }
37658 #endif
37659
37660 /*
37661 ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
37662 ** the entire master journal file. The case pSavepoint==NULL occurs when 
37663 ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction 
37664 ** savepoint.
37665 **
37666 ** When pSavepoint is not NULL (meaning a non-transaction savepoint is 
37667 ** being rolled back), then the rollback consists of up to three stages,
37668 ** performed in the order specified:
37669 **
37670 **   * Pages are played back from the main journal starting at byte
37671 **     offset PagerSavepoint.iOffset and continuing to 
37672 **     PagerSavepoint.iHdrOffset, or to the end of the main journal
37673 **     file if PagerSavepoint.iHdrOffset is zero.
37674 **
37675 **   * If PagerSavepoint.iHdrOffset is not zero, then pages are played
37676 **     back starting from the journal header immediately following 
37677 **     PagerSavepoint.iHdrOffset to the end of the main journal file.
37678 **
37679 **   * Pages are then played back from the sub-journal file, starting
37680 **     with the PagerSavepoint.iSubRec and continuing to the end of
37681 **     the journal file.
37682 **
37683 ** Throughout the rollback process, each time a page is rolled back, the
37684 ** corresponding bit is set in a bitvec structure (variable pDone in the
37685 ** implementation below). This is used to ensure that a page is only
37686 ** rolled back the first time it is encountered in either journal.
37687 **
37688 ** If pSavepoint is NULL, then pages are only played back from the main
37689 ** journal file. There is no need for a bitvec in this case.
37690 **
37691 ** In either case, before playback commences the Pager.dbSize variable
37692 ** is reset to the value that it held at the start of the savepoint 
37693 ** (or transaction). No page with a page-number greater than this value
37694 ** is played back. If one is encountered it is simply skipped.
37695 */
37696 static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
37697   i64 szJ;                 /* Effective size of the main journal */
37698   i64 iHdrOff;             /* End of first segment of main-journal records */
37699   int rc = SQLITE_OK;      /* Return code */
37700   Bitvec *pDone = 0;       /* Bitvec to ensure pages played back only once */
37701
37702   assert( pPager->eState!=PAGER_ERROR );
37703   assert( pPager->eState>=PAGER_WRITER_LOCKED );
37704
37705   /* Allocate a bitvec to use to store the set of pages rolled back */
37706   if( pSavepoint ){
37707     pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
37708     if( !pDone ){
37709       return SQLITE_NOMEM;
37710     }
37711   }
37712
37713   /* Set the database size back to the value it was before the savepoint 
37714   ** being reverted was opened.
37715   */
37716   pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
37717   pPager->changeCountDone = pPager->tempFile;
37718
37719   if( !pSavepoint && pagerUseWal(pPager) ){
37720     return pagerRollbackWal(pPager);
37721   }
37722
37723   /* Use pPager->journalOff as the effective size of the main rollback
37724   ** journal.  The actual file might be larger than this in
37725   ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST.  But anything
37726   ** past pPager->journalOff is off-limits to us.
37727   */
37728   szJ = pPager->journalOff;
37729   assert( pagerUseWal(pPager)==0 || szJ==0 );
37730
37731   /* Begin by rolling back records from the main journal starting at
37732   ** PagerSavepoint.iOffset and continuing to the next journal header.
37733   ** There might be records in the main journal that have a page number
37734   ** greater than the current database size (pPager->dbSize) but those
37735   ** will be skipped automatically.  Pages are added to pDone as they
37736   ** are played back.
37737   */
37738   if( pSavepoint && !pagerUseWal(pPager) ){
37739     iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
37740     pPager->journalOff = pSavepoint->iOffset;
37741     while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
37742       rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
37743     }
37744     assert( rc!=SQLITE_DONE );
37745   }else{
37746     pPager->journalOff = 0;
37747   }
37748
37749   /* Continue rolling back records out of the main journal starting at
37750   ** the first journal header seen and continuing until the effective end
37751   ** of the main journal file.  Continue to skip out-of-range pages and
37752   ** continue adding pages rolled back to pDone.
37753   */
37754   while( rc==SQLITE_OK && pPager->journalOff<szJ ){
37755     u32 ii;            /* Loop counter */
37756     u32 nJRec = 0;     /* Number of Journal Records */
37757     u32 dummy;
37758     rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
37759     assert( rc!=SQLITE_DONE );
37760
37761     /*
37762     ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
37763     ** test is related to ticket #2565.  See the discussion in the
37764     ** pager_playback() function for additional information.
37765     */
37766     if( nJRec==0 
37767      && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
37768     ){
37769       nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
37770     }
37771     for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
37772       rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
37773     }
37774     assert( rc!=SQLITE_DONE );
37775   }
37776   assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
37777
37778   /* Finally,  rollback pages from the sub-journal.  Page that were
37779   ** previously rolled back out of the main journal (and are hence in pDone)
37780   ** will be skipped.  Out-of-range pages are also skipped.
37781   */
37782   if( pSavepoint ){
37783     u32 ii;            /* Loop counter */
37784     i64 offset = pSavepoint->iSubRec*(4+pPager->pageSize);
37785
37786     if( pagerUseWal(pPager) ){
37787       rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
37788     }
37789     for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
37790       assert( offset==ii*(4+pPager->pageSize) );
37791       rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
37792     }
37793     assert( rc!=SQLITE_DONE );
37794   }
37795
37796   sqlite3BitvecDestroy(pDone);
37797   if( rc==SQLITE_OK ){
37798     pPager->journalOff = szJ;
37799   }
37800
37801   return rc;
37802 }
37803
37804 /*
37805 ** Change the maximum number of in-memory pages that are allowed.
37806 */
37807 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
37808   sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
37809 }
37810
37811 /*
37812 ** Adjust the robustness of the database to damage due to OS crashes
37813 ** or power failures by changing the number of syncs()s when writing
37814 ** the rollback journal.  There are three levels:
37815 **
37816 **    OFF       sqlite3OsSync() is never called.  This is the default
37817 **              for temporary and transient files.
37818 **
37819 **    NORMAL    The journal is synced once before writes begin on the
37820 **              database.  This is normally adequate protection, but
37821 **              it is theoretically possible, though very unlikely,
37822 **              that an inopertune power failure could leave the journal
37823 **              in a state which would cause damage to the database
37824 **              when it is rolled back.
37825 **
37826 **    FULL      The journal is synced twice before writes begin on the
37827 **              database (with some additional information - the nRec field
37828 **              of the journal header - being written in between the two
37829 **              syncs).  If we assume that writing a
37830 **              single disk sector is atomic, then this mode provides
37831 **              assurance that the journal will not be corrupted to the
37832 **              point of causing damage to the database during rollback.
37833 **
37834 ** Numeric values associated with these states are OFF==1, NORMAL=2,
37835 ** and FULL=3.
37836 */
37837 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
37838 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager *pPager, int level, int bFullFsync){
37839   pPager->noSync =  (level==1 || pPager->tempFile) ?1:0;
37840   pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
37841   pPager->sync_flags = (bFullFsync?SQLITE_SYNC_FULL:SQLITE_SYNC_NORMAL);
37842 }
37843 #endif
37844
37845 /*
37846 ** The following global variable is incremented whenever the library
37847 ** attempts to open a temporary file.  This information is used for
37848 ** testing and analysis only.  
37849 */
37850 #ifdef SQLITE_TEST
37851 SQLITE_API int sqlite3_opentemp_count = 0;
37852 #endif
37853
37854 /*
37855 ** Open a temporary file.
37856 **
37857 ** Write the file descriptor into *pFile. Return SQLITE_OK on success 
37858 ** or some other error code if we fail. The OS will automatically 
37859 ** delete the temporary file when it is closed.
37860 **
37861 ** The flags passed to the VFS layer xOpen() call are those specified
37862 ** by parameter vfsFlags ORed with the following:
37863 **
37864 **     SQLITE_OPEN_READWRITE
37865 **     SQLITE_OPEN_CREATE
37866 **     SQLITE_OPEN_EXCLUSIVE
37867 **     SQLITE_OPEN_DELETEONCLOSE
37868 */
37869 static int pagerOpentemp(
37870   Pager *pPager,        /* The pager object */
37871   sqlite3_file *pFile,  /* Write the file descriptor here */
37872   int vfsFlags          /* Flags passed through to the VFS */
37873 ){
37874   int rc;               /* Return code */
37875
37876 #ifdef SQLITE_TEST
37877   sqlite3_opentemp_count++;  /* Used for testing and analysis only */
37878 #endif
37879
37880   vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
37881             SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
37882   rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
37883   assert( rc!=SQLITE_OK || isOpen(pFile) );
37884   return rc;
37885 }
37886
37887 /*
37888 ** Set the busy handler function.
37889 **
37890 ** The pager invokes the busy-handler if sqlite3OsLock() returns 
37891 ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
37892 ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE 
37893 ** lock. It does *not* invoke the busy handler when upgrading from
37894 ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
37895 ** (which occurs during hot-journal rollback). Summary:
37896 **
37897 **   Transition                        | Invokes xBusyHandler
37898 **   --------------------------------------------------------
37899 **   NO_LOCK       -> SHARED_LOCK      | Yes
37900 **   SHARED_LOCK   -> RESERVED_LOCK    | No
37901 **   SHARED_LOCK   -> EXCLUSIVE_LOCK   | No
37902 **   RESERVED_LOCK -> EXCLUSIVE_LOCK   | Yes
37903 **
37904 ** If the busy-handler callback returns non-zero, the lock is 
37905 ** retried. If it returns zero, then the SQLITE_BUSY error is
37906 ** returned to the caller of the pager API function.
37907 */
37908 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
37909   Pager *pPager,                       /* Pager object */
37910   int (*xBusyHandler)(void *),         /* Pointer to busy-handler function */
37911   void *pBusyHandlerArg                /* Argument to pass to xBusyHandler */
37912 ){  
37913   pPager->xBusyHandler = xBusyHandler;
37914   pPager->pBusyHandlerArg = pBusyHandlerArg;
37915 }
37916
37917 /*
37918 ** Change the page size used by the Pager object. The new page size 
37919 ** is passed in *pPageSize.
37920 **
37921 ** If the pager is in the error state when this function is called, it
37922 ** is a no-op. The value returned is the error state error code (i.e. 
37923 ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
37924 **
37925 ** Otherwise, if all of the following are true:
37926 **
37927 **   * the new page size (value of *pPageSize) is valid (a power 
37928 **     of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
37929 **
37930 **   * there are no outstanding page references, and
37931 **
37932 **   * the database is either not an in-memory database or it is
37933 **     an in-memory database that currently consists of zero pages.
37934 **
37935 ** then the pager object page size is set to *pPageSize.
37936 **
37937 ** If the page size is changed, then this function uses sqlite3PagerMalloc() 
37938 ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt 
37939 ** fails, SQLITE_NOMEM is returned and the page size remains unchanged. 
37940 ** In all other cases, SQLITE_OK is returned.
37941 **
37942 ** If the page size is not changed, either because one of the enumerated
37943 ** conditions above is not true, the pager was in error state when this
37944 ** function was called, or because the memory allocation attempt failed, 
37945 ** then *pPageSize is set to the old, retained page size before returning.
37946 */
37947 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
37948   int rc = SQLITE_OK;
37949
37950   /* It is not possible to do a full assert_pager_state() here, as this
37951   ** function may be called from within PagerOpen(), before the state
37952   ** of the Pager object is internally consistent.
37953   **
37954   ** At one point this function returned an error if the pager was in 
37955   ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
37956   ** there is at least one outstanding page reference, this function
37957   ** is a no-op for that case anyhow.
37958   */
37959
37960   u32 pageSize = *pPageSize;
37961   assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
37962   if( (pPager->memDb==0 || pPager->dbSize==0)
37963    && sqlite3PcacheRefCount(pPager->pPCache)==0 
37964    && pageSize && pageSize!=(u32)pPager->pageSize 
37965   ){
37966     char *pNew = NULL;             /* New temp space */
37967     i64 nByte = 0;
37968
37969     if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
37970       rc = sqlite3OsFileSize(pPager->fd, &nByte);
37971     }
37972     if( rc==SQLITE_OK ){
37973       pNew = (char *)sqlite3PageMalloc(pageSize);
37974       if( !pNew ) rc = SQLITE_NOMEM;
37975     }
37976
37977     if( rc==SQLITE_OK ){
37978       pager_reset(pPager);
37979       pPager->dbSize = (Pgno)(nByte/pageSize);
37980       pPager->pageSize = pageSize;
37981       sqlite3PageFree(pPager->pTmpSpace);
37982       pPager->pTmpSpace = pNew;
37983       sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
37984     }
37985   }
37986
37987   *pPageSize = pPager->pageSize;
37988   if( rc==SQLITE_OK ){
37989     if( nReserve<0 ) nReserve = pPager->nReserve;
37990     assert( nReserve>=0 && nReserve<1000 );
37991     pPager->nReserve = (i16)nReserve;
37992     pagerReportSize(pPager);
37993   }
37994   return rc;
37995 }
37996
37997 /*
37998 ** Return a pointer to the "temporary page" buffer held internally
37999 ** by the pager.  This is a buffer that is big enough to hold the
38000 ** entire content of a database page.  This buffer is used internally
38001 ** during rollback and will be overwritten whenever a rollback
38002 ** occurs.  But other modules are free to use it too, as long as
38003 ** no rollbacks are happening.
38004 */
38005 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
38006   return pPager->pTmpSpace;
38007 }
38008
38009 /*
38010 ** Attempt to set the maximum database page count if mxPage is positive. 
38011 ** Make no changes if mxPage is zero or negative.  And never reduce the
38012 ** maximum page count below the current size of the database.
38013 **
38014 ** Regardless of mxPage, return the current maximum page count.
38015 */
38016 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
38017   if( mxPage>0 ){
38018     pPager->mxPgno = mxPage;
38019   }
38020   if( pPager->eState!=PAGER_OPEN && pPager->mxPgno<pPager->dbSize ){
38021     pPager->mxPgno = pPager->dbSize;
38022   }
38023   return pPager->mxPgno;
38024 }
38025
38026 /*
38027 ** The following set of routines are used to disable the simulated
38028 ** I/O error mechanism.  These routines are used to avoid simulated
38029 ** errors in places where we do not care about errors.
38030 **
38031 ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
38032 ** and generate no code.
38033 */
38034 #ifdef SQLITE_TEST
38035 SQLITE_API extern int sqlite3_io_error_pending;
38036 SQLITE_API extern int sqlite3_io_error_hit;
38037 static int saved_cnt;
38038 void disable_simulated_io_errors(void){
38039   saved_cnt = sqlite3_io_error_pending;
38040   sqlite3_io_error_pending = -1;
38041 }
38042 void enable_simulated_io_errors(void){
38043   sqlite3_io_error_pending = saved_cnt;
38044 }
38045 #else
38046 # define disable_simulated_io_errors()
38047 # define enable_simulated_io_errors()
38048 #endif
38049
38050 /*
38051 ** Read the first N bytes from the beginning of the file into memory
38052 ** that pDest points to. 
38053 **
38054 ** If the pager was opened on a transient file (zFilename==""), or
38055 ** opened on a file less than N bytes in size, the output buffer is
38056 ** zeroed and SQLITE_OK returned. The rationale for this is that this 
38057 ** function is used to read database headers, and a new transient or
38058 ** zero sized database has a header than consists entirely of zeroes.
38059 **
38060 ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
38061 ** the error code is returned to the caller and the contents of the
38062 ** output buffer undefined.
38063 */
38064 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
38065   int rc = SQLITE_OK;
38066   memset(pDest, 0, N);
38067   assert( isOpen(pPager->fd) || pPager->tempFile );
38068
38069   /* This routine is only called by btree immediately after creating
38070   ** the Pager object.  There has not been an opportunity to transition
38071   ** to WAL mode yet.
38072   */
38073   assert( !pagerUseWal(pPager) );
38074
38075   if( isOpen(pPager->fd) ){
38076     IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
38077     rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
38078     if( rc==SQLITE_IOERR_SHORT_READ ){
38079       rc = SQLITE_OK;
38080     }
38081   }
38082   return rc;
38083 }
38084
38085 /*
38086 ** This function may only be called when a read-transaction is open on
38087 ** the pager. It returns the total number of pages in the database.
38088 **
38089 ** However, if the file is between 1 and <page-size> bytes in size, then 
38090 ** this is considered a 1 page file.
38091 */
38092 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
38093   assert( pPager->eState>=PAGER_READER );
38094   assert( pPager->eState!=PAGER_WRITER_FINISHED );
38095   *pnPage = (int)pPager->dbSize;
38096 }
38097
38098
38099 /*
38100 ** Try to obtain a lock of type locktype on the database file. If
38101 ** a similar or greater lock is already held, this function is a no-op
38102 ** (returning SQLITE_OK immediately).
38103 **
38104 ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke 
38105 ** the busy callback if the lock is currently not available. Repeat 
38106 ** until the busy callback returns false or until the attempt to 
38107 ** obtain the lock succeeds.
38108 **
38109 ** Return SQLITE_OK on success and an error code if we cannot obtain
38110 ** the lock. If the lock is obtained successfully, set the Pager.state 
38111 ** variable to locktype before returning.
38112 */
38113 static int pager_wait_on_lock(Pager *pPager, int locktype){
38114   int rc;                              /* Return code */
38115
38116   /* Check that this is either a no-op (because the requested lock is 
38117   ** already held, or one of the transistions that the busy-handler
38118   ** may be invoked during, according to the comment above
38119   ** sqlite3PagerSetBusyhandler().
38120   */
38121   assert( (pPager->eLock>=locktype)
38122        || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
38123        || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
38124   );
38125
38126   do {
38127     rc = pagerLockDb(pPager, locktype);
38128   }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
38129   return rc;
38130 }
38131
38132 /*
38133 ** Function assertTruncateConstraint(pPager) checks that one of the 
38134 ** following is true for all dirty pages currently in the page-cache:
38135 **
38136 **   a) The page number is less than or equal to the size of the 
38137 **      current database image, in pages, OR
38138 **
38139 **   b) if the page content were written at this time, it would not
38140 **      be necessary to write the current content out to the sub-journal
38141 **      (as determined by function subjRequiresPage()).
38142 **
38143 ** If the condition asserted by this function were not true, and the
38144 ** dirty page were to be discarded from the cache via the pagerStress()
38145 ** routine, pagerStress() would not write the current page content to
38146 ** the database file. If a savepoint transaction were rolled back after
38147 ** this happened, the correct behaviour would be to restore the current
38148 ** content of the page. However, since this content is not present in either
38149 ** the database file or the portion of the rollback journal and 
38150 ** sub-journal rolled back the content could not be restored and the
38151 ** database image would become corrupt. It is therefore fortunate that 
38152 ** this circumstance cannot arise.
38153 */
38154 #if defined(SQLITE_DEBUG)
38155 static void assertTruncateConstraintCb(PgHdr *pPg){
38156   assert( pPg->flags&PGHDR_DIRTY );
38157   assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
38158 }
38159 static void assertTruncateConstraint(Pager *pPager){
38160   sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
38161 }
38162 #else
38163 # define assertTruncateConstraint(pPager)
38164 #endif
38165
38166 /*
38167 ** Truncate the in-memory database file image to nPage pages. This 
38168 ** function does not actually modify the database file on disk. It 
38169 ** just sets the internal state of the pager object so that the 
38170 ** truncation will be done when the current transaction is committed.
38171 */
38172 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
38173   assert( pPager->dbSize>=nPage );
38174   assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
38175   pPager->dbSize = nPage;
38176   assertTruncateConstraint(pPager);
38177 }
38178
38179
38180 /*
38181 ** This function is called before attempting a hot-journal rollback. It
38182 ** syncs the journal file to disk, then sets pPager->journalHdr to the
38183 ** size of the journal file so that the pager_playback() routine knows
38184 ** that the entire journal file has been synced.
38185 **
38186 ** Syncing a hot-journal to disk before attempting to roll it back ensures 
38187 ** that if a power-failure occurs during the rollback, the process that
38188 ** attempts rollback following system recovery sees the same journal
38189 ** content as this process.
38190 **
38191 ** If everything goes as planned, SQLITE_OK is returned. Otherwise, 
38192 ** an SQLite error code.
38193 */
38194 static int pagerSyncHotJournal(Pager *pPager){
38195   int rc = SQLITE_OK;
38196   if( !pPager->noSync ){
38197     rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
38198   }
38199   if( rc==SQLITE_OK ){
38200     rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
38201   }
38202   return rc;
38203 }
38204
38205 /*
38206 ** Shutdown the page cache.  Free all memory and close all files.
38207 **
38208 ** If a transaction was in progress when this routine is called, that
38209 ** transaction is rolled back.  All outstanding pages are invalidated
38210 ** and their memory is freed.  Any attempt to use a page associated
38211 ** with this page cache after this function returns will likely
38212 ** result in a coredump.
38213 **
38214 ** This function always succeeds. If a transaction is active an attempt
38215 ** is made to roll it back. If an error occurs during the rollback 
38216 ** a hot journal may be left in the filesystem but no error is returned
38217 ** to the caller.
38218 */
38219 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
38220   u8 *pTmp = (u8 *)pPager->pTmpSpace;
38221
38222   disable_simulated_io_errors();
38223   sqlite3BeginBenignMalloc();
38224   /* pPager->errCode = 0; */
38225   pPager->exclusiveMode = 0;
38226 #ifndef SQLITE_OMIT_WAL
38227   sqlite3WalClose(pPager->pWal,
38228     (pPager->noSync ? 0 : pPager->sync_flags), 
38229     pPager->pageSize, pTmp
38230   );
38231   pPager->pWal = 0;
38232 #endif
38233   pager_reset(pPager);
38234   if( MEMDB ){
38235     pager_unlock(pPager);
38236   }else{
38237     /* If it is open, sync the journal file before calling UnlockAndRollback.
38238     ** If this is not done, then an unsynced portion of the open journal 
38239     ** file may be played back into the database. If a power failure occurs 
38240     ** while this is happening, the database could become corrupt.
38241     **
38242     ** If an error occurs while trying to sync the journal, shift the pager
38243     ** into the ERROR state. This causes UnlockAndRollback to unlock the
38244     ** database and close the journal file without attempting to roll it
38245     ** back or finalize it. The next database user will have to do hot-journal
38246     ** rollback before accessing the database file.
38247     */
38248     if( isOpen(pPager->jfd) ){
38249       pager_error(pPager, pagerSyncHotJournal(pPager));
38250     }
38251     pagerUnlockAndRollback(pPager);
38252   }
38253   sqlite3EndBenignMalloc();
38254   enable_simulated_io_errors();
38255   PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
38256   IOTRACE(("CLOSE %p\n", pPager))
38257   sqlite3OsClose(pPager->jfd);
38258   sqlite3OsClose(pPager->fd);
38259   sqlite3PageFree(pTmp);
38260   sqlite3PcacheClose(pPager->pPCache);
38261
38262 #ifdef SQLITE_HAS_CODEC
38263   if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
38264 #endif
38265
38266   assert( !pPager->aSavepoint && !pPager->pInJournal );
38267   assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
38268
38269   sqlite3_free(pPager);
38270   return SQLITE_OK;
38271 }
38272
38273 #if !defined(NDEBUG) || defined(SQLITE_TEST)
38274 /*
38275 ** Return the page number for page pPg.
38276 */
38277 SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
38278   return pPg->pgno;
38279 }
38280 #endif
38281
38282 /*
38283 ** Increment the reference count for page pPg.
38284 */
38285 SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
38286   sqlite3PcacheRef(pPg);
38287 }
38288
38289 /*
38290 ** Sync the journal. In other words, make sure all the pages that have
38291 ** been written to the journal have actually reached the surface of the
38292 ** disk and can be restored in the event of a hot-journal rollback.
38293 **
38294 ** If the Pager.noSync flag is set, then this function is a no-op.
38295 ** Otherwise, the actions required depend on the journal-mode and the 
38296 ** device characteristics of the the file-system, as follows:
38297 **
38298 **   * If the journal file is an in-memory journal file, no action need
38299 **     be taken.
38300 **
38301 **   * Otherwise, if the device does not support the SAFE_APPEND property,
38302 **     then the nRec field of the most recently written journal header
38303 **     is updated to contain the number of journal records that have
38304 **     been written following it. If the pager is operating in full-sync
38305 **     mode, then the journal file is synced before this field is updated.
38306 **
38307 **   * If the device does not support the SEQUENTIAL property, then 
38308 **     journal file is synced.
38309 **
38310 ** Or, in pseudo-code:
38311 **
38312 **   if( NOT <in-memory journal> ){
38313 **     if( NOT SAFE_APPEND ){
38314 **       if( <full-sync mode> ) xSync(<journal file>);
38315 **       <update nRec field>
38316 **     } 
38317 **     if( NOT SEQUENTIAL ) xSync(<journal file>);
38318 **   }
38319 **
38320 ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every 
38321 ** page currently held in memory before returning SQLITE_OK. If an IO
38322 ** error is encountered, then the IO error code is returned to the caller.
38323 */
38324 static int syncJournal(Pager *pPager, int newHdr){
38325   int rc;                         /* Return code */
38326
38327   assert( pPager->eState==PAGER_WRITER_CACHEMOD
38328        || pPager->eState==PAGER_WRITER_DBMOD
38329   );
38330   assert( assert_pager_state(pPager) );
38331   assert( !pagerUseWal(pPager) );
38332
38333   rc = sqlite3PagerExclusiveLock(pPager);
38334   if( rc!=SQLITE_OK ) return rc;
38335
38336   if( !pPager->noSync ){
38337     assert( !pPager->tempFile );
38338     if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
38339       const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
38340       assert( isOpen(pPager->jfd) );
38341
38342       if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
38343         /* This block deals with an obscure problem. If the last connection
38344         ** that wrote to this database was operating in persistent-journal
38345         ** mode, then the journal file may at this point actually be larger
38346         ** than Pager.journalOff bytes. If the next thing in the journal
38347         ** file happens to be a journal-header (written as part of the
38348         ** previous connection's transaction), and a crash or power-failure 
38349         ** occurs after nRec is updated but before this connection writes 
38350         ** anything else to the journal file (or commits/rolls back its 
38351         ** transaction), then SQLite may become confused when doing the 
38352         ** hot-journal rollback following recovery. It may roll back all
38353         ** of this connections data, then proceed to rolling back the old,
38354         ** out-of-date data that follows it. Database corruption.
38355         **
38356         ** To work around this, if the journal file does appear to contain
38357         ** a valid header following Pager.journalOff, then write a 0x00
38358         ** byte to the start of it to prevent it from being recognized.
38359         **
38360         ** Variable iNextHdrOffset is set to the offset at which this
38361         ** problematic header will occur, if it exists. aMagic is used 
38362         ** as a temporary buffer to inspect the first couple of bytes of
38363         ** the potential journal header.
38364         */
38365         i64 iNextHdrOffset;
38366         u8 aMagic[8];
38367         u8 zHeader[sizeof(aJournalMagic)+4];
38368
38369         memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
38370         put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
38371
38372         iNextHdrOffset = journalHdrOffset(pPager);
38373         rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
38374         if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
38375           static const u8 zerobyte = 0;
38376           rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
38377         }
38378         if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
38379           return rc;
38380         }
38381
38382         /* Write the nRec value into the journal file header. If in
38383         ** full-synchronous mode, sync the journal first. This ensures that
38384         ** all data has really hit the disk before nRec is updated to mark
38385         ** it as a candidate for rollback.
38386         **
38387         ** This is not required if the persistent media supports the
38388         ** SAFE_APPEND property. Because in this case it is not possible 
38389         ** for garbage data to be appended to the file, the nRec field
38390         ** is populated with 0xFFFFFFFF when the journal header is written
38391         ** and never needs to be updated.
38392         */
38393         if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
38394           PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
38395           IOTRACE(("JSYNC %p\n", pPager))
38396           rc = sqlite3OsSync(pPager->jfd, pPager->sync_flags);
38397           if( rc!=SQLITE_OK ) return rc;
38398         }
38399         IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
38400         rc = sqlite3OsWrite(
38401             pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
38402         );
38403         if( rc!=SQLITE_OK ) return rc;
38404       }
38405       if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
38406         PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
38407         IOTRACE(("JSYNC %p\n", pPager))
38408         rc = sqlite3OsSync(pPager->jfd, pPager->sync_flags| 
38409           (pPager->sync_flags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
38410         );
38411         if( rc!=SQLITE_OK ) return rc;
38412       }
38413
38414       pPager->journalHdr = pPager->journalOff;
38415       if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
38416         pPager->nRec = 0;
38417         rc = writeJournalHdr(pPager);
38418         if( rc!=SQLITE_OK ) return rc;
38419       }
38420     }else{
38421       pPager->journalHdr = pPager->journalOff;
38422     }
38423   }
38424
38425   /* Unless the pager is in noSync mode, the journal file was just 
38426   ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on 
38427   ** all pages.
38428   */
38429   sqlite3PcacheClearSyncFlags(pPager->pPCache);
38430   pPager->eState = PAGER_WRITER_DBMOD;
38431   assert( assert_pager_state(pPager) );
38432   return SQLITE_OK;
38433 }
38434
38435 /*
38436 ** The argument is the first in a linked list of dirty pages connected
38437 ** by the PgHdr.pDirty pointer. This function writes each one of the
38438 ** in-memory pages in the list to the database file. The argument may
38439 ** be NULL, representing an empty list. In this case this function is
38440 ** a no-op.
38441 **
38442 ** The pager must hold at least a RESERVED lock when this function
38443 ** is called. Before writing anything to the database file, this lock
38444 ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
38445 ** SQLITE_BUSY is returned and no data is written to the database file.
38446 ** 
38447 ** If the pager is a temp-file pager and the actual file-system file
38448 ** is not yet open, it is created and opened before any data is 
38449 ** written out.
38450 **
38451 ** Once the lock has been upgraded and, if necessary, the file opened,
38452 ** the pages are written out to the database file in list order. Writing
38453 ** a page is skipped if it meets either of the following criteria:
38454 **
38455 **   * The page number is greater than Pager.dbSize, or
38456 **   * The PGHDR_DONT_WRITE flag is set on the page.
38457 **
38458 ** If writing out a page causes the database file to grow, Pager.dbFileSize
38459 ** is updated accordingly. If page 1 is written out, then the value cached
38460 ** in Pager.dbFileVers[] is updated to match the new value stored in
38461 ** the database file.
38462 **
38463 ** If everything is successful, SQLITE_OK is returned. If an IO error 
38464 ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
38465 ** be obtained, SQLITE_BUSY is returned.
38466 */
38467 static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
38468   int rc = SQLITE_OK;                  /* Return code */
38469
38470   /* This function is only called for rollback pagers in WRITER_DBMOD state. */
38471   assert( !pagerUseWal(pPager) );
38472   assert( pPager->eState==PAGER_WRITER_DBMOD );
38473   assert( pPager->eLock==EXCLUSIVE_LOCK );
38474
38475   /* If the file is a temp-file has not yet been opened, open it now. It
38476   ** is not possible for rc to be other than SQLITE_OK if this branch
38477   ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
38478   */
38479   if( !isOpen(pPager->fd) ){
38480     assert( pPager->tempFile && rc==SQLITE_OK );
38481     rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
38482   }
38483
38484   /* Before the first write, give the VFS a hint of what the final
38485   ** file size will be.
38486   */
38487   assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
38488   if( rc==SQLITE_OK && pPager->dbSize>pPager->dbHintSize ){
38489     sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
38490     sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
38491     pPager->dbHintSize = pPager->dbSize;
38492   }
38493
38494   while( rc==SQLITE_OK && pList ){
38495     Pgno pgno = pList->pgno;
38496
38497     /* If there are dirty pages in the page cache with page numbers greater
38498     ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
38499     ** make the file smaller (presumably by auto-vacuum code). Do not write
38500     ** any such pages to the file.
38501     **
38502     ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
38503     ** set (set by sqlite3PagerDontWrite()).
38504     */
38505     if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
38506       i64 offset = (pgno-1)*(i64)pPager->pageSize;   /* Offset to write */
38507       char *pData;                                   /* Data to write */    
38508
38509       assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
38510
38511       /* Encode the database */
38512       CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
38513
38514       /* Write out the page data. */
38515       rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
38516
38517       /* If page 1 was just written, update Pager.dbFileVers to match
38518       ** the value now stored in the database file. If writing this 
38519       ** page caused the database file to grow, update dbFileSize. 
38520       */
38521       if( pgno==1 ){
38522         memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
38523       }
38524       if( pgno>pPager->dbFileSize ){
38525         pPager->dbFileSize = pgno;
38526       }
38527
38528       /* Update any backup objects copying the contents of this pager. */
38529       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
38530
38531       PAGERTRACE(("STORE %d page %d hash(%08x)\n",
38532                    PAGERID(pPager), pgno, pager_pagehash(pList)));
38533       IOTRACE(("PGOUT %p %d\n", pPager, pgno));
38534       PAGER_INCR(sqlite3_pager_writedb_count);
38535       PAGER_INCR(pPager->nWrite);
38536     }else{
38537       PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
38538     }
38539     pager_set_pagehash(pList);
38540     pList = pList->pDirty;
38541   }
38542
38543   return rc;
38544 }
38545
38546 /*
38547 ** Ensure that the sub-journal file is open. If it is already open, this 
38548 ** function is a no-op.
38549 **
38550 ** SQLITE_OK is returned if everything goes according to plan. An 
38551 ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen() 
38552 ** fails.
38553 */
38554 static int openSubJournal(Pager *pPager){
38555   int rc = SQLITE_OK;
38556   if( !isOpen(pPager->sjfd) ){
38557     if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
38558       sqlite3MemJournalOpen(pPager->sjfd);
38559     }else{
38560       rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
38561     }
38562   }
38563   return rc;
38564 }
38565
38566 /*
38567 ** Append a record of the current state of page pPg to the sub-journal. 
38568 ** It is the callers responsibility to use subjRequiresPage() to check 
38569 ** that it is really required before calling this function.
38570 **
38571 ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
38572 ** for all open savepoints before returning.
38573 **
38574 ** This function returns SQLITE_OK if everything is successful, an IO
38575 ** error code if the attempt to write to the sub-journal fails, or 
38576 ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
38577 ** bitvec.
38578 */
38579 static int subjournalPage(PgHdr *pPg){
38580   int rc = SQLITE_OK;
38581   Pager *pPager = pPg->pPager;
38582   if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
38583
38584     /* Open the sub-journal, if it has not already been opened */
38585     assert( pPager->useJournal );
38586     assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
38587     assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
38588     assert( pagerUseWal(pPager) 
38589          || pageInJournal(pPg) 
38590          || pPg->pgno>pPager->dbOrigSize 
38591     );
38592     rc = openSubJournal(pPager);
38593
38594     /* If the sub-journal was opened successfully (or was already open),
38595     ** write the journal record into the file.  */
38596     if( rc==SQLITE_OK ){
38597       void *pData = pPg->pData;
38598       i64 offset = pPager->nSubRec*(4+pPager->pageSize);
38599       char *pData2;
38600   
38601       CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
38602       PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
38603       rc = write32bits(pPager->sjfd, offset, pPg->pgno);
38604       if( rc==SQLITE_OK ){
38605         rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
38606       }
38607     }
38608   }
38609   if( rc==SQLITE_OK ){
38610     pPager->nSubRec++;
38611     assert( pPager->nSavepoint>0 );
38612     rc = addToSavepointBitvecs(pPager, pPg->pgno);
38613   }
38614   return rc;
38615 }
38616
38617 /*
38618 ** This function is called by the pcache layer when it has reached some
38619 ** soft memory limit. The first argument is a pointer to a Pager object
38620 ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
38621 ** database). The second argument is a reference to a page that is 
38622 ** currently dirty but has no outstanding references. The page
38623 ** is always associated with the Pager object passed as the first 
38624 ** argument.
38625 **
38626 ** The job of this function is to make pPg clean by writing its contents
38627 ** out to the database file, if possible. This may involve syncing the
38628 ** journal file. 
38629 **
38630 ** If successful, sqlite3PcacheMakeClean() is called on the page and
38631 ** SQLITE_OK returned. If an IO error occurs while trying to make the
38632 ** page clean, the IO error code is returned. If the page cannot be
38633 ** made clean for some other reason, but no error occurs, then SQLITE_OK
38634 ** is returned by sqlite3PcacheMakeClean() is not called.
38635 */
38636 static int pagerStress(void *p, PgHdr *pPg){
38637   Pager *pPager = (Pager *)p;
38638   int rc = SQLITE_OK;
38639
38640   assert( pPg->pPager==pPager );
38641   assert( pPg->flags&PGHDR_DIRTY );
38642
38643   /* The doNotSyncSpill flag is set during times when doing a sync of
38644   ** journal (and adding a new header) is not allowed.  This occurs
38645   ** during calls to sqlite3PagerWrite() while trying to journal multiple
38646   ** pages belonging to the same sector.
38647   **
38648   ** The doNotSpill flag inhibits all cache spilling regardless of whether
38649   ** or not a sync is required.  This is set during a rollback.
38650   **
38651   ** Spilling is also prohibited when in an error state since that could
38652   ** lead to database corruption.   In the current implementaton it 
38653   ** is impossible for sqlite3PCacheFetch() to be called with createFlag==1
38654   ** while in the error state, hence it is impossible for this routine to
38655   ** be called in the error state.  Nevertheless, we include a NEVER()
38656   ** test for the error state as a safeguard against future changes.
38657   */
38658   if( NEVER(pPager->errCode) ) return SQLITE_OK;
38659   if( pPager->doNotSpill ) return SQLITE_OK;
38660   if( pPager->doNotSyncSpill && (pPg->flags & PGHDR_NEED_SYNC)!=0 ){
38661     return SQLITE_OK;
38662   }
38663
38664   pPg->pDirty = 0;
38665   if( pagerUseWal(pPager) ){
38666     /* Write a single frame for this page to the log. */
38667     if( subjRequiresPage(pPg) ){ 
38668       rc = subjournalPage(pPg); 
38669     }
38670     if( rc==SQLITE_OK ){
38671       rc = pagerWalFrames(pPager, pPg, 0, 0, 0);
38672     }
38673   }else{
38674   
38675     /* Sync the journal file if required. */
38676     if( pPg->flags&PGHDR_NEED_SYNC 
38677      || pPager->eState==PAGER_WRITER_CACHEMOD
38678     ){
38679       rc = syncJournal(pPager, 1);
38680     }
38681   
38682     /* If the page number of this page is larger than the current size of
38683     ** the database image, it may need to be written to the sub-journal.
38684     ** This is because the call to pager_write_pagelist() below will not
38685     ** actually write data to the file in this case.
38686     **
38687     ** Consider the following sequence of events:
38688     **
38689     **   BEGIN;
38690     **     <journal page X>
38691     **     <modify page X>
38692     **     SAVEPOINT sp;
38693     **       <shrink database file to Y pages>
38694     **       pagerStress(page X)
38695     **     ROLLBACK TO sp;
38696     **
38697     ** If (X>Y), then when pagerStress is called page X will not be written
38698     ** out to the database file, but will be dropped from the cache. Then,
38699     ** following the "ROLLBACK TO sp" statement, reading page X will read
38700     ** data from the database file. This will be the copy of page X as it
38701     ** was when the transaction started, not as it was when "SAVEPOINT sp"
38702     ** was executed.
38703     **
38704     ** The solution is to write the current data for page X into the 
38705     ** sub-journal file now (if it is not already there), so that it will
38706     ** be restored to its current value when the "ROLLBACK TO sp" is 
38707     ** executed.
38708     */
38709     if( NEVER(
38710         rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg)
38711     ) ){
38712       rc = subjournalPage(pPg);
38713     }
38714   
38715     /* Write the contents of the page out to the database file. */
38716     if( rc==SQLITE_OK ){
38717       assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
38718       rc = pager_write_pagelist(pPager, pPg);
38719     }
38720   }
38721
38722   /* Mark the page as clean. */
38723   if( rc==SQLITE_OK ){
38724     PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
38725     sqlite3PcacheMakeClean(pPg);
38726   }
38727
38728   return pager_error(pPager, rc); 
38729 }
38730
38731
38732 /*
38733 ** Allocate and initialize a new Pager object and put a pointer to it
38734 ** in *ppPager. The pager should eventually be freed by passing it
38735 ** to sqlite3PagerClose().
38736 **
38737 ** The zFilename argument is the path to the database file to open.
38738 ** If zFilename is NULL then a randomly-named temporary file is created
38739 ** and used as the file to be cached. Temporary files are be deleted
38740 ** automatically when they are closed. If zFilename is ":memory:" then 
38741 ** all information is held in cache. It is never written to disk. 
38742 ** This can be used to implement an in-memory database.
38743 **
38744 ** The nExtra parameter specifies the number of bytes of space allocated
38745 ** along with each page reference. This space is available to the user
38746 ** via the sqlite3PagerGetExtra() API.
38747 **
38748 ** The flags argument is used to specify properties that affect the
38749 ** operation of the pager. It should be passed some bitwise combination
38750 ** of the PAGER_OMIT_JOURNAL and PAGER_NO_READLOCK flags.
38751 **
38752 ** The vfsFlags parameter is a bitmask to pass to the flags parameter
38753 ** of the xOpen() method of the supplied VFS when opening files. 
38754 **
38755 ** If the pager object is allocated and the specified file opened 
38756 ** successfully, SQLITE_OK is returned and *ppPager set to point to
38757 ** the new pager object. If an error occurs, *ppPager is set to NULL
38758 ** and error code returned. This function may return SQLITE_NOMEM
38759 ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or 
38760 ** various SQLITE_IO_XXX errors.
38761 */
38762 SQLITE_PRIVATE int sqlite3PagerOpen(
38763   sqlite3_vfs *pVfs,       /* The virtual file system to use */
38764   Pager **ppPager,         /* OUT: Return the Pager structure here */
38765   const char *zFilename,   /* Name of the database file to open */
38766   int nExtra,              /* Extra bytes append to each in-memory page */
38767   int flags,               /* flags controlling this file */
38768   int vfsFlags,            /* flags passed through to sqlite3_vfs.xOpen() */
38769   void (*xReinit)(DbPage*) /* Function to reinitialize pages */
38770 ){
38771   u8 *pPtr;
38772   Pager *pPager = 0;       /* Pager object to allocate and return */
38773   int rc = SQLITE_OK;      /* Return code */
38774   int tempFile = 0;        /* True for temp files (incl. in-memory files) */
38775   int memDb = 0;           /* True if this is an in-memory file */
38776   int readOnly = 0;        /* True if this is a read-only file */
38777   int journalFileSize;     /* Bytes to allocate for each journal fd */
38778   char *zPathname = 0;     /* Full path to database file */
38779   int nPathname = 0;       /* Number of bytes in zPathname */
38780   int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
38781   int noReadlock = (flags & PAGER_NO_READLOCK)!=0;  /* True to omit read-lock */
38782   int pcacheSize = sqlite3PcacheSize();       /* Bytes to allocate for PCache */
38783   u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;  /* Default page size */
38784
38785   /* Figure out how much space is required for each journal file-handle
38786   ** (there are two of them, the main journal and the sub-journal). This
38787   ** is the maximum space required for an in-memory journal file handle 
38788   ** and a regular journal file-handle. Note that a "regular journal-handle"
38789   ** may be a wrapper capable of caching the first portion of the journal
38790   ** file in memory to implement the atomic-write optimization (see 
38791   ** source file journal.c).
38792   */
38793   if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
38794     journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
38795   }else{
38796     journalFileSize = ROUND8(sqlite3MemJournalSize());
38797   }
38798
38799   /* Set the output variable to NULL in case an error occurs. */
38800   *ppPager = 0;
38801
38802 #ifndef SQLITE_OMIT_MEMORYDB
38803   if( flags & PAGER_MEMORY ){
38804     memDb = 1;
38805     zFilename = 0;
38806   }
38807 #endif
38808
38809   /* Compute and store the full pathname in an allocated buffer pointed
38810   ** to by zPathname, length nPathname. Or, if this is a temporary file,
38811   ** leave both nPathname and zPathname set to 0.
38812   */
38813   if( zFilename && zFilename[0] ){
38814     nPathname = pVfs->mxPathname+1;
38815     zPathname = sqlite3Malloc(nPathname*2);
38816     if( zPathname==0 ){
38817       return SQLITE_NOMEM;
38818     }
38819     zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
38820     rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
38821     nPathname = sqlite3Strlen30(zPathname);
38822     if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
38823       /* This branch is taken when the journal path required by
38824       ** the database being opened will be more than pVfs->mxPathname
38825       ** bytes in length. This means the database cannot be opened,
38826       ** as it will not be possible to open the journal file or even
38827       ** check for a hot-journal before reading.
38828       */
38829       rc = SQLITE_CANTOPEN_BKPT;
38830     }
38831     if( rc!=SQLITE_OK ){
38832       sqlite3_free(zPathname);
38833       return rc;
38834     }
38835   }
38836
38837   /* Allocate memory for the Pager structure, PCache object, the
38838   ** three file descriptors, the database file name and the journal 
38839   ** file name. The layout in memory is as follows:
38840   **
38841   **     Pager object                    (sizeof(Pager) bytes)
38842   **     PCache object                   (sqlite3PcacheSize() bytes)
38843   **     Database file handle            (pVfs->szOsFile bytes)
38844   **     Sub-journal file handle         (journalFileSize bytes)
38845   **     Main journal file handle        (journalFileSize bytes)
38846   **     Database file name              (nPathname+1 bytes)
38847   **     Journal file name               (nPathname+8+1 bytes)
38848   */
38849   pPtr = (u8 *)sqlite3MallocZero(
38850     ROUND8(sizeof(*pPager)) +      /* Pager structure */
38851     ROUND8(pcacheSize) +           /* PCache object */
38852     ROUND8(pVfs->szOsFile) +       /* The main db file */
38853     journalFileSize * 2 +          /* The two journal files */ 
38854     nPathname + 1 +                /* zFilename */
38855     nPathname + 8 + 1              /* zJournal */
38856 #ifndef SQLITE_OMIT_WAL
38857     + nPathname + 4 + 1              /* zWal */
38858 #endif
38859   );
38860   assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
38861   if( !pPtr ){
38862     sqlite3_free(zPathname);
38863     return SQLITE_NOMEM;
38864   }
38865   pPager =              (Pager*)(pPtr);
38866   pPager->pPCache =    (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
38867   pPager->fd =   (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
38868   pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
38869   pPager->jfd =  (sqlite3_file*)(pPtr += journalFileSize);
38870   pPager->zFilename =    (char*)(pPtr += journalFileSize);
38871   assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
38872
38873   /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
38874   if( zPathname ){
38875     assert( nPathname>0 );
38876     pPager->zJournal =   (char*)(pPtr += nPathname + 1);
38877     memcpy(pPager->zFilename, zPathname, nPathname);
38878     memcpy(pPager->zJournal, zPathname, nPathname);
38879     memcpy(&pPager->zJournal[nPathname], "-journal", 8);
38880 #ifndef SQLITE_OMIT_WAL
38881     pPager->zWal = &pPager->zJournal[nPathname+8+1];
38882     memcpy(pPager->zWal, zPathname, nPathname);
38883     memcpy(&pPager->zWal[nPathname], "-wal", 4);
38884 #endif
38885     sqlite3_free(zPathname);
38886   }
38887   pPager->pVfs = pVfs;
38888   pPager->vfsFlags = vfsFlags;
38889
38890   /* Open the pager file.
38891   */
38892   if( zFilename && zFilename[0] ){
38893     int fout = 0;                    /* VFS flags returned by xOpen() */
38894     rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
38895     assert( !memDb );
38896     readOnly = (fout&SQLITE_OPEN_READONLY);
38897
38898     /* If the file was successfully opened for read/write access,
38899     ** choose a default page size in case we have to create the
38900     ** database file. The default page size is the maximum of:
38901     **
38902     **    + SQLITE_DEFAULT_PAGE_SIZE,
38903     **    + The value returned by sqlite3OsSectorSize()
38904     **    + The largest page size that can be written atomically.
38905     */
38906     if( rc==SQLITE_OK && !readOnly ){
38907       setSectorSize(pPager);
38908       assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
38909       if( szPageDflt<pPager->sectorSize ){
38910         if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
38911           szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
38912         }else{
38913           szPageDflt = (u32)pPager->sectorSize;
38914         }
38915       }
38916 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
38917       {
38918         int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
38919         int ii;
38920         assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
38921         assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
38922         assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
38923         for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
38924           if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
38925             szPageDflt = ii;
38926           }
38927         }
38928       }
38929 #endif
38930     }
38931   }else{
38932     /* If a temporary file is requested, it is not opened immediately.
38933     ** In this case we accept the default page size and delay actually
38934     ** opening the file until the first call to OsWrite().
38935     **
38936     ** This branch is also run for an in-memory database. An in-memory
38937     ** database is the same as a temp-file that is never written out to
38938     ** disk and uses an in-memory rollback journal.
38939     */ 
38940     tempFile = 1;
38941     pPager->eState = PAGER_READER;
38942     pPager->eLock = EXCLUSIVE_LOCK;
38943     readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
38944   }
38945
38946   /* The following call to PagerSetPagesize() serves to set the value of 
38947   ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
38948   */
38949   if( rc==SQLITE_OK ){
38950     assert( pPager->memDb==0 );
38951     rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
38952     testcase( rc!=SQLITE_OK );
38953   }
38954
38955   /* If an error occurred in either of the blocks above, free the 
38956   ** Pager structure and close the file.
38957   */
38958   if( rc!=SQLITE_OK ){
38959     assert( !pPager->pTmpSpace );
38960     sqlite3OsClose(pPager->fd);
38961     sqlite3_free(pPager);
38962     return rc;
38963   }
38964
38965   /* Initialize the PCache object. */
38966   assert( nExtra<1000 );
38967   nExtra = ROUND8(nExtra);
38968   sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
38969                     !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
38970
38971   PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
38972   IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
38973
38974   pPager->useJournal = (u8)useJournal;
38975   pPager->noReadlock = (noReadlock && readOnly) ?1:0;
38976   /* pPager->stmtOpen = 0; */
38977   /* pPager->stmtInUse = 0; */
38978   /* pPager->nRef = 0; */
38979   /* pPager->stmtSize = 0; */
38980   /* pPager->stmtJSize = 0; */
38981   /* pPager->nPage = 0; */
38982   pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
38983   /* pPager->state = PAGER_UNLOCK; */
38984 #if 0
38985   assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
38986 #endif
38987   /* pPager->errMask = 0; */
38988   pPager->tempFile = (u8)tempFile;
38989   assert( tempFile==PAGER_LOCKINGMODE_NORMAL 
38990           || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
38991   assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
38992   pPager->exclusiveMode = (u8)tempFile; 
38993   pPager->changeCountDone = pPager->tempFile;
38994   pPager->memDb = (u8)memDb;
38995   pPager->readOnly = (u8)readOnly;
38996   assert( useJournal || pPager->tempFile );
38997   pPager->noSync = pPager->tempFile;
38998   pPager->fullSync = pPager->noSync ?0:1;
38999   pPager->sync_flags = SQLITE_SYNC_NORMAL;
39000   /* pPager->pFirst = 0; */
39001   /* pPager->pFirstSynced = 0; */
39002   /* pPager->pLast = 0; */
39003   pPager->nExtra = (u16)nExtra;
39004   pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
39005   assert( isOpen(pPager->fd) || tempFile );
39006   setSectorSize(pPager);
39007   if( !useJournal ){
39008     pPager->journalMode = PAGER_JOURNALMODE_OFF;
39009   }else if( memDb ){
39010     pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
39011   }
39012   /* pPager->xBusyHandler = 0; */
39013   /* pPager->pBusyHandlerArg = 0; */
39014   pPager->xReiniter = xReinit;
39015   /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
39016
39017   *ppPager = pPager;
39018   return SQLITE_OK;
39019 }
39020
39021
39022
39023 /*
39024 ** This function is called after transitioning from PAGER_UNLOCK to
39025 ** PAGER_SHARED state. It tests if there is a hot journal present in
39026 ** the file-system for the given pager. A hot journal is one that 
39027 ** needs to be played back. According to this function, a hot-journal
39028 ** file exists if the following criteria are met:
39029 **
39030 **   * The journal file exists in the file system, and
39031 **   * No process holds a RESERVED or greater lock on the database file, and
39032 **   * The database file itself is greater than 0 bytes in size, and
39033 **   * The first byte of the journal file exists and is not 0x00.
39034 **
39035 ** If the current size of the database file is 0 but a journal file
39036 ** exists, that is probably an old journal left over from a prior
39037 ** database with the same name. In this case the journal file is
39038 ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
39039 ** is returned.
39040 **
39041 ** This routine does not check if there is a master journal filename
39042 ** at the end of the file. If there is, and that master journal file
39043 ** does not exist, then the journal file is not really hot. In this
39044 ** case this routine will return a false-positive. The pager_playback()
39045 ** routine will discover that the journal file is not really hot and 
39046 ** will not roll it back. 
39047 **
39048 ** If a hot-journal file is found to exist, *pExists is set to 1 and 
39049 ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
39050 ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
39051 ** to determine whether or not a hot-journal file exists, the IO error
39052 ** code is returned and the value of *pExists is undefined.
39053 */
39054 static int hasHotJournal(Pager *pPager, int *pExists){
39055   sqlite3_vfs * const pVfs = pPager->pVfs;
39056   int rc = SQLITE_OK;           /* Return code */
39057   int exists = 1;               /* True if a journal file is present */
39058   int jrnlOpen = !!isOpen(pPager->jfd);
39059
39060   assert( pPager->useJournal );
39061   assert( isOpen(pPager->fd) );
39062   assert( pPager->eState==PAGER_OPEN );
39063
39064   assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
39065     SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
39066   ));
39067
39068   *pExists = 0;
39069   if( !jrnlOpen ){
39070     rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
39071   }
39072   if( rc==SQLITE_OK && exists ){
39073     int locked = 0;             /* True if some process holds a RESERVED lock */
39074
39075     /* Race condition here:  Another process might have been holding the
39076     ** the RESERVED lock and have a journal open at the sqlite3OsAccess() 
39077     ** call above, but then delete the journal and drop the lock before
39078     ** we get to the following sqlite3OsCheckReservedLock() call.  If that
39079     ** is the case, this routine might think there is a hot journal when
39080     ** in fact there is none.  This results in a false-positive which will
39081     ** be dealt with by the playback routine.  Ticket #3883.
39082     */
39083     rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
39084     if( rc==SQLITE_OK && !locked ){
39085       Pgno nPage;                 /* Number of pages in database file */
39086
39087       /* Check the size of the database file. If it consists of 0 pages,
39088       ** then delete the journal file. See the header comment above for 
39089       ** the reasoning here.  Delete the obsolete journal file under
39090       ** a RESERVED lock to avoid race conditions and to avoid violating
39091       ** [H33020].
39092       */
39093       rc = pagerPagecount(pPager, &nPage);
39094       if( rc==SQLITE_OK ){
39095         if( nPage==0 ){
39096           sqlite3BeginBenignMalloc();
39097           if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
39098             sqlite3OsDelete(pVfs, pPager->zJournal, 0);
39099             pagerUnlockDb(pPager, SHARED_LOCK);
39100           }
39101           sqlite3EndBenignMalloc();
39102         }else{
39103           /* The journal file exists and no other connection has a reserved
39104           ** or greater lock on the database file. Now check that there is
39105           ** at least one non-zero bytes at the start of the journal file.
39106           ** If there is, then we consider this journal to be hot. If not, 
39107           ** it can be ignored.
39108           */
39109           if( !jrnlOpen ){
39110             int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
39111             rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
39112           }
39113           if( rc==SQLITE_OK ){
39114             u8 first = 0;
39115             rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
39116             if( rc==SQLITE_IOERR_SHORT_READ ){
39117               rc = SQLITE_OK;
39118             }
39119             if( !jrnlOpen ){
39120               sqlite3OsClose(pPager->jfd);
39121             }
39122             *pExists = (first!=0);
39123           }else if( rc==SQLITE_CANTOPEN ){
39124             /* If we cannot open the rollback journal file in order to see if
39125             ** its has a zero header, that might be due to an I/O error, or
39126             ** it might be due to the race condition described above and in
39127             ** ticket #3883.  Either way, assume that the journal is hot.
39128             ** This might be a false positive.  But if it is, then the
39129             ** automatic journal playback and recovery mechanism will deal
39130             ** with it under an EXCLUSIVE lock where we do not need to
39131             ** worry so much with race conditions.
39132             */
39133             *pExists = 1;
39134             rc = SQLITE_OK;
39135           }
39136         }
39137       }
39138     }
39139   }
39140
39141   return rc;
39142 }
39143
39144 /*
39145 ** This function is called to obtain a shared lock on the database file.
39146 ** It is illegal to call sqlite3PagerAcquire() until after this function
39147 ** has been successfully called. If a shared-lock is already held when
39148 ** this function is called, it is a no-op.
39149 **
39150 ** The following operations are also performed by this function.
39151 **
39152 **   1) If the pager is currently in PAGER_OPEN state (no lock held
39153 **      on the database file), then an attempt is made to obtain a
39154 **      SHARED lock on the database file. Immediately after obtaining
39155 **      the SHARED lock, the file-system is checked for a hot-journal,
39156 **      which is played back if present. Following any hot-journal 
39157 **      rollback, the contents of the cache are validated by checking
39158 **      the 'change-counter' field of the database file header and
39159 **      discarded if they are found to be invalid.
39160 **
39161 **   2) If the pager is running in exclusive-mode, and there are currently
39162 **      no outstanding references to any pages, and is in the error state,
39163 **      then an attempt is made to clear the error state by discarding
39164 **      the contents of the page cache and rolling back any open journal
39165 **      file.
39166 **
39167 ** If everything is successful, SQLITE_OK is returned. If an IO error 
39168 ** occurs while locking the database, checking for a hot-journal file or 
39169 ** rolling back a journal file, the IO error code is returned.
39170 */
39171 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
39172   int rc = SQLITE_OK;                /* Return code */
39173
39174   /* This routine is only called from b-tree and only when there are no
39175   ** outstanding pages. This implies that the pager state should either
39176   ** be OPEN or READER. READER is only possible if the pager is or was in 
39177   ** exclusive access mode.
39178   */
39179   assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
39180   assert( assert_pager_state(pPager) );
39181   assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
39182   if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
39183
39184   if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
39185     int bHotJournal = 1;          /* True if there exists a hot journal-file */
39186
39187     assert( !MEMDB );
39188     assert( pPager->noReadlock==0 || pPager->readOnly );
39189
39190     if( pPager->noReadlock==0 ){
39191       rc = pager_wait_on_lock(pPager, SHARED_LOCK);
39192       if( rc!=SQLITE_OK ){
39193         assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
39194         goto failed;
39195       }
39196     }
39197
39198     /* If a journal file exists, and there is no RESERVED lock on the
39199     ** database file, then it either needs to be played back or deleted.
39200     */
39201     if( pPager->eLock<=SHARED_LOCK ){
39202       rc = hasHotJournal(pPager, &bHotJournal);
39203     }
39204     if( rc!=SQLITE_OK ){
39205       goto failed;
39206     }
39207     if( bHotJournal ){
39208       /* Get an EXCLUSIVE lock on the database file. At this point it is
39209       ** important that a RESERVED lock is not obtained on the way to the
39210       ** EXCLUSIVE lock. If it were, another process might open the
39211       ** database file, detect the RESERVED lock, and conclude that the
39212       ** database is safe to read while this process is still rolling the 
39213       ** hot-journal back.
39214       ** 
39215       ** Because the intermediate RESERVED lock is not requested, any
39216       ** other process attempting to access the database file will get to 
39217       ** this point in the code and fail to obtain its own EXCLUSIVE lock 
39218       ** on the database file.
39219       **
39220       ** Unless the pager is in locking_mode=exclusive mode, the lock is
39221       ** downgraded to SHARED_LOCK before this function returns.
39222       */
39223       rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
39224       if( rc!=SQLITE_OK ){
39225         goto failed;
39226       }
39227  
39228       /* If it is not already open and the file exists on disk, open the 
39229       ** journal for read/write access. Write access is required because 
39230       ** in exclusive-access mode the file descriptor will be kept open 
39231       ** and possibly used for a transaction later on. Also, write-access 
39232       ** is usually required to finalize the journal in journal_mode=persist 
39233       ** mode (and also for journal_mode=truncate on some systems).
39234       **
39235       ** If the journal does not exist, it usually means that some 
39236       ** other connection managed to get in and roll it back before 
39237       ** this connection obtained the exclusive lock above. Or, it 
39238       ** may mean that the pager was in the error-state when this
39239       ** function was called and the journal file does not exist.
39240       */
39241       if( !isOpen(pPager->jfd) ){
39242         sqlite3_vfs * const pVfs = pPager->pVfs;
39243         int bExists;              /* True if journal file exists */
39244         rc = sqlite3OsAccess(
39245             pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
39246         if( rc==SQLITE_OK && bExists ){
39247           int fout = 0;
39248           int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
39249           assert( !pPager->tempFile );
39250           rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
39251           assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
39252           if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
39253             rc = SQLITE_CANTOPEN_BKPT;
39254             sqlite3OsClose(pPager->jfd);
39255           }
39256         }
39257       }
39258  
39259       /* Playback and delete the journal.  Drop the database write
39260       ** lock and reacquire the read lock. Purge the cache before
39261       ** playing back the hot-journal so that we don't end up with
39262       ** an inconsistent cache.  Sync the hot journal before playing
39263       ** it back since the process that crashed and left the hot journal
39264       ** probably did not sync it and we are required to always sync
39265       ** the journal before playing it back.
39266       */
39267       if( isOpen(pPager->jfd) ){
39268         assert( rc==SQLITE_OK );
39269         rc = pagerSyncHotJournal(pPager);
39270         if( rc==SQLITE_OK ){
39271           rc = pager_playback(pPager, 1);
39272           pPager->eState = PAGER_OPEN;
39273         }
39274       }else if( !pPager->exclusiveMode ){
39275         pagerUnlockDb(pPager, SHARED_LOCK);
39276       }
39277
39278       if( rc!=SQLITE_OK ){
39279         /* This branch is taken if an error occurs while trying to open
39280         ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
39281         ** pager_unlock() routine will be called before returning to unlock
39282         ** the file. If the unlock attempt fails, then Pager.eLock must be
39283         ** set to UNKNOWN_LOCK (see the comment above the #define for 
39284         ** UNKNOWN_LOCK above for an explanation). 
39285         **
39286         ** In order to get pager_unlock() to do this, set Pager.eState to
39287         ** PAGER_ERROR now. This is not actually counted as a transition
39288         ** to ERROR state in the state diagram at the top of this file,
39289         ** since we know that the same call to pager_unlock() will very
39290         ** shortly transition the pager object to the OPEN state. Calling
39291         ** assert_pager_state() would fail now, as it should not be possible
39292         ** to be in ERROR state when there are zero outstanding page 
39293         ** references.
39294         */
39295         pager_error(pPager, rc);
39296         goto failed;
39297       }
39298
39299       assert( pPager->eState==PAGER_OPEN );
39300       assert( (pPager->eLock==SHARED_LOCK)
39301            || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
39302       );
39303     }
39304
39305     if( !pPager->tempFile 
39306      && (pPager->pBackup || sqlite3PcachePagecount(pPager->pPCache)>0) 
39307     ){
39308       /* The shared-lock has just been acquired on the database file
39309       ** and there are already pages in the cache (from a previous
39310       ** read or write transaction).  Check to see if the database
39311       ** has been modified.  If the database has changed, flush the
39312       ** cache.
39313       **
39314       ** Database changes is detected by looking at 15 bytes beginning
39315       ** at offset 24 into the file.  The first 4 of these 16 bytes are
39316       ** a 32-bit counter that is incremented with each change.  The
39317       ** other bytes change randomly with each file change when
39318       ** a codec is in use.
39319       ** 
39320       ** There is a vanishingly small chance that a change will not be 
39321       ** detected.  The chance of an undetected change is so small that
39322       ** it can be neglected.
39323       */
39324       Pgno nPage = 0;
39325       char dbFileVers[sizeof(pPager->dbFileVers)];
39326
39327       rc = pagerPagecount(pPager, &nPage);
39328       if( rc ) goto failed;
39329
39330       if( nPage>0 ){
39331         IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
39332         rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
39333         if( rc!=SQLITE_OK ){
39334           goto failed;
39335         }
39336       }else{
39337         memset(dbFileVers, 0, sizeof(dbFileVers));
39338       }
39339
39340       if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
39341         pager_reset(pPager);
39342       }
39343     }
39344
39345     /* If there is a WAL file in the file-system, open this database in WAL
39346     ** mode. Otherwise, the following function call is a no-op.
39347     */
39348     rc = pagerOpenWalIfPresent(pPager);
39349 #ifndef SQLITE_OMIT_WAL
39350     assert( pPager->pWal==0 || rc==SQLITE_OK );
39351 #endif
39352   }
39353
39354   if( pagerUseWal(pPager) ){
39355     assert( rc==SQLITE_OK );
39356     rc = pagerBeginReadTransaction(pPager);
39357   }
39358
39359   if( pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
39360     rc = pagerPagecount(pPager, &pPager->dbSize);
39361   }
39362
39363  failed:
39364   if( rc!=SQLITE_OK ){
39365     assert( !MEMDB );
39366     pager_unlock(pPager);
39367     assert( pPager->eState==PAGER_OPEN );
39368   }else{
39369     pPager->eState = PAGER_READER;
39370   }
39371   return rc;
39372 }
39373
39374 /*
39375 ** If the reference count has reached zero, rollback any active
39376 ** transaction and unlock the pager.
39377 **
39378 ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
39379 ** the rollback journal, the unlock is not performed and there is
39380 ** nothing to rollback, so this routine is a no-op.
39381 */ 
39382 static void pagerUnlockIfUnused(Pager *pPager){
39383   if( (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
39384     pagerUnlockAndRollback(pPager);
39385   }
39386 }
39387
39388 /*
39389 ** Acquire a reference to page number pgno in pager pPager (a page
39390 ** reference has type DbPage*). If the requested reference is 
39391 ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
39392 **
39393 ** If the requested page is already in the cache, it is returned. 
39394 ** Otherwise, a new page object is allocated and populated with data
39395 ** read from the database file. In some cases, the pcache module may
39396 ** choose not to allocate a new page object and may reuse an existing
39397 ** object with no outstanding references.
39398 **
39399 ** The extra data appended to a page is always initialized to zeros the 
39400 ** first time a page is loaded into memory. If the page requested is 
39401 ** already in the cache when this function is called, then the extra
39402 ** data is left as it was when the page object was last used.
39403 **
39404 ** If the database image is smaller than the requested page or if a 
39405 ** non-zero value is passed as the noContent parameter and the 
39406 ** requested page is not already stored in the cache, then no 
39407 ** actual disk read occurs. In this case the memory image of the 
39408 ** page is initialized to all zeros. 
39409 **
39410 ** If noContent is true, it means that we do not care about the contents
39411 ** of the page. This occurs in two seperate scenarios:
39412 **
39413 **   a) When reading a free-list leaf page from the database, and
39414 **
39415 **   b) When a savepoint is being rolled back and we need to load
39416 **      a new page into the cache to be filled with the data read
39417 **      from the savepoint journal.
39418 **
39419 ** If noContent is true, then the data returned is zeroed instead of
39420 ** being read from the database. Additionally, the bits corresponding
39421 ** to pgno in Pager.pInJournal (bitvec of pages already written to the
39422 ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
39423 ** savepoints are set. This means if the page is made writable at any
39424 ** point in the future, using a call to sqlite3PagerWrite(), its contents
39425 ** will not be journaled. This saves IO.
39426 **
39427 ** The acquisition might fail for several reasons.  In all cases,
39428 ** an appropriate error code is returned and *ppPage is set to NULL.
39429 **
39430 ** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt
39431 ** to find a page in the in-memory cache first.  If the page is not already
39432 ** in memory, this routine goes to disk to read it in whereas Lookup()
39433 ** just returns 0.  This routine acquires a read-lock the first time it
39434 ** has to go to disk, and could also playback an old journal if necessary.
39435 ** Since Lookup() never goes to disk, it never has to deal with locks
39436 ** or journal files.
39437 */
39438 SQLITE_PRIVATE int sqlite3PagerAcquire(
39439   Pager *pPager,      /* The pager open on the database file */
39440   Pgno pgno,          /* Page number to fetch */
39441   DbPage **ppPage,    /* Write a pointer to the page here */
39442   int noContent       /* Do not bother reading content from disk if true */
39443 ){
39444   int rc;
39445   PgHdr *pPg;
39446
39447   assert( pPager->eState>=PAGER_READER );
39448   assert( assert_pager_state(pPager) );
39449
39450   if( pgno==0 ){
39451     return SQLITE_CORRUPT_BKPT;
39452   }
39453
39454   /* If the pager is in the error state, return an error immediately. 
39455   ** Otherwise, request the page from the PCache layer. */
39456   if( pPager->errCode!=SQLITE_OK ){
39457     rc = pPager->errCode;
39458   }else{
39459     rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, ppPage);
39460   }
39461
39462   if( rc!=SQLITE_OK ){
39463     /* Either the call to sqlite3PcacheFetch() returned an error or the
39464     ** pager was already in the error-state when this function was called.
39465     ** Set pPg to 0 and jump to the exception handler.  */
39466     pPg = 0;
39467     goto pager_acquire_err;
39468   }
39469   assert( (*ppPage)->pgno==pgno );
39470   assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 );
39471
39472   if( (*ppPage)->pPager && !noContent ){
39473     /* In this case the pcache already contains an initialized copy of
39474     ** the page. Return without further ado.  */
39475     assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
39476     PAGER_INCR(pPager->nHit);
39477     return SQLITE_OK;
39478
39479   }else{
39480     /* The pager cache has created a new page. Its content needs to 
39481     ** be initialized.  */
39482
39483     PAGER_INCR(pPager->nMiss);
39484     pPg = *ppPage;
39485     pPg->pPager = pPager;
39486
39487     /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
39488     ** number greater than this, or the unused locking-page, is requested. */
39489     if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
39490       rc = SQLITE_CORRUPT_BKPT;
39491       goto pager_acquire_err;
39492     }
39493
39494     if( MEMDB || pPager->dbSize<pgno || noContent || !isOpen(pPager->fd) ){
39495       if( pgno>pPager->mxPgno ){
39496         rc = SQLITE_FULL;
39497         goto pager_acquire_err;
39498       }
39499       if( noContent ){
39500         /* Failure to set the bits in the InJournal bit-vectors is benign.
39501         ** It merely means that we might do some extra work to journal a 
39502         ** page that does not need to be journaled.  Nevertheless, be sure 
39503         ** to test the case where a malloc error occurs while trying to set 
39504         ** a bit in a bit vector.
39505         */
39506         sqlite3BeginBenignMalloc();
39507         if( pgno<=pPager->dbOrigSize ){
39508           TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
39509           testcase( rc==SQLITE_NOMEM );
39510         }
39511         TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
39512         testcase( rc==SQLITE_NOMEM );
39513         sqlite3EndBenignMalloc();
39514       }
39515       memset(pPg->pData, 0, pPager->pageSize);
39516       IOTRACE(("ZERO %p %d\n", pPager, pgno));
39517     }else{
39518       assert( pPg->pPager==pPager );
39519       rc = readDbPage(pPg);
39520       if( rc!=SQLITE_OK ){
39521         goto pager_acquire_err;
39522       }
39523     }
39524     pager_set_pagehash(pPg);
39525   }
39526
39527   return SQLITE_OK;
39528
39529 pager_acquire_err:
39530   assert( rc!=SQLITE_OK );
39531   if( pPg ){
39532     sqlite3PcacheDrop(pPg);
39533   }
39534   pagerUnlockIfUnused(pPager);
39535
39536   *ppPage = 0;
39537   return rc;
39538 }
39539
39540 /*
39541 ** Acquire a page if it is already in the in-memory cache.  Do
39542 ** not read the page from disk.  Return a pointer to the page,
39543 ** or 0 if the page is not in cache. 
39544 **
39545 ** See also sqlite3PagerGet().  The difference between this routine
39546 ** and sqlite3PagerGet() is that _get() will go to the disk and read
39547 ** in the page if the page is not already in cache.  This routine
39548 ** returns NULL if the page is not in cache or if a disk I/O error 
39549 ** has ever happened.
39550 */
39551 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
39552   PgHdr *pPg = 0;
39553   assert( pPager!=0 );
39554   assert( pgno!=0 );
39555   assert( pPager->pPCache!=0 );
39556   assert( pPager->eState>=PAGER_READER && pPager->eState!=PAGER_ERROR );
39557   sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
39558   return pPg;
39559 }
39560
39561 /*
39562 ** Release a page reference.
39563 **
39564 ** If the number of references to the page drop to zero, then the
39565 ** page is added to the LRU list.  When all references to all pages
39566 ** are released, a rollback occurs and the lock on the database is
39567 ** removed.
39568 */
39569 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
39570   if( pPg ){
39571     Pager *pPager = pPg->pPager;
39572     sqlite3PcacheRelease(pPg);
39573     pagerUnlockIfUnused(pPager);
39574   }
39575 }
39576
39577 /*
39578 ** This function is called at the start of every write transaction.
39579 ** There must already be a RESERVED or EXCLUSIVE lock on the database 
39580 ** file when this routine is called.
39581 **
39582 ** Open the journal file for pager pPager and write a journal header
39583 ** to the start of it. If there are active savepoints, open the sub-journal
39584 ** as well. This function is only used when the journal file is being 
39585 ** opened to write a rollback log for a transaction. It is not used 
39586 ** when opening a hot journal file to roll it back.
39587 **
39588 ** If the journal file is already open (as it may be in exclusive mode),
39589 ** then this function just writes a journal header to the start of the
39590 ** already open file. 
39591 **
39592 ** Whether or not the journal file is opened by this function, the
39593 ** Pager.pInJournal bitvec structure is allocated.
39594 **
39595 ** Return SQLITE_OK if everything is successful. Otherwise, return 
39596 ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or 
39597 ** an IO error code if opening or writing the journal file fails.
39598 */
39599 static int pager_open_journal(Pager *pPager){
39600   int rc = SQLITE_OK;                        /* Return code */
39601   sqlite3_vfs * const pVfs = pPager->pVfs;   /* Local cache of vfs pointer */
39602
39603   assert( pPager->eState==PAGER_WRITER_LOCKED );
39604   assert( assert_pager_state(pPager) );
39605   assert( pPager->pInJournal==0 );
39606   
39607   /* If already in the error state, this function is a no-op.  But on
39608   ** the other hand, this routine is never called if we are already in
39609   ** an error state. */
39610   if( NEVER(pPager->errCode) ) return pPager->errCode;
39611
39612   if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
39613     pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
39614     if( pPager->pInJournal==0 ){
39615       return SQLITE_NOMEM;
39616     }
39617   
39618     /* Open the journal file if it is not already open. */
39619     if( !isOpen(pPager->jfd) ){
39620       if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
39621         sqlite3MemJournalOpen(pPager->jfd);
39622       }else{
39623         const int flags =                   /* VFS flags to open journal file */
39624           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
39625           (pPager->tempFile ? 
39626             (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
39627             (SQLITE_OPEN_MAIN_JOURNAL)
39628           );
39629   #ifdef SQLITE_ENABLE_ATOMIC_WRITE
39630         rc = sqlite3JournalOpen(
39631             pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
39632         );
39633   #else
39634         rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
39635   #endif
39636       }
39637       assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
39638     }
39639   
39640   
39641     /* Write the first journal header to the journal file and open 
39642     ** the sub-journal if necessary.
39643     */
39644     if( rc==SQLITE_OK ){
39645       /* TODO: Check if all of these are really required. */
39646       pPager->nRec = 0;
39647       pPager->journalOff = 0;
39648       pPager->setMaster = 0;
39649       pPager->journalHdr = 0;
39650       rc = writeJournalHdr(pPager);
39651     }
39652   }
39653
39654   if( rc!=SQLITE_OK ){
39655     sqlite3BitvecDestroy(pPager->pInJournal);
39656     pPager->pInJournal = 0;
39657   }else{
39658     assert( pPager->eState==PAGER_WRITER_LOCKED );
39659     pPager->eState = PAGER_WRITER_CACHEMOD;
39660   }
39661
39662   return rc;
39663 }
39664
39665 /*
39666 ** Begin a write-transaction on the specified pager object. If a 
39667 ** write-transaction has already been opened, this function is a no-op.
39668 **
39669 ** If the exFlag argument is false, then acquire at least a RESERVED
39670 ** lock on the database file. If exFlag is true, then acquire at least
39671 ** an EXCLUSIVE lock. If such a lock is already held, no locking 
39672 ** functions need be called.
39673 **
39674 ** If the subjInMemory argument is non-zero, then any sub-journal opened
39675 ** within this transaction will be opened as an in-memory file. This
39676 ** has no effect if the sub-journal is already opened (as it may be when
39677 ** running in exclusive mode) or if the transaction does not require a
39678 ** sub-journal. If the subjInMemory argument is zero, then any required
39679 ** sub-journal is implemented in-memory if pPager is an in-memory database, 
39680 ** or using a temporary file otherwise.
39681 */
39682 SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
39683   int rc = SQLITE_OK;
39684
39685   if( pPager->errCode ) return pPager->errCode;
39686   assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
39687   pPager->subjInMemory = (u8)subjInMemory;
39688
39689   if( ALWAYS(pPager->eState==PAGER_READER) ){
39690     assert( pPager->pInJournal==0 );
39691
39692     if( pagerUseWal(pPager) ){
39693       /* If the pager is configured to use locking_mode=exclusive, and an
39694       ** exclusive lock on the database is not already held, obtain it now.
39695       */
39696       if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
39697         rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
39698         if( rc!=SQLITE_OK ){
39699           return rc;
39700         }
39701         sqlite3WalExclusiveMode(pPager->pWal, 1);
39702       }
39703
39704       /* Grab the write lock on the log file. If successful, upgrade to
39705       ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
39706       ** The busy-handler is not invoked if another connection already
39707       ** holds the write-lock. If possible, the upper layer will call it.
39708       */
39709       rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
39710     }else{
39711       /* Obtain a RESERVED lock on the database file. If the exFlag parameter
39712       ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
39713       ** busy-handler callback can be used when upgrading to the EXCLUSIVE
39714       ** lock, but not when obtaining the RESERVED lock.
39715       */
39716       rc = pagerLockDb(pPager, RESERVED_LOCK);
39717       if( rc==SQLITE_OK && exFlag ){
39718         rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
39719       }
39720     }
39721
39722     if( rc==SQLITE_OK ){
39723       /* Change to WRITER_LOCKED state.
39724       **
39725       ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
39726       ** when it has an open transaction, but never to DBMOD or FINISHED.
39727       ** This is because in those states the code to roll back savepoint 
39728       ** transactions may copy data from the sub-journal into the database 
39729       ** file as well as into the page cache. Which would be incorrect in 
39730       ** WAL mode.
39731       */
39732       pPager->eState = PAGER_WRITER_LOCKED;
39733       pPager->dbHintSize = pPager->dbSize;
39734       pPager->dbFileSize = pPager->dbSize;
39735       pPager->dbOrigSize = pPager->dbSize;
39736       pPager->journalOff = 0;
39737     }
39738
39739     assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
39740     assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
39741     assert( assert_pager_state(pPager) );
39742   }
39743
39744   PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
39745   return rc;
39746 }
39747
39748 /*
39749 ** Mark a single data page as writeable. The page is written into the 
39750 ** main journal or sub-journal as required. If the page is written into
39751 ** one of the journals, the corresponding bit is set in the 
39752 ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
39753 ** of any open savepoints as appropriate.
39754 */
39755 static int pager_write(PgHdr *pPg){
39756   void *pData = pPg->pData;
39757   Pager *pPager = pPg->pPager;
39758   int rc = SQLITE_OK;
39759
39760   /* This routine is not called unless a write-transaction has already 
39761   ** been started. The journal file may or may not be open at this point.
39762   ** It is never called in the ERROR state.
39763   */
39764   assert( pPager->eState==PAGER_WRITER_LOCKED
39765        || pPager->eState==PAGER_WRITER_CACHEMOD
39766        || pPager->eState==PAGER_WRITER_DBMOD
39767   );
39768   assert( assert_pager_state(pPager) );
39769
39770   /* If an error has been previously detected, report the same error
39771   ** again. This should not happen, but the check provides robustness. */
39772   if( NEVER(pPager->errCode) )  return pPager->errCode;
39773
39774   /* Higher-level routines never call this function if database is not
39775   ** writable.  But check anyway, just for robustness. */
39776   if( NEVER(pPager->readOnly) ) return SQLITE_PERM;
39777
39778   CHECK_PAGE(pPg);
39779
39780   /* The journal file needs to be opened. Higher level routines have already
39781   ** obtained the necessary locks to begin the write-transaction, but the
39782   ** rollback journal might not yet be open. Open it now if this is the case.
39783   **
39784   ** This is done before calling sqlite3PcacheMakeDirty() on the page. 
39785   ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
39786   ** an error might occur and the pager would end up in WRITER_LOCKED state
39787   ** with pages marked as dirty in the cache.
39788   */
39789   if( pPager->eState==PAGER_WRITER_LOCKED ){
39790     rc = pager_open_journal(pPager);
39791     if( rc!=SQLITE_OK ) return rc;
39792   }
39793   assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
39794   assert( assert_pager_state(pPager) );
39795
39796   /* Mark the page as dirty.  If the page has already been written
39797   ** to the journal then we can return right away.
39798   */
39799   sqlite3PcacheMakeDirty(pPg);
39800   if( pageInJournal(pPg) && !subjRequiresPage(pPg) ){
39801     assert( !pagerUseWal(pPager) );
39802   }else{
39803   
39804     /* The transaction journal now exists and we have a RESERVED or an
39805     ** EXCLUSIVE lock on the main database file.  Write the current page to
39806     ** the transaction journal if it is not there already.
39807     */
39808     if( !pageInJournal(pPg) && !pagerUseWal(pPager) ){
39809       assert( pagerUseWal(pPager)==0 );
39810       if( pPg->pgno<=pPager->dbOrigSize && isOpen(pPager->jfd) ){
39811         u32 cksum;
39812         char *pData2;
39813         i64 iOff = pPager->journalOff;
39814
39815         /* We should never write to the journal file the page that
39816         ** contains the database locks.  The following assert verifies
39817         ** that we do not. */
39818         assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
39819
39820         assert( pPager->journalHdr<=pPager->journalOff );
39821         CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
39822         cksum = pager_cksum(pPager, (u8*)pData2);
39823
39824         /* Even if an IO or diskfull error occurs while journalling the
39825         ** page in the block above, set the need-sync flag for the page.
39826         ** Otherwise, when the transaction is rolled back, the logic in
39827         ** playback_one_page() will think that the page needs to be restored
39828         ** in the database file. And if an IO error occurs while doing so,
39829         ** then corruption may follow.
39830         */
39831         pPg->flags |= PGHDR_NEED_SYNC;
39832
39833         rc = write32bits(pPager->jfd, iOff, pPg->pgno);
39834         if( rc!=SQLITE_OK ) return rc;
39835         rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
39836         if( rc!=SQLITE_OK ) return rc;
39837         rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
39838         if( rc!=SQLITE_OK ) return rc;
39839
39840         IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno, 
39841                  pPager->journalOff, pPager->pageSize));
39842         PAGER_INCR(sqlite3_pager_writej_count);
39843         PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
39844              PAGERID(pPager), pPg->pgno, 
39845              ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
39846
39847         pPager->journalOff += 8 + pPager->pageSize;
39848         pPager->nRec++;
39849         assert( pPager->pInJournal!=0 );
39850         rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
39851         testcase( rc==SQLITE_NOMEM );
39852         assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
39853         rc |= addToSavepointBitvecs(pPager, pPg->pgno);
39854         if( rc!=SQLITE_OK ){
39855           assert( rc==SQLITE_NOMEM );
39856           return rc;
39857         }
39858       }else{
39859         if( pPager->eState!=PAGER_WRITER_DBMOD ){
39860           pPg->flags |= PGHDR_NEED_SYNC;
39861         }
39862         PAGERTRACE(("APPEND %d page %d needSync=%d\n",
39863                 PAGERID(pPager), pPg->pgno,
39864                ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
39865       }
39866     }
39867   
39868     /* If the statement journal is open and the page is not in it,
39869     ** then write the current page to the statement journal.  Note that
39870     ** the statement journal format differs from the standard journal format
39871     ** in that it omits the checksums and the header.
39872     */
39873     if( subjRequiresPage(pPg) ){
39874       rc = subjournalPage(pPg);
39875     }
39876   }
39877
39878   /* Update the database size and return.
39879   */
39880   if( pPager->dbSize<pPg->pgno ){
39881     pPager->dbSize = pPg->pgno;
39882   }
39883   return rc;
39884 }
39885
39886 /*
39887 ** Mark a data page as writeable. This routine must be called before 
39888 ** making changes to a page. The caller must check the return value 
39889 ** of this function and be careful not to change any page data unless 
39890 ** this routine returns SQLITE_OK.
39891 **
39892 ** The difference between this function and pager_write() is that this
39893 ** function also deals with the special case where 2 or more pages
39894 ** fit on a single disk sector. In this case all co-resident pages
39895 ** must have been written to the journal file before returning.
39896 **
39897 ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
39898 ** as appropriate. Otherwise, SQLITE_OK.
39899 */
39900 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *pDbPage){
39901   int rc = SQLITE_OK;
39902
39903   PgHdr *pPg = pDbPage;
39904   Pager *pPager = pPg->pPager;
39905   Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
39906
39907   assert( pPager->eState>=PAGER_WRITER_LOCKED );
39908   assert( pPager->eState!=PAGER_ERROR );
39909   assert( assert_pager_state(pPager) );
39910
39911   if( nPagePerSector>1 ){
39912     Pgno nPageCount;          /* Total number of pages in database file */
39913     Pgno pg1;                 /* First page of the sector pPg is located on. */
39914     int nPage = 0;            /* Number of pages starting at pg1 to journal */
39915     int ii;                   /* Loop counter */
39916     int needSync = 0;         /* True if any page has PGHDR_NEED_SYNC */
39917
39918     /* Set the doNotSyncSpill flag to 1. This is because we cannot allow
39919     ** a journal header to be written between the pages journaled by
39920     ** this function.
39921     */
39922     assert( !MEMDB );
39923     assert( pPager->doNotSyncSpill==0 );
39924     pPager->doNotSyncSpill++;
39925
39926     /* This trick assumes that both the page-size and sector-size are
39927     ** an integer power of 2. It sets variable pg1 to the identifier
39928     ** of the first page of the sector pPg is located on.
39929     */
39930     pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
39931
39932     nPageCount = pPager->dbSize;
39933     if( pPg->pgno>nPageCount ){
39934       nPage = (pPg->pgno - pg1)+1;
39935     }else if( (pg1+nPagePerSector-1)>nPageCount ){
39936       nPage = nPageCount+1-pg1;
39937     }else{
39938       nPage = nPagePerSector;
39939     }
39940     assert(nPage>0);
39941     assert(pg1<=pPg->pgno);
39942     assert((pg1+nPage)>pPg->pgno);
39943
39944     for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
39945       Pgno pg = pg1+ii;
39946       PgHdr *pPage;
39947       if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
39948         if( pg!=PAGER_MJ_PGNO(pPager) ){
39949           rc = sqlite3PagerGet(pPager, pg, &pPage);
39950           if( rc==SQLITE_OK ){
39951             rc = pager_write(pPage);
39952             if( pPage->flags&PGHDR_NEED_SYNC ){
39953               needSync = 1;
39954             }
39955             sqlite3PagerUnref(pPage);
39956           }
39957         }
39958       }else if( (pPage = pager_lookup(pPager, pg))!=0 ){
39959         if( pPage->flags&PGHDR_NEED_SYNC ){
39960           needSync = 1;
39961         }
39962         sqlite3PagerUnref(pPage);
39963       }
39964     }
39965
39966     /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages 
39967     ** starting at pg1, then it needs to be set for all of them. Because
39968     ** writing to any of these nPage pages may damage the others, the
39969     ** journal file must contain sync()ed copies of all of them
39970     ** before any of them can be written out to the database file.
39971     */
39972     if( rc==SQLITE_OK && needSync ){
39973       assert( !MEMDB );
39974       for(ii=0; ii<nPage; ii++){
39975         PgHdr *pPage = pager_lookup(pPager, pg1+ii);
39976         if( pPage ){
39977           pPage->flags |= PGHDR_NEED_SYNC;
39978           sqlite3PagerUnref(pPage);
39979         }
39980       }
39981     }
39982
39983     assert( pPager->doNotSyncSpill==1 );
39984     pPager->doNotSyncSpill--;
39985   }else{
39986     rc = pager_write(pDbPage);
39987   }
39988   return rc;
39989 }
39990
39991 /*
39992 ** Return TRUE if the page given in the argument was previously passed
39993 ** to sqlite3PagerWrite().  In other words, return TRUE if it is ok
39994 ** to change the content of the page.
39995 */
39996 #ifndef NDEBUG
39997 SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
39998   return pPg->flags&PGHDR_DIRTY;
39999 }
40000 #endif
40001
40002 /*
40003 ** A call to this routine tells the pager that it is not necessary to
40004 ** write the information on page pPg back to the disk, even though
40005 ** that page might be marked as dirty.  This happens, for example, when
40006 ** the page has been added as a leaf of the freelist and so its
40007 ** content no longer matters.
40008 **
40009 ** The overlying software layer calls this routine when all of the data
40010 ** on the given page is unused. The pager marks the page as clean so
40011 ** that it does not get written to disk.
40012 **
40013 ** Tests show that this optimization can quadruple the speed of large 
40014 ** DELETE operations.
40015 */
40016 SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
40017   Pager *pPager = pPg->pPager;
40018   if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
40019     PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
40020     IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
40021     pPg->flags |= PGHDR_DONT_WRITE;
40022     pager_set_pagehash(pPg);
40023   }
40024 }
40025
40026 /*
40027 ** This routine is called to increment the value of the database file 
40028 ** change-counter, stored as a 4-byte big-endian integer starting at 
40029 ** byte offset 24 of the pager file.
40030 **
40031 ** If the isDirectMode flag is zero, then this is done by calling 
40032 ** sqlite3PagerWrite() on page 1, then modifying the contents of the
40033 ** page data. In this case the file will be updated when the current
40034 ** transaction is committed.
40035 **
40036 ** The isDirectMode flag may only be non-zero if the library was compiled
40037 ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
40038 ** if isDirect is non-zero, then the database file is updated directly
40039 ** by writing an updated version of page 1 using a call to the 
40040 ** sqlite3OsWrite() function.
40041 */
40042 static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
40043   int rc = SQLITE_OK;
40044
40045   assert( pPager->eState==PAGER_WRITER_CACHEMOD
40046        || pPager->eState==PAGER_WRITER_DBMOD
40047   );
40048   assert( assert_pager_state(pPager) );
40049
40050   /* Declare and initialize constant integer 'isDirect'. If the
40051   ** atomic-write optimization is enabled in this build, then isDirect
40052   ** is initialized to the value passed as the isDirectMode parameter
40053   ** to this function. Otherwise, it is always set to zero.
40054   **
40055   ** The idea is that if the atomic-write optimization is not
40056   ** enabled at compile time, the compiler can omit the tests of
40057   ** 'isDirect' below, as well as the block enclosed in the
40058   ** "if( isDirect )" condition.
40059   */
40060 #ifndef SQLITE_ENABLE_ATOMIC_WRITE
40061 # define DIRECT_MODE 0
40062   assert( isDirectMode==0 );
40063   UNUSED_PARAMETER(isDirectMode);
40064 #else
40065 # define DIRECT_MODE isDirectMode
40066 #endif
40067
40068   if( !pPager->changeCountDone && pPager->dbSize>0 ){
40069     PgHdr *pPgHdr;                /* Reference to page 1 */
40070     u32 change_counter;           /* Initial value of change-counter field */
40071
40072     assert( !pPager->tempFile && isOpen(pPager->fd) );
40073
40074     /* Open page 1 of the file for writing. */
40075     rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
40076     assert( pPgHdr==0 || rc==SQLITE_OK );
40077
40078     /* If page one was fetched successfully, and this function is not
40079     ** operating in direct-mode, make page 1 writable.  When not in 
40080     ** direct mode, page 1 is always held in cache and hence the PagerGet()
40081     ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
40082     */
40083     if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
40084       rc = sqlite3PagerWrite(pPgHdr);
40085     }
40086
40087     if( rc==SQLITE_OK ){
40088       /* Increment the value just read and write it back to byte 24. */
40089       change_counter = sqlite3Get4byte((u8*)pPager->dbFileVers);
40090       change_counter++;
40091       put32bits(((char*)pPgHdr->pData)+24, change_counter);
40092
40093       /* Also store the SQLite version number in bytes 96..99 and in
40094       ** bytes 92..95 store the change counter for which the version number
40095       ** is valid. */
40096       put32bits(((char*)pPgHdr->pData)+92, change_counter);
40097       put32bits(((char*)pPgHdr->pData)+96, SQLITE_VERSION_NUMBER);
40098
40099       /* If running in direct mode, write the contents of page 1 to the file. */
40100       if( DIRECT_MODE ){
40101         const void *zBuf;
40102         assert( pPager->dbFileSize>0 );
40103         CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM, zBuf);
40104         if( rc==SQLITE_OK ){
40105           rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
40106         }
40107         if( rc==SQLITE_OK ){
40108           pPager->changeCountDone = 1;
40109         }
40110       }else{
40111         pPager->changeCountDone = 1;
40112       }
40113     }
40114
40115     /* Release the page reference. */
40116     sqlite3PagerUnref(pPgHdr);
40117   }
40118   return rc;
40119 }
40120
40121 /*
40122 ** Sync the pager file to disk. This is a no-op for in-memory files
40123 ** or pages with the Pager.noSync flag set.
40124 **
40125 ** If successful, or called on a pager for which it is a no-op, this
40126 ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
40127 */
40128 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager){
40129   int rc;                              /* Return code */
40130   assert( !MEMDB );
40131   if( pPager->noSync ){
40132     rc = SQLITE_OK;
40133   }else{
40134     rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
40135   }
40136   return rc;
40137 }
40138
40139 /*
40140 ** This function may only be called while a write-transaction is active in
40141 ** rollback. If the connection is in WAL mode, this call is a no-op. 
40142 ** Otherwise, if the connection does not already have an EXCLUSIVE lock on 
40143 ** the database file, an attempt is made to obtain one.
40144 **
40145 ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
40146 ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
40147 ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is 
40148 ** returned.
40149 */
40150 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
40151   int rc = SQLITE_OK;
40152   assert( pPager->eState==PAGER_WRITER_CACHEMOD 
40153        || pPager->eState==PAGER_WRITER_DBMOD 
40154        || pPager->eState==PAGER_WRITER_LOCKED 
40155   );
40156   assert( assert_pager_state(pPager) );
40157   if( 0==pagerUseWal(pPager) ){
40158     rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
40159   }
40160   return rc;
40161 }
40162
40163 /*
40164 ** Sync the database file for the pager pPager. zMaster points to the name
40165 ** of a master journal file that should be written into the individual
40166 ** journal file. zMaster may be NULL, which is interpreted as no master
40167 ** journal (a single database transaction).
40168 **
40169 ** This routine ensures that:
40170 **
40171 **   * The database file change-counter is updated,
40172 **   * the journal is synced (unless the atomic-write optimization is used),
40173 **   * all dirty pages are written to the database file, 
40174 **   * the database file is truncated (if required), and
40175 **   * the database file synced. 
40176 **
40177 ** The only thing that remains to commit the transaction is to finalize 
40178 ** (delete, truncate or zero the first part of) the journal file (or 
40179 ** delete the master journal file if specified).
40180 **
40181 ** Note that if zMaster==NULL, this does not overwrite a previous value
40182 ** passed to an sqlite3PagerCommitPhaseOne() call.
40183 **
40184 ** If the final parameter - noSync - is true, then the database file itself
40185 ** is not synced. The caller must call sqlite3PagerSync() directly to
40186 ** sync the database file before calling CommitPhaseTwo() to delete the
40187 ** journal file in this case.
40188 */
40189 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
40190   Pager *pPager,                  /* Pager object */
40191   const char *zMaster,            /* If not NULL, the master journal name */
40192   int noSync                      /* True to omit the xSync on the db file */
40193 ){
40194   int rc = SQLITE_OK;             /* Return code */
40195
40196   assert( pPager->eState==PAGER_WRITER_LOCKED
40197        || pPager->eState==PAGER_WRITER_CACHEMOD
40198        || pPager->eState==PAGER_WRITER_DBMOD
40199        || pPager->eState==PAGER_ERROR
40200   );
40201   assert( assert_pager_state(pPager) );
40202
40203   /* If a prior error occurred, report that error again. */
40204   if( NEVER(pPager->errCode) ) return pPager->errCode;
40205
40206   PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n", 
40207       pPager->zFilename, zMaster, pPager->dbSize));
40208
40209   /* If no database changes have been made, return early. */
40210   if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
40211
40212   if( MEMDB ){
40213     /* If this is an in-memory db, or no pages have been written to, or this
40214     ** function has already been called, it is mostly a no-op.  However, any
40215     ** backup in progress needs to be restarted.
40216     */
40217     sqlite3BackupRestart(pPager->pBackup);
40218   }else{
40219     if( pagerUseWal(pPager) ){
40220       PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
40221       if( pList ){
40222         rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1, 
40223             (pPager->fullSync ? pPager->sync_flags : 0)
40224         );
40225       }
40226       if( rc==SQLITE_OK ){
40227         sqlite3PcacheCleanAll(pPager->pPCache);
40228       }
40229     }else{
40230       /* The following block updates the change-counter. Exactly how it
40231       ** does this depends on whether or not the atomic-update optimization
40232       ** was enabled at compile time, and if this transaction meets the 
40233       ** runtime criteria to use the operation: 
40234       **
40235       **    * The file-system supports the atomic-write property for
40236       **      blocks of size page-size, and 
40237       **    * This commit is not part of a multi-file transaction, and
40238       **    * Exactly one page has been modified and store in the journal file.
40239       **
40240       ** If the optimization was not enabled at compile time, then the
40241       ** pager_incr_changecounter() function is called to update the change
40242       ** counter in 'indirect-mode'. If the optimization is compiled in but
40243       ** is not applicable to this transaction, call sqlite3JournalCreate()
40244       ** to make sure the journal file has actually been created, then call
40245       ** pager_incr_changecounter() to update the change-counter in indirect
40246       ** mode. 
40247       **
40248       ** Otherwise, if the optimization is both enabled and applicable,
40249       ** then call pager_incr_changecounter() to update the change-counter
40250       ** in 'direct' mode. In this case the journal file will never be
40251       ** created for this transaction.
40252       */
40253   #ifdef SQLITE_ENABLE_ATOMIC_WRITE
40254       PgHdr *pPg;
40255       assert( isOpen(pPager->jfd) 
40256            || pPager->journalMode==PAGER_JOURNALMODE_OFF 
40257            || pPager->journalMode==PAGER_JOURNALMODE_WAL 
40258       );
40259       if( !zMaster && isOpen(pPager->jfd) 
40260        && pPager->journalOff==jrnlBufferSize(pPager) 
40261        && pPager->dbSize>=pPager->dbOrigSize
40262        && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
40263       ){
40264         /* Update the db file change counter via the direct-write method. The 
40265         ** following call will modify the in-memory representation of page 1 
40266         ** to include the updated change counter and then write page 1 
40267         ** directly to the database file. Because of the atomic-write 
40268         ** property of the host file-system, this is safe.
40269         */
40270         rc = pager_incr_changecounter(pPager, 1);
40271       }else{
40272         rc = sqlite3JournalCreate(pPager->jfd);
40273         if( rc==SQLITE_OK ){
40274           rc = pager_incr_changecounter(pPager, 0);
40275         }
40276       }
40277   #else
40278       rc = pager_incr_changecounter(pPager, 0);
40279   #endif
40280       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
40281   
40282       /* If this transaction has made the database smaller, then all pages
40283       ** being discarded by the truncation must be written to the journal
40284       ** file. This can only happen in auto-vacuum mode.
40285       **
40286       ** Before reading the pages with page numbers larger than the 
40287       ** current value of Pager.dbSize, set dbSize back to the value
40288       ** that it took at the start of the transaction. Otherwise, the
40289       ** calls to sqlite3PagerGet() return zeroed pages instead of 
40290       ** reading data from the database file.
40291       */
40292   #ifndef SQLITE_OMIT_AUTOVACUUM
40293       if( pPager->dbSize<pPager->dbOrigSize 
40294        && pPager->journalMode!=PAGER_JOURNALMODE_OFF
40295       ){
40296         Pgno i;                                   /* Iterator variable */
40297         const Pgno iSkip = PAGER_MJ_PGNO(pPager); /* Pending lock page */
40298         const Pgno dbSize = pPager->dbSize;       /* Database image size */ 
40299         pPager->dbSize = pPager->dbOrigSize;
40300         for( i=dbSize+1; i<=pPager->dbOrigSize; i++ ){
40301           if( !sqlite3BitvecTest(pPager->pInJournal, i) && i!=iSkip ){
40302             PgHdr *pPage;             /* Page to journal */
40303             rc = sqlite3PagerGet(pPager, i, &pPage);
40304             if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
40305             rc = sqlite3PagerWrite(pPage);
40306             sqlite3PagerUnref(pPage);
40307             if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
40308           }
40309         }
40310         pPager->dbSize = dbSize;
40311       } 
40312   #endif
40313   
40314       /* Write the master journal name into the journal file. If a master 
40315       ** journal file name has already been written to the journal file, 
40316       ** or if zMaster is NULL (no master journal), then this call is a no-op.
40317       */
40318       rc = writeMasterJournal(pPager, zMaster);
40319       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
40320   
40321       /* Sync the journal file and write all dirty pages to the database.
40322       ** If the atomic-update optimization is being used, this sync will not 
40323       ** create the journal file or perform any real IO.
40324       **
40325       ** Because the change-counter page was just modified, unless the
40326       ** atomic-update optimization is used it is almost certain that the
40327       ** journal requires a sync here. However, in locking_mode=exclusive
40328       ** on a system under memory pressure it is just possible that this is 
40329       ** not the case. In this case it is likely enough that the redundant
40330       ** xSync() call will be changed to a no-op by the OS anyhow. 
40331       */
40332       rc = syncJournal(pPager, 0);
40333       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
40334   
40335       rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
40336       if( rc!=SQLITE_OK ){
40337         assert( rc!=SQLITE_IOERR_BLOCKED );
40338         goto commit_phase_one_exit;
40339       }
40340       sqlite3PcacheCleanAll(pPager->pPCache);
40341   
40342       /* If the file on disk is not the same size as the database image,
40343       ** then use pager_truncate to grow or shrink the file here.
40344       */
40345       if( pPager->dbSize!=pPager->dbFileSize ){
40346         Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
40347         assert( pPager->eState==PAGER_WRITER_DBMOD );
40348         rc = pager_truncate(pPager, nNew);
40349         if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
40350       }
40351   
40352       /* Finally, sync the database file. */
40353       if( !pPager->noSync && !noSync ){
40354         rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
40355       }
40356       IOTRACE(("DBSYNC %p\n", pPager))
40357     }
40358   }
40359
40360 commit_phase_one_exit:
40361   if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
40362     pPager->eState = PAGER_WRITER_FINISHED;
40363   }
40364   return rc;
40365 }
40366
40367
40368 /*
40369 ** When this function is called, the database file has been completely
40370 ** updated to reflect the changes made by the current transaction and
40371 ** synced to disk. The journal file still exists in the file-system 
40372 ** though, and if a failure occurs at this point it will eventually
40373 ** be used as a hot-journal and the current transaction rolled back.
40374 **
40375 ** This function finalizes the journal file, either by deleting, 
40376 ** truncating or partially zeroing it, so that it cannot be used 
40377 ** for hot-journal rollback. Once this is done the transaction is
40378 ** irrevocably committed.
40379 **
40380 ** If an error occurs, an IO error code is returned and the pager
40381 ** moves into the error state. Otherwise, SQLITE_OK is returned.
40382 */
40383 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
40384   int rc = SQLITE_OK;                  /* Return code */
40385
40386   /* This routine should not be called if a prior error has occurred.
40387   ** But if (due to a coding error elsewhere in the system) it does get
40388   ** called, just return the same error code without doing anything. */
40389   if( NEVER(pPager->errCode) ) return pPager->errCode;
40390
40391   assert( pPager->eState==PAGER_WRITER_LOCKED
40392        || pPager->eState==PAGER_WRITER_FINISHED
40393        || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
40394   );
40395   assert( assert_pager_state(pPager) );
40396
40397   /* An optimization. If the database was not actually modified during
40398   ** this transaction, the pager is running in exclusive-mode and is
40399   ** using persistent journals, then this function is a no-op.
40400   **
40401   ** The start of the journal file currently contains a single journal 
40402   ** header with the nRec field set to 0. If such a journal is used as
40403   ** a hot-journal during hot-journal rollback, 0 changes will be made
40404   ** to the database file. So there is no need to zero the journal 
40405   ** header. Since the pager is in exclusive mode, there is no need
40406   ** to drop any locks either.
40407   */
40408   if( pPager->eState==PAGER_WRITER_LOCKED 
40409    && pPager->exclusiveMode 
40410    && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
40411   ){
40412     assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
40413     pPager->eState = PAGER_READER;
40414     return SQLITE_OK;
40415   }
40416
40417   PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
40418   rc = pager_end_transaction(pPager, pPager->setMaster);
40419   return pager_error(pPager, rc);
40420 }
40421
40422 /*
40423 ** If a write transaction is open, then all changes made within the 
40424 ** transaction are reverted and the current write-transaction is closed.
40425 ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
40426 ** state if an error occurs.
40427 **
40428 ** If the pager is already in PAGER_ERROR state when this function is called,
40429 ** it returns Pager.errCode immediately. No work is performed in this case.
40430 **
40431 ** Otherwise, in rollback mode, this function performs two functions:
40432 **
40433 **   1) It rolls back the journal file, restoring all database file and 
40434 **      in-memory cache pages to the state they were in when the transaction
40435 **      was opened, and
40436 **
40437 **   2) It finalizes the journal file, so that it is not used for hot
40438 **      rollback at any point in the future.
40439 **
40440 ** Finalization of the journal file (task 2) is only performed if the 
40441 ** rollback is successful.
40442 **
40443 ** In WAL mode, all cache-entries containing data modified within the
40444 ** current transaction are either expelled from the cache or reverted to
40445 ** their pre-transaction state by re-reading data from the database or
40446 ** WAL files. The WAL transaction is then closed.
40447 */
40448 SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
40449   int rc = SQLITE_OK;                  /* Return code */
40450   PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
40451
40452   /* PagerRollback() is a no-op if called in READER or OPEN state. If
40453   ** the pager is already in the ERROR state, the rollback is not 
40454   ** attempted here. Instead, the error code is returned to the caller.
40455   */
40456   assert( assert_pager_state(pPager) );
40457   if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
40458   if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
40459
40460   if( pagerUseWal(pPager) ){
40461     int rc2;
40462     rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
40463     rc2 = pager_end_transaction(pPager, pPager->setMaster);
40464     if( rc==SQLITE_OK ) rc = rc2;
40465   }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
40466     rc = pager_end_transaction(pPager, 0);
40467   }else{
40468     rc = pager_playback(pPager, 0);
40469   }
40470
40471   assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
40472   assert( rc==SQLITE_OK || rc==SQLITE_FULL || (rc&0xFF)==SQLITE_IOERR );
40473
40474   /* If an error occurs during a ROLLBACK, we can no longer trust the pager
40475   ** cache. So call pager_error() on the way out to make any error persistent.
40476   */
40477   return pager_error(pPager, rc);
40478 }
40479
40480 /*
40481 ** Return TRUE if the database file is opened read-only.  Return FALSE
40482 ** if the database is (in theory) writable.
40483 */
40484 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
40485   return pPager->readOnly;
40486 }
40487
40488 /*
40489 ** Return the number of references to the pager.
40490 */
40491 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
40492   return sqlite3PcacheRefCount(pPager->pPCache);
40493 }
40494
40495 /*
40496 ** Return the approximate number of bytes of memory currently
40497 ** used by the pager and its associated cache.
40498 */
40499 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
40500   int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
40501                                      + 5*sizeof(void*);
40502   return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
40503            + sqlite3MallocSize(pPager)
40504            + pPager->pageSize;
40505 }
40506
40507 /*
40508 ** Return the number of references to the specified page.
40509 */
40510 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
40511   return sqlite3PcachePageRefcount(pPage);
40512 }
40513
40514 #ifdef SQLITE_TEST
40515 /*
40516 ** This routine is used for testing and analysis only.
40517 */
40518 SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
40519   static int a[11];
40520   a[0] = sqlite3PcacheRefCount(pPager->pPCache);
40521   a[1] = sqlite3PcachePagecount(pPager->pPCache);
40522   a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
40523   a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
40524   a[4] = pPager->eState;
40525   a[5] = pPager->errCode;
40526   a[6] = pPager->nHit;
40527   a[7] = pPager->nMiss;
40528   a[8] = 0;  /* Used to be pPager->nOvfl */
40529   a[9] = pPager->nRead;
40530   a[10] = pPager->nWrite;
40531   return a;
40532 }
40533 #endif
40534
40535 /*
40536 ** Return true if this is an in-memory pager.
40537 */
40538 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
40539   return MEMDB;
40540 }
40541
40542 /*
40543 ** Check that there are at least nSavepoint savepoints open. If there are
40544 ** currently less than nSavepoints open, then open one or more savepoints
40545 ** to make up the difference. If the number of savepoints is already
40546 ** equal to nSavepoint, then this function is a no-op.
40547 **
40548 ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error 
40549 ** occurs while opening the sub-journal file, then an IO error code is
40550 ** returned. Otherwise, SQLITE_OK.
40551 */
40552 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
40553   int rc = SQLITE_OK;                       /* Return code */
40554   int nCurrent = pPager->nSavepoint;        /* Current number of savepoints */
40555
40556   assert( pPager->eState>=PAGER_WRITER_LOCKED );
40557   assert( assert_pager_state(pPager) );
40558
40559   if( nSavepoint>nCurrent && pPager->useJournal ){
40560     int ii;                                 /* Iterator variable */
40561     PagerSavepoint *aNew;                   /* New Pager.aSavepoint array */
40562
40563     /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
40564     ** if the allocation fails. Otherwise, zero the new portion in case a 
40565     ** malloc failure occurs while populating it in the for(...) loop below.
40566     */
40567     aNew = (PagerSavepoint *)sqlite3Realloc(
40568         pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
40569     );
40570     if( !aNew ){
40571       return SQLITE_NOMEM;
40572     }
40573     memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
40574     pPager->aSavepoint = aNew;
40575
40576     /* Populate the PagerSavepoint structures just allocated. */
40577     for(ii=nCurrent; ii<nSavepoint; ii++){
40578       aNew[ii].nOrig = pPager->dbSize;
40579       if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
40580         aNew[ii].iOffset = pPager->journalOff;
40581       }else{
40582         aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
40583       }
40584       aNew[ii].iSubRec = pPager->nSubRec;
40585       aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
40586       if( !aNew[ii].pInSavepoint ){
40587         return SQLITE_NOMEM;
40588       }
40589       if( pagerUseWal(pPager) ){
40590         sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
40591       }
40592       pPager->nSavepoint = ii+1;
40593     }
40594     assert( pPager->nSavepoint==nSavepoint );
40595     assertTruncateConstraint(pPager);
40596   }
40597
40598   return rc;
40599 }
40600
40601 /*
40602 ** This function is called to rollback or release (commit) a savepoint.
40603 ** The savepoint to release or rollback need not be the most recently 
40604 ** created savepoint.
40605 **
40606 ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
40607 ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
40608 ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
40609 ** that have occurred since the specified savepoint was created.
40610 **
40611 ** The savepoint to rollback or release is identified by parameter 
40612 ** iSavepoint. A value of 0 means to operate on the outermost savepoint
40613 ** (the first created). A value of (Pager.nSavepoint-1) means operate
40614 ** on the most recently created savepoint. If iSavepoint is greater than
40615 ** (Pager.nSavepoint-1), then this function is a no-op.
40616 **
40617 ** If a negative value is passed to this function, then the current
40618 ** transaction is rolled back. This is different to calling 
40619 ** sqlite3PagerRollback() because this function does not terminate
40620 ** the transaction or unlock the database, it just restores the 
40621 ** contents of the database to its original state. 
40622 **
40623 ** In any case, all savepoints with an index greater than iSavepoint 
40624 ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
40625 ** then savepoint iSavepoint is also destroyed.
40626 **
40627 ** This function may return SQLITE_NOMEM if a memory allocation fails,
40628 ** or an IO error code if an IO error occurs while rolling back a 
40629 ** savepoint. If no errors occur, SQLITE_OK is returned.
40630 */ 
40631 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
40632   int rc = pPager->errCode;       /* Return code */
40633
40634   assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
40635   assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
40636
40637   if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
40638     int ii;            /* Iterator variable */
40639     int nNew;          /* Number of remaining savepoints after this op. */
40640
40641     /* Figure out how many savepoints will still be active after this
40642     ** operation. Store this value in nNew. Then free resources associated 
40643     ** with any savepoints that are destroyed by this operation.
40644     */
40645     nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
40646     for(ii=nNew; ii<pPager->nSavepoint; ii++){
40647       sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
40648     }
40649     pPager->nSavepoint = nNew;
40650
40651     /* If this is a release of the outermost savepoint, truncate 
40652     ** the sub-journal to zero bytes in size. */
40653     if( op==SAVEPOINT_RELEASE ){
40654       if( nNew==0 && isOpen(pPager->sjfd) ){
40655         /* Only truncate if it is an in-memory sub-journal. */
40656         if( sqlite3IsMemJournal(pPager->sjfd) ){
40657           rc = sqlite3OsTruncate(pPager->sjfd, 0);
40658           assert( rc==SQLITE_OK );
40659         }
40660         pPager->nSubRec = 0;
40661       }
40662     }
40663     /* Else this is a rollback operation, playback the specified savepoint.
40664     ** If this is a temp-file, it is possible that the journal file has
40665     ** not yet been opened. In this case there have been no changes to
40666     ** the database file, so the playback operation can be skipped.
40667     */
40668     else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
40669       PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
40670       rc = pagerPlaybackSavepoint(pPager, pSavepoint);
40671       assert(rc!=SQLITE_DONE);
40672     }
40673   }
40674
40675   return rc;
40676 }
40677
40678 /*
40679 ** Return the full pathname of the database file.
40680 */
40681 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager){
40682   return pPager->zFilename;
40683 }
40684
40685 /*
40686 ** Return the VFS structure for the pager.
40687 */
40688 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
40689   return pPager->pVfs;
40690 }
40691
40692 /*
40693 ** Return the file handle for the database file associated
40694 ** with the pager.  This might return NULL if the file has
40695 ** not yet been opened.
40696 */
40697 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
40698   return pPager->fd;
40699 }
40700
40701 /*
40702 ** Return the full pathname of the journal file.
40703 */
40704 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
40705   return pPager->zJournal;
40706 }
40707
40708 /*
40709 ** Return true if fsync() calls are disabled for this pager.  Return FALSE
40710 ** if fsync()s are executed normally.
40711 */
40712 SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
40713   return pPager->noSync;
40714 }
40715
40716 #ifdef SQLITE_HAS_CODEC
40717 /*
40718 ** Set or retrieve the codec for this pager
40719 */
40720 SQLITE_PRIVATE void sqlite3PagerSetCodec(
40721   Pager *pPager,
40722   void *(*xCodec)(void*,void*,Pgno,int),
40723   void (*xCodecSizeChng)(void*,int,int),
40724   void (*xCodecFree)(void*),
40725   void *pCodec
40726 ){
40727   if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
40728   pPager->xCodec = pPager->memDb ? 0 : xCodec;
40729   pPager->xCodecSizeChng = xCodecSizeChng;
40730   pPager->xCodecFree = xCodecFree;
40731   pPager->pCodec = pCodec;
40732   pagerReportSize(pPager);
40733 }
40734 SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
40735   return pPager->pCodec;
40736 }
40737 #endif
40738
40739 #ifndef SQLITE_OMIT_AUTOVACUUM
40740 /*
40741 ** Move the page pPg to location pgno in the file.
40742 **
40743 ** There must be no references to the page previously located at
40744 ** pgno (which we call pPgOld) though that page is allowed to be
40745 ** in cache.  If the page previously located at pgno is not already
40746 ** in the rollback journal, it is not put there by by this routine.
40747 **
40748 ** References to the page pPg remain valid. Updating any
40749 ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
40750 ** allocated along with the page) is the responsibility of the caller.
40751 **
40752 ** A transaction must be active when this routine is called. It used to be
40753 ** required that a statement transaction was not active, but this restriction
40754 ** has been removed (CREATE INDEX needs to move a page when a statement
40755 ** transaction is active).
40756 **
40757 ** If the fourth argument, isCommit, is non-zero, then this page is being
40758 ** moved as part of a database reorganization just before the transaction 
40759 ** is being committed. In this case, it is guaranteed that the database page 
40760 ** pPg refers to will not be written to again within this transaction.
40761 **
40762 ** This function may return SQLITE_NOMEM or an IO error code if an error
40763 ** occurs. Otherwise, it returns SQLITE_OK.
40764 */
40765 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
40766   PgHdr *pPgOld;               /* The page being overwritten. */
40767   Pgno needSyncPgno = 0;       /* Old value of pPg->pgno, if sync is required */
40768   int rc;                      /* Return code */
40769   Pgno origPgno;               /* The original page number */
40770
40771   assert( pPg->nRef>0 );
40772   assert( pPager->eState==PAGER_WRITER_CACHEMOD
40773        || pPager->eState==PAGER_WRITER_DBMOD
40774   );
40775   assert( assert_pager_state(pPager) );
40776
40777   /* In order to be able to rollback, an in-memory database must journal
40778   ** the page we are moving from.
40779   */
40780   if( MEMDB ){
40781     rc = sqlite3PagerWrite(pPg);
40782     if( rc ) return rc;
40783   }
40784
40785   /* If the page being moved is dirty and has not been saved by the latest
40786   ** savepoint, then save the current contents of the page into the 
40787   ** sub-journal now. This is required to handle the following scenario:
40788   **
40789   **   BEGIN;
40790   **     <journal page X, then modify it in memory>
40791   **     SAVEPOINT one;
40792   **       <Move page X to location Y>
40793   **     ROLLBACK TO one;
40794   **
40795   ** If page X were not written to the sub-journal here, it would not
40796   ** be possible to restore its contents when the "ROLLBACK TO one"
40797   ** statement were is processed.
40798   **
40799   ** subjournalPage() may need to allocate space to store pPg->pgno into
40800   ** one or more savepoint bitvecs. This is the reason this function
40801   ** may return SQLITE_NOMEM.
40802   */
40803   if( pPg->flags&PGHDR_DIRTY
40804    && subjRequiresPage(pPg)
40805    && SQLITE_OK!=(rc = subjournalPage(pPg))
40806   ){
40807     return rc;
40808   }
40809
40810   PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n", 
40811       PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
40812   IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
40813
40814   /* If the journal needs to be sync()ed before page pPg->pgno can
40815   ** be written to, store pPg->pgno in local variable needSyncPgno.
40816   **
40817   ** If the isCommit flag is set, there is no need to remember that
40818   ** the journal needs to be sync()ed before database page pPg->pgno 
40819   ** can be written to. The caller has already promised not to write to it.
40820   */
40821   if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
40822     needSyncPgno = pPg->pgno;
40823     assert( pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
40824     assert( pPg->flags&PGHDR_DIRTY );
40825   }
40826
40827   /* If the cache contains a page with page-number pgno, remove it
40828   ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for 
40829   ** page pgno before the 'move' operation, it needs to be retained 
40830   ** for the page moved there.
40831   */
40832   pPg->flags &= ~PGHDR_NEED_SYNC;
40833   pPgOld = pager_lookup(pPager, pgno);
40834   assert( !pPgOld || pPgOld->nRef==1 );
40835   if( pPgOld ){
40836     pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
40837     if( MEMDB ){
40838       /* Do not discard pages from an in-memory database since we might
40839       ** need to rollback later.  Just move the page out of the way. */
40840       sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
40841     }else{
40842       sqlite3PcacheDrop(pPgOld);
40843     }
40844   }
40845
40846   origPgno = pPg->pgno;
40847   sqlite3PcacheMove(pPg, pgno);
40848   sqlite3PcacheMakeDirty(pPg);
40849
40850   /* For an in-memory database, make sure the original page continues
40851   ** to exist, in case the transaction needs to roll back.  Use pPgOld
40852   ** as the original page since it has already been allocated.
40853   */
40854   if( MEMDB ){
40855     assert( pPgOld );
40856     sqlite3PcacheMove(pPgOld, origPgno);
40857     sqlite3PagerUnref(pPgOld);
40858   }
40859
40860   if( needSyncPgno ){
40861     /* If needSyncPgno is non-zero, then the journal file needs to be 
40862     ** sync()ed before any data is written to database file page needSyncPgno.
40863     ** Currently, no such page exists in the page-cache and the 
40864     ** "is journaled" bitvec flag has been set. This needs to be remedied by
40865     ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
40866     ** flag.
40867     **
40868     ** If the attempt to load the page into the page-cache fails, (due
40869     ** to a malloc() or IO failure), clear the bit in the pInJournal[]
40870     ** array. Otherwise, if the page is loaded and written again in
40871     ** this transaction, it may be written to the database file before
40872     ** it is synced into the journal file. This way, it may end up in
40873     ** the journal file twice, but that is not a problem.
40874     */
40875     PgHdr *pPgHdr;
40876     rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
40877     if( rc!=SQLITE_OK ){
40878       if( needSyncPgno<=pPager->dbOrigSize ){
40879         assert( pPager->pTmpSpace!=0 );
40880         sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
40881       }
40882       return rc;
40883     }
40884     pPgHdr->flags |= PGHDR_NEED_SYNC;
40885     sqlite3PcacheMakeDirty(pPgHdr);
40886     sqlite3PagerUnref(pPgHdr);
40887   }
40888
40889   return SQLITE_OK;
40890 }
40891 #endif
40892
40893 /*
40894 ** Return a pointer to the data for the specified page.
40895 */
40896 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
40897   assert( pPg->nRef>0 || pPg->pPager->memDb );
40898   return pPg->pData;
40899 }
40900
40901 /*
40902 ** Return a pointer to the Pager.nExtra bytes of "extra" space 
40903 ** allocated along with the specified page.
40904 */
40905 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
40906   return pPg->pExtra;
40907 }
40908
40909 /*
40910 ** Get/set the locking-mode for this pager. Parameter eMode must be one
40911 ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or 
40912 ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
40913 ** the locking-mode is set to the value specified.
40914 **
40915 ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
40916 ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
40917 ** locking-mode.
40918 */
40919 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
40920   assert( eMode==PAGER_LOCKINGMODE_QUERY
40921             || eMode==PAGER_LOCKINGMODE_NORMAL
40922             || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
40923   assert( PAGER_LOCKINGMODE_QUERY<0 );
40924   assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
40925   if( eMode>=0 && !pPager->tempFile ){
40926     pPager->exclusiveMode = (u8)eMode;
40927   }
40928   return (int)pPager->exclusiveMode;
40929 }
40930
40931 /*
40932 ** Set the journal-mode for this pager. Parameter eMode must be one of:
40933 **
40934 **    PAGER_JOURNALMODE_DELETE
40935 **    PAGER_JOURNALMODE_TRUNCATE
40936 **    PAGER_JOURNALMODE_PERSIST
40937 **    PAGER_JOURNALMODE_OFF
40938 **    PAGER_JOURNALMODE_MEMORY
40939 **    PAGER_JOURNALMODE_WAL
40940 **
40941 ** The journalmode is set to the value specified if the change is allowed.
40942 ** The change may be disallowed for the following reasons:
40943 **
40944 **   *  An in-memory database can only have its journal_mode set to _OFF
40945 **      or _MEMORY.
40946 **
40947 **   *  Temporary databases cannot have _WAL journalmode.
40948 **
40949 ** The returned indicate the current (possibly updated) journal-mode.
40950 */
40951 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
40952   u8 eOld = pPager->journalMode;    /* Prior journalmode */
40953
40954 #ifdef SQLITE_DEBUG
40955   /* The print_pager_state() routine is intended to be used by the debugger
40956   ** only.  We invoke it once here to suppress a compiler warning. */
40957   print_pager_state(pPager);
40958 #endif
40959
40960
40961   /* The eMode parameter is always valid */
40962   assert(      eMode==PAGER_JOURNALMODE_DELETE
40963             || eMode==PAGER_JOURNALMODE_TRUNCATE
40964             || eMode==PAGER_JOURNALMODE_PERSIST
40965             || eMode==PAGER_JOURNALMODE_OFF 
40966             || eMode==PAGER_JOURNALMODE_WAL 
40967             || eMode==PAGER_JOURNALMODE_MEMORY );
40968
40969   /* This routine is only called from the OP_JournalMode opcode, and
40970   ** the logic there will never allow a temporary file to be changed
40971   ** to WAL mode.
40972   */
40973   assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
40974
40975   /* Do allow the journalmode of an in-memory database to be set to
40976   ** anything other than MEMORY or OFF
40977   */
40978   if( MEMDB ){
40979     assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
40980     if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
40981       eMode = eOld;
40982     }
40983   }
40984
40985   if( eMode!=eOld ){
40986
40987     /* Change the journal mode. */
40988     assert( pPager->eState!=PAGER_ERROR );
40989     pPager->journalMode = (u8)eMode;
40990
40991     /* When transistioning from TRUNCATE or PERSIST to any other journal
40992     ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
40993     ** delete the journal file.
40994     */
40995     assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
40996     assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
40997     assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
40998     assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
40999     assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
41000     assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
41001
41002     assert( isOpen(pPager->fd) || pPager->exclusiveMode );
41003     if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
41004
41005       /* In this case we would like to delete the journal file. If it is
41006       ** not possible, then that is not a problem. Deleting the journal file
41007       ** here is an optimization only.
41008       **
41009       ** Before deleting the journal file, obtain a RESERVED lock on the
41010       ** database file. This ensures that the journal file is not deleted
41011       ** while it is in use by some other client.
41012       */
41013       sqlite3OsClose(pPager->jfd);
41014       if( pPager->eLock>=RESERVED_LOCK ){
41015         sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
41016       }else{
41017         int rc = SQLITE_OK;
41018         int state = pPager->eState;
41019         assert( state==PAGER_OPEN || state==PAGER_READER );
41020         if( state==PAGER_OPEN ){
41021           rc = sqlite3PagerSharedLock(pPager);
41022         }
41023         if( pPager->eState==PAGER_READER ){
41024           assert( rc==SQLITE_OK );
41025           rc = pagerLockDb(pPager, RESERVED_LOCK);
41026         }
41027         if( rc==SQLITE_OK ){
41028           sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
41029         }
41030         if( rc==SQLITE_OK && state==PAGER_READER ){
41031           pagerUnlockDb(pPager, SHARED_LOCK);
41032         }else if( state==PAGER_OPEN ){
41033           pager_unlock(pPager);
41034         }
41035         assert( state==pPager->eState );
41036       }
41037     }
41038   }
41039
41040   /* Return the new journal mode */
41041   return (int)pPager->journalMode;
41042 }
41043
41044 /*
41045 ** Return the current journal mode.
41046 */
41047 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
41048   return (int)pPager->journalMode;
41049 }
41050
41051 /*
41052 ** Return TRUE if the pager is in a state where it is OK to change the
41053 ** journalmode.  Journalmode changes can only happen when the database
41054 ** is unmodified.
41055 */
41056 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
41057   assert( assert_pager_state(pPager) );
41058   if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
41059   if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
41060   return 1;
41061 }
41062
41063 /*
41064 ** Get/set the size-limit used for persistent journal files.
41065 **
41066 ** Setting the size limit to -1 means no limit is enforced.
41067 ** An attempt to set a limit smaller than -1 is a no-op.
41068 */
41069 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
41070   if( iLimit>=-1 ){
41071     pPager->journalSizeLimit = iLimit;
41072   }
41073   return pPager->journalSizeLimit;
41074 }
41075
41076 /*
41077 ** Return a pointer to the pPager->pBackup variable. The backup module
41078 ** in backup.c maintains the content of this variable. This module
41079 ** uses it opaquely as an argument to sqlite3BackupRestart() and
41080 ** sqlite3BackupUpdate() only.
41081 */
41082 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
41083   return &pPager->pBackup;
41084 }
41085
41086 #ifndef SQLITE_OMIT_WAL
41087 /*
41088 ** This function is called when the user invokes "PRAGMA checkpoint".
41089 */
41090 SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager){
41091   int rc = SQLITE_OK;
41092   if( pPager->pWal ){
41093     u8 *zBuf = (u8 *)pPager->pTmpSpace;
41094     rc = sqlite3WalCheckpoint(pPager->pWal,
41095         (pPager->noSync ? 0 : pPager->sync_flags),
41096         pPager->pageSize, zBuf
41097     );
41098   }
41099   return rc;
41100 }
41101
41102 SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
41103   return sqlite3WalCallback(pPager->pWal);
41104 }
41105
41106 /*
41107 ** Return true if the underlying VFS for the given pager supports the
41108 ** primitives necessary for write-ahead logging.
41109 */
41110 SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
41111   const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
41112   return pMethods->iVersion>=2 && pMethods->xShmMap!=0;
41113 }
41114
41115 /*
41116 ** The caller must be holding a SHARED lock on the database file to call
41117 ** this function.
41118 **
41119 ** If the pager passed as the first argument is open on a real database
41120 ** file (not a temp file or an in-memory database), and the WAL file
41121 ** is not already open, make an attempt to open it now. If successful,
41122 ** return SQLITE_OK. If an error occurs or the VFS used by the pager does 
41123 ** not support the xShmXXX() methods, return an error code. *pbOpen is
41124 ** not modified in either case.
41125 **
41126 ** If the pager is open on a temp-file (or in-memory database), or if
41127 ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
41128 ** without doing anything.
41129 */
41130 SQLITE_PRIVATE int sqlite3PagerOpenWal(
41131   Pager *pPager,                  /* Pager object */
41132   int *pbOpen                     /* OUT: Set to true if call is a no-op */
41133 ){
41134   int rc = SQLITE_OK;             /* Return code */
41135
41136   assert( assert_pager_state(pPager) );
41137   assert( pPager->eState==PAGER_OPEN   || pbOpen );
41138   assert( pPager->eState==PAGER_READER || !pbOpen );
41139   assert( pbOpen==0 || *pbOpen==0 );
41140   assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
41141
41142   if( !pPager->tempFile && !pPager->pWal ){
41143     if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
41144
41145     /* Close any rollback journal previously open */
41146     sqlite3OsClose(pPager->jfd);
41147
41148     /* Open the connection to the log file. If this operation fails, 
41149     ** (e.g. due to malloc() failure), unlock the database file and 
41150     ** return an error code.
41151     */
41152     rc = sqlite3WalOpen(pPager->pVfs, pPager->fd, pPager->zWal, &pPager->pWal);
41153     if( rc==SQLITE_OK ){
41154       pPager->journalMode = PAGER_JOURNALMODE_WAL;
41155       pPager->eState = PAGER_OPEN;
41156     }
41157   }else{
41158     *pbOpen = 1;
41159   }
41160
41161   return rc;
41162 }
41163
41164 /*
41165 ** This function is called to close the connection to the log file prior
41166 ** to switching from WAL to rollback mode.
41167 **
41168 ** Before closing the log file, this function attempts to take an 
41169 ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
41170 ** error (SQLITE_BUSY) is returned and the log connection is not closed.
41171 ** If successful, the EXCLUSIVE lock is not released before returning.
41172 */
41173 SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){
41174   int rc = SQLITE_OK;
41175
41176   assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
41177
41178   /* If the log file is not already open, but does exist in the file-system,
41179   ** it may need to be checkpointed before the connection can switch to
41180   ** rollback mode. Open it now so this can happen.
41181   */
41182   if( !pPager->pWal ){
41183     int logexists = 0;
41184     rc = pagerLockDb(pPager, SHARED_LOCK);
41185     if( rc==SQLITE_OK ){
41186       rc = sqlite3OsAccess(
41187           pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
41188       );
41189     }
41190     if( rc==SQLITE_OK && logexists ){
41191       rc = sqlite3WalOpen(pPager->pVfs, pPager->fd,
41192                           pPager->zWal, &pPager->pWal);
41193     }
41194   }
41195     
41196   /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
41197   ** the database file, the log and log-summary files will be deleted.
41198   */
41199   if( rc==SQLITE_OK && pPager->pWal ){
41200     rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
41201     if( rc==SQLITE_OK ){
41202       rc = sqlite3WalClose(pPager->pWal,
41203                            (pPager->noSync ? 0 : pPager->sync_flags), 
41204         pPager->pageSize, (u8*)pPager->pTmpSpace
41205       );
41206       pPager->pWal = 0;
41207     }else{
41208       /* If we cannot get an EXCLUSIVE lock, downgrade the PENDING lock
41209       ** that we did get back to SHARED. */
41210       pagerUnlockDb(pPager, SQLITE_LOCK_SHARED);
41211     }
41212   }
41213   return rc;
41214 }
41215
41216 #ifdef SQLITE_HAS_CODEC
41217 /*
41218 ** This function is called by the wal module when writing page content
41219 ** into the log file.
41220 **
41221 ** This function returns a pointer to a buffer containing the encrypted
41222 ** page content. If a malloc fails, this function may return NULL.
41223 */
41224 SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
41225   void *aData = 0;
41226   CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
41227   return aData;
41228 }
41229 #endif /* SQLITE_HAS_CODEC */
41230
41231 #endif /* !SQLITE_OMIT_WAL */
41232
41233 #endif /* SQLITE_OMIT_DISKIO */
41234
41235 /************** End of pager.c ***********************************************/
41236 /************** Begin file wal.c *********************************************/
41237 /*
41238 ** 2010 February 1
41239 **
41240 ** The author disclaims copyright to this source code.  In place of
41241 ** a legal notice, here is a blessing:
41242 **
41243 **    May you do good and not evil.
41244 **    May you find forgiveness for yourself and forgive others.
41245 **    May you share freely, never taking more than you give.
41246 **
41247 *************************************************************************
41248 **
41249 ** This file contains the implementation of a write-ahead log (WAL) used in 
41250 ** "journal_mode=WAL" mode.
41251 **
41252 ** WRITE-AHEAD LOG (WAL) FILE FORMAT
41253 **
41254 ** A WAL file consists of a header followed by zero or more "frames".
41255 ** Each frame records the revised content of a single page from the
41256 ** database file.  All changes to the database are recorded by writing
41257 ** frames into the WAL.  Transactions commit when a frame is written that
41258 ** contains a commit marker.  A single WAL can and usually does record 
41259 ** multiple transactions.  Periodically, the content of the WAL is
41260 ** transferred back into the database file in an operation called a
41261 ** "checkpoint".
41262 **
41263 ** A single WAL file can be used multiple times.  In other words, the
41264 ** WAL can fill up with frames and then be checkpointed and then new
41265 ** frames can overwrite the old ones.  A WAL always grows from beginning
41266 ** toward the end.  Checksums and counters attached to each frame are
41267 ** used to determine which frames within the WAL are valid and which
41268 ** are leftovers from prior checkpoints.
41269 **
41270 ** The WAL header is 32 bytes in size and consists of the following eight
41271 ** big-endian 32-bit unsigned integer values:
41272 **
41273 **     0: Magic number.  0x377f0682 or 0x377f0683
41274 **     4: File format version.  Currently 3007000
41275 **     8: Database page size.  Example: 1024
41276 **    12: Checkpoint sequence number
41277 **    16: Salt-1, random integer incremented with each checkpoint
41278 **    20: Salt-2, a different random integer changing with each ckpt
41279 **    24: Checksum-1 (first part of checksum for first 24 bytes of header).
41280 **    28: Checksum-2 (second part of checksum for first 24 bytes of header).
41281 **
41282 ** Immediately following the wal-header are zero or more frames. Each
41283 ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
41284 ** of page data. The frame-header is six big-endian 32-bit unsigned 
41285 ** integer values, as follows:
41286 **
41287 **     0: Page number.
41288 **     4: For commit records, the size of the database image in pages 
41289 **        after the commit. For all other records, zero.
41290 **     8: Salt-1 (copied from the header)
41291 **    12: Salt-2 (copied from the header)
41292 **    16: Checksum-1.
41293 **    20: Checksum-2.
41294 **
41295 ** A frame is considered valid if and only if the following conditions are
41296 ** true:
41297 **
41298 **    (1) The salt-1 and salt-2 values in the frame-header match
41299 **        salt values in the wal-header
41300 **
41301 **    (2) The checksum values in the final 8 bytes of the frame-header
41302 **        exactly match the checksum computed consecutively on the
41303 **        WAL header and the first 8 bytes and the content of all frames
41304 **        up to and including the current frame.
41305 **
41306 ** The checksum is computed using 32-bit big-endian integers if the
41307 ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
41308 ** is computed using little-endian if the magic number is 0x377f0682.
41309 ** The checksum values are always stored in the frame header in a
41310 ** big-endian format regardless of which byte order is used to compute
41311 ** the checksum.  The checksum is computed by interpreting the input as
41312 ** an even number of unsigned 32-bit integers: x[0] through x[N].  The
41313 ** algorithm used for the checksum is as follows:
41314 ** 
41315 **   for i from 0 to n-1 step 2:
41316 **     s0 += x[i] + s1;
41317 **     s1 += x[i+1] + s0;
41318 **   endfor
41319 **
41320 ** Note that s0 and s1 are both weighted checksums using fibonacci weights
41321 ** in reverse order (the largest fibonacci weight occurs on the first element
41322 ** of the sequence being summed.)  The s1 value spans all 32-bit 
41323 ** terms of the sequence whereas s0 omits the final term.
41324 **
41325 ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
41326 ** WAL is transferred into the database, then the database is VFS.xSync-ed.
41327 ** The VFS.xSync operations serve as write barriers - all writes launched
41328 ** before the xSync must complete before any write that launches after the
41329 ** xSync begins.
41330 **
41331 ** After each checkpoint, the salt-1 value is incremented and the salt-2
41332 ** value is randomized.  This prevents old and new frames in the WAL from
41333 ** being considered valid at the same time and being checkpointing together
41334 ** following a crash.
41335 **
41336 ** READER ALGORITHM
41337 **
41338 ** To read a page from the database (call it page number P), a reader
41339 ** first checks the WAL to see if it contains page P.  If so, then the
41340 ** last valid instance of page P that is a followed by a commit frame
41341 ** or is a commit frame itself becomes the value read.  If the WAL
41342 ** contains no copies of page P that are valid and which are a commit
41343 ** frame or are followed by a commit frame, then page P is read from
41344 ** the database file.
41345 **
41346 ** To start a read transaction, the reader records the index of the last
41347 ** valid frame in the WAL.  The reader uses this recorded "mxFrame" value
41348 ** for all subsequent read operations.  New transactions can be appended
41349 ** to the WAL, but as long as the reader uses its original mxFrame value
41350 ** and ignores the newly appended content, it will see a consistent snapshot
41351 ** of the database from a single point in time.  This technique allows
41352 ** multiple concurrent readers to view different versions of the database
41353 ** content simultaneously.
41354 **
41355 ** The reader algorithm in the previous paragraphs works correctly, but 
41356 ** because frames for page P can appear anywhere within the WAL, the
41357 ** reader has to scan the entire WAL looking for page P frames.  If the
41358 ** WAL is large (multiple megabytes is typical) that scan can be slow,
41359 ** and read performance suffers.  To overcome this problem, a separate
41360 ** data structure called the wal-index is maintained to expedite the
41361 ** search for frames of a particular page.
41362 ** 
41363 ** WAL-INDEX FORMAT
41364 **
41365 ** Conceptually, the wal-index is shared memory, though VFS implementations
41366 ** might choose to implement the wal-index using a mmapped file.  Because
41367 ** the wal-index is shared memory, SQLite does not support journal_mode=WAL 
41368 ** on a network filesystem.  All users of the database must be able to
41369 ** share memory.
41370 **
41371 ** The wal-index is transient.  After a crash, the wal-index can (and should
41372 ** be) reconstructed from the original WAL file.  In fact, the VFS is required
41373 ** to either truncate or zero the header of the wal-index when the last
41374 ** connection to it closes.  Because the wal-index is transient, it can
41375 ** use an architecture-specific format; it does not have to be cross-platform.
41376 ** Hence, unlike the database and WAL file formats which store all values
41377 ** as big endian, the wal-index can store multi-byte values in the native
41378 ** byte order of the host computer.
41379 **
41380 ** The purpose of the wal-index is to answer this question quickly:  Given
41381 ** a page number P, return the index of the last frame for page P in the WAL,
41382 ** or return NULL if there are no frames for page P in the WAL.
41383 **
41384 ** The wal-index consists of a header region, followed by an one or
41385 ** more index blocks.  
41386 **
41387 ** The wal-index header contains the total number of frames within the WAL
41388 ** in the the mxFrame field.  
41389 **
41390 ** Each index block except for the first contains information on 
41391 ** HASHTABLE_NPAGE frames. The first index block contains information on
41392 ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and 
41393 ** HASHTABLE_NPAGE are selected so that together the wal-index header and
41394 ** first index block are the same size as all other index blocks in the
41395 ** wal-index.
41396 **
41397 ** Each index block contains two sections, a page-mapping that contains the
41398 ** database page number associated with each wal frame, and a hash-table 
41399 ** that allows readers to query an index block for a specific page number.
41400 ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
41401 ** for the first index block) 32-bit page numbers. The first entry in the 
41402 ** first index-block contains the database page number corresponding to the
41403 ** first frame in the WAL file. The first entry in the second index block
41404 ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
41405 ** the log, and so on.
41406 **
41407 ** The last index block in a wal-index usually contains less than the full
41408 ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
41409 ** depending on the contents of the WAL file. This does not change the
41410 ** allocated size of the page-mapping array - the page-mapping array merely
41411 ** contains unused entries.
41412 **
41413 ** Even without using the hash table, the last frame for page P
41414 ** can be found by scanning the page-mapping sections of each index block
41415 ** starting with the last index block and moving toward the first, and
41416 ** within each index block, starting at the end and moving toward the
41417 ** beginning.  The first entry that equals P corresponds to the frame
41418 ** holding the content for that page.
41419 **
41420 ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
41421 ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
41422 ** hash table for each page number in the mapping section, so the hash 
41423 ** table is never more than half full.  The expected number of collisions 
41424 ** prior to finding a match is 1.  Each entry of the hash table is an
41425 ** 1-based index of an entry in the mapping section of the same
41426 ** index block.   Let K be the 1-based index of the largest entry in
41427 ** the mapping section.  (For index blocks other than the last, K will
41428 ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
41429 ** K will be (mxFrame%HASHTABLE_NPAGE).)  Unused slots of the hash table
41430 ** contain a value of 0.
41431 **
41432 ** To look for page P in the hash table, first compute a hash iKey on
41433 ** P as follows:
41434 **
41435 **      iKey = (P * 383) % HASHTABLE_NSLOT
41436 **
41437 ** Then start scanning entries of the hash table, starting with iKey
41438 ** (wrapping around to the beginning when the end of the hash table is
41439 ** reached) until an unused hash slot is found. Let the first unused slot
41440 ** be at index iUnused.  (iUnused might be less than iKey if there was
41441 ** wrap-around.) Because the hash table is never more than half full,
41442 ** the search is guaranteed to eventually hit an unused entry.  Let 
41443 ** iMax be the value between iKey and iUnused, closest to iUnused,
41444 ** where aHash[iMax]==P.  If there is no iMax entry (if there exists
41445 ** no hash slot such that aHash[i]==p) then page P is not in the
41446 ** current index block.  Otherwise the iMax-th mapping entry of the
41447 ** current index block corresponds to the last entry that references 
41448 ** page P.
41449 **
41450 ** A hash search begins with the last index block and moves toward the
41451 ** first index block, looking for entries corresponding to page P.  On
41452 ** average, only two or three slots in each index block need to be
41453 ** examined in order to either find the last entry for page P, or to
41454 ** establish that no such entry exists in the block.  Each index block
41455 ** holds over 4000 entries.  So two or three index blocks are sufficient
41456 ** to cover a typical 10 megabyte WAL file, assuming 1K pages.  8 or 10
41457 ** comparisons (on average) suffice to either locate a frame in the
41458 ** WAL or to establish that the frame does not exist in the WAL.  This
41459 ** is much faster than scanning the entire 10MB WAL.
41460 **
41461 ** Note that entries are added in order of increasing K.  Hence, one
41462 ** reader might be using some value K0 and a second reader that started
41463 ** at a later time (after additional transactions were added to the WAL
41464 ** and to the wal-index) might be using a different value K1, where K1>K0.
41465 ** Both readers can use the same hash table and mapping section to get
41466 ** the correct result.  There may be entries in the hash table with
41467 ** K>K0 but to the first reader, those entries will appear to be unused
41468 ** slots in the hash table and so the first reader will get an answer as
41469 ** if no values greater than K0 had ever been inserted into the hash table
41470 ** in the first place - which is what reader one wants.  Meanwhile, the
41471 ** second reader using K1 will see additional values that were inserted
41472 ** later, which is exactly what reader two wants.  
41473 **
41474 ** When a rollback occurs, the value of K is decreased. Hash table entries
41475 ** that correspond to frames greater than the new K value are removed
41476 ** from the hash table at this point.
41477 */
41478 #ifndef SQLITE_OMIT_WAL
41479
41480
41481 /*
41482 ** Trace output macros
41483 */
41484 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
41485 SQLITE_PRIVATE int sqlite3WalTrace = 0;
41486 # define WALTRACE(X)  if(sqlite3WalTrace) sqlite3DebugPrintf X
41487 #else
41488 # define WALTRACE(X)
41489 #endif
41490
41491 /*
41492 ** The maximum (and only) versions of the wal and wal-index formats
41493 ** that may be interpreted by this version of SQLite.
41494 **
41495 ** If a client begins recovering a WAL file and finds that (a) the checksum
41496 ** values in the wal-header are correct and (b) the version field is not
41497 ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
41498 **
41499 ** Similarly, if a client successfully reads a wal-index header (i.e. the 
41500 ** checksum test is successful) and finds that the version field is not
41501 ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
41502 ** returns SQLITE_CANTOPEN.
41503 */
41504 #define WAL_MAX_VERSION      3007000
41505 #define WALINDEX_MAX_VERSION 3007000
41506
41507 /*
41508 ** Indices of various locking bytes.   WAL_NREADER is the number
41509 ** of available reader locks and should be at least 3.
41510 */
41511 #define WAL_WRITE_LOCK         0
41512 #define WAL_ALL_BUT_WRITE      1
41513 #define WAL_CKPT_LOCK          1
41514 #define WAL_RECOVER_LOCK       2
41515 #define WAL_READ_LOCK(I)       (3+(I))
41516 #define WAL_NREADER            (SQLITE_SHM_NLOCK-3)
41517
41518
41519 /* Object declarations */
41520 typedef struct WalIndexHdr WalIndexHdr;
41521 typedef struct WalIterator WalIterator;
41522 typedef struct WalCkptInfo WalCkptInfo;
41523
41524
41525 /*
41526 ** The following object holds a copy of the wal-index header content.
41527 **
41528 ** The actual header in the wal-index consists of two copies of this
41529 ** object.
41530 **
41531 ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
41532 ** Or it can be 1 to represent a 65536-byte page.  The latter case was
41533 ** added in 3.7.1 when support for 64K pages was added.  
41534 */
41535 struct WalIndexHdr {
41536   u32 iVersion;                   /* Wal-index version */
41537   u32 unused;                     /* Unused (padding) field */
41538   u32 iChange;                    /* Counter incremented each transaction */
41539   u8 isInit;                      /* 1 when initialized */
41540   u8 bigEndCksum;                 /* True if checksums in WAL are big-endian */
41541   u16 szPage;                     /* Database page size in bytes. 1==64K */
41542   u32 mxFrame;                    /* Index of last valid frame in the WAL */
41543   u32 nPage;                      /* Size of database in pages */
41544   u32 aFrameCksum[2];             /* Checksum of last frame in log */
41545   u32 aSalt[2];                   /* Two salt values copied from WAL header */
41546   u32 aCksum[2];                  /* Checksum over all prior fields */
41547 };
41548
41549 /*
41550 ** A copy of the following object occurs in the wal-index immediately
41551 ** following the second copy of the WalIndexHdr.  This object stores
41552 ** information used by checkpoint.
41553 **
41554 ** nBackfill is the number of frames in the WAL that have been written
41555 ** back into the database. (We call the act of moving content from WAL to
41556 ** database "backfilling".)  The nBackfill number is never greater than
41557 ** WalIndexHdr.mxFrame.  nBackfill can only be increased by threads
41558 ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
41559 ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
41560 ** mxFrame back to zero when the WAL is reset.
41561 **
41562 ** There is one entry in aReadMark[] for each reader lock.  If a reader
41563 ** holds read-lock K, then the value in aReadMark[K] is no greater than
41564 ** the mxFrame for that reader.  The value READMARK_NOT_USED (0xffffffff)
41565 ** for any aReadMark[] means that entry is unused.  aReadMark[0] is 
41566 ** a special case; its value is never used and it exists as a place-holder
41567 ** to avoid having to offset aReadMark[] indexs by one.  Readers holding
41568 ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
41569 ** directly from the database.
41570 **
41571 ** The value of aReadMark[K] may only be changed by a thread that
41572 ** is holding an exclusive lock on WAL_READ_LOCK(K).  Thus, the value of
41573 ** aReadMark[K] cannot changed while there is a reader is using that mark
41574 ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
41575 **
41576 ** The checkpointer may only transfer frames from WAL to database where
41577 ** the frame numbers are less than or equal to every aReadMark[] that is
41578 ** in use (that is, every aReadMark[j] for which there is a corresponding
41579 ** WAL_READ_LOCK(j)).  New readers (usually) pick the aReadMark[] with the
41580 ** largest value and will increase an unused aReadMark[] to mxFrame if there
41581 ** is not already an aReadMark[] equal to mxFrame.  The exception to the
41582 ** previous sentence is when nBackfill equals mxFrame (meaning that everything
41583 ** in the WAL has been backfilled into the database) then new readers
41584 ** will choose aReadMark[0] which has value 0 and hence such reader will
41585 ** get all their all content directly from the database file and ignore 
41586 ** the WAL.
41587 **
41588 ** Writers normally append new frames to the end of the WAL.  However,
41589 ** if nBackfill equals mxFrame (meaning that all WAL content has been
41590 ** written back into the database) and if no readers are using the WAL
41591 ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
41592 ** the writer will first "reset" the WAL back to the beginning and start
41593 ** writing new content beginning at frame 1.
41594 **
41595 ** We assume that 32-bit loads are atomic and so no locks are needed in
41596 ** order to read from any aReadMark[] entries.
41597 */
41598 struct WalCkptInfo {
41599   u32 nBackfill;                  /* Number of WAL frames backfilled into DB */
41600   u32 aReadMark[WAL_NREADER];     /* Reader marks */
41601 };
41602 #define READMARK_NOT_USED  0xffffffff
41603
41604
41605 /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
41606 ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
41607 ** only support mandatory file-locks, we do not read or write data
41608 ** from the region of the file on which locks are applied.
41609 */
41610 #define WALINDEX_LOCK_OFFSET   (sizeof(WalIndexHdr)*2 + sizeof(WalCkptInfo))
41611 #define WALINDEX_LOCK_RESERVED 16
41612 #define WALINDEX_HDR_SIZE      (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED)
41613
41614 /* Size of header before each frame in wal */
41615 #define WAL_FRAME_HDRSIZE 24
41616
41617 /* Size of write ahead log header, including checksum. */
41618 /* #define WAL_HDRSIZE 24 */
41619 #define WAL_HDRSIZE 32
41620
41621 /* WAL magic value. Either this value, or the same value with the least
41622 ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
41623 ** big-endian format in the first 4 bytes of a WAL file.
41624 **
41625 ** If the LSB is set, then the checksums for each frame within the WAL
41626 ** file are calculated by treating all data as an array of 32-bit 
41627 ** big-endian words. Otherwise, they are calculated by interpreting 
41628 ** all data as 32-bit little-endian words.
41629 */
41630 #define WAL_MAGIC 0x377f0682
41631
41632 /*
41633 ** Return the offset of frame iFrame in the write-ahead log file, 
41634 ** assuming a database page size of szPage bytes. The offset returned
41635 ** is to the start of the write-ahead log frame-header.
41636 */
41637 #define walFrameOffset(iFrame, szPage) (                               \
41638   WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE)         \
41639 )
41640
41641 /*
41642 ** An open write-ahead log file is represented by an instance of the
41643 ** following object.
41644 */
41645 struct Wal {
41646   sqlite3_vfs *pVfs;         /* The VFS used to create pDbFd */
41647   sqlite3_file *pDbFd;       /* File handle for the database file */
41648   sqlite3_file *pWalFd;      /* File handle for WAL file */
41649   u32 iCallback;             /* Value to pass to log callback (or 0) */
41650   int nWiData;               /* Size of array apWiData */
41651   volatile u32 **apWiData;   /* Pointer to wal-index content in memory */
41652   u32 szPage;                /* Database page size */
41653   i16 readLock;              /* Which read lock is being held.  -1 for none */
41654   u8 exclusiveMode;          /* Non-zero if connection is in exclusive mode */
41655   u8 writeLock;              /* True if in a write transaction */
41656   u8 ckptLock;               /* True if holding a checkpoint lock */
41657   u8 readOnly;               /* True if the WAL file is open read-only */
41658   WalIndexHdr hdr;           /* Wal-index header for current transaction */
41659   const char *zWalName;      /* Name of WAL file */
41660   u32 nCkpt;                 /* Checkpoint sequence counter in the wal-header */
41661 #ifdef SQLITE_DEBUG
41662   u8 lockError;              /* True if a locking error has occurred */
41663 #endif
41664 };
41665
41666 /*
41667 ** Each page of the wal-index mapping contains a hash-table made up of
41668 ** an array of HASHTABLE_NSLOT elements of the following type.
41669 */
41670 typedef u16 ht_slot;
41671
41672 /*
41673 ** This structure is used to implement an iterator that loops through
41674 ** all frames in the WAL in database page order. Where two or more frames
41675 ** correspond to the same database page, the iterator visits only the 
41676 ** frame most recently written to the WAL (in other words, the frame with
41677 ** the largest index).
41678 **
41679 ** The internals of this structure are only accessed by:
41680 **
41681 **   walIteratorInit() - Create a new iterator,
41682 **   walIteratorNext() - Step an iterator,
41683 **   walIteratorFree() - Free an iterator.
41684 **
41685 ** This functionality is used by the checkpoint code (see walCheckpoint()).
41686 */
41687 struct WalIterator {
41688   int iPrior;                     /* Last result returned from the iterator */
41689   int nSegment;                   /* Size of the aSegment[] array */
41690   struct WalSegment {
41691     int iNext;                    /* Next slot in aIndex[] not yet returned */
41692     ht_slot *aIndex;              /* i0, i1, i2... such that aPgno[iN] ascend */
41693     u32 *aPgno;                   /* Array of page numbers. */
41694     int nEntry;                   /* Max size of aPgno[] and aIndex[] arrays */
41695     int iZero;                    /* Frame number associated with aPgno[0] */
41696   } aSegment[1];                  /* One for every 32KB page in the WAL */
41697 };
41698
41699 /*
41700 ** Define the parameters of the hash tables in the wal-index file. There
41701 ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
41702 ** wal-index.
41703 **
41704 ** Changing any of these constants will alter the wal-index format and
41705 ** create incompatibilities.
41706 */
41707 #define HASHTABLE_NPAGE      4096                 /* Must be power of 2 */
41708 #define HASHTABLE_HASH_1     383                  /* Should be prime */
41709 #define HASHTABLE_NSLOT      (HASHTABLE_NPAGE*2)  /* Must be a power of 2 */
41710
41711 /* 
41712 ** The block of page numbers associated with the first hash-table in a
41713 ** wal-index is smaller than usual. This is so that there is a complete
41714 ** hash-table on each aligned 32KB page of the wal-index.
41715 */
41716 #define HASHTABLE_NPAGE_ONE  (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
41717
41718 /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
41719 #define WALINDEX_PGSZ   (                                         \
41720     sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
41721 )
41722
41723 /*
41724 ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
41725 ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
41726 ** numbered from zero.
41727 **
41728 ** If this call is successful, *ppPage is set to point to the wal-index
41729 ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
41730 ** then an SQLite error code is returned and *ppPage is set to 0.
41731 */
41732 static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
41733   int rc = SQLITE_OK;
41734
41735   /* Enlarge the pWal->apWiData[] array if required */
41736   if( pWal->nWiData<=iPage ){
41737     int nByte = sizeof(u32*)*(iPage+1);
41738     volatile u32 **apNew;
41739     apNew = (volatile u32 **)sqlite3_realloc((void *)pWal->apWiData, nByte);
41740     if( !apNew ){
41741       *ppPage = 0;
41742       return SQLITE_NOMEM;
41743     }
41744     memset((void*)&apNew[pWal->nWiData], 0,
41745            sizeof(u32*)*(iPage+1-pWal->nWiData));
41746     pWal->apWiData = apNew;
41747     pWal->nWiData = iPage+1;
41748   }
41749
41750   /* Request a pointer to the required page from the VFS */
41751   if( pWal->apWiData[iPage]==0 ){
41752     rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ, 
41753         pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
41754     );
41755   }
41756
41757   *ppPage = pWal->apWiData[iPage];
41758   assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
41759   return rc;
41760 }
41761
41762 /*
41763 ** Return a pointer to the WalCkptInfo structure in the wal-index.
41764 */
41765 static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
41766   assert( pWal->nWiData>0 && pWal->apWiData[0] );
41767   return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
41768 }
41769
41770 /*
41771 ** Return a pointer to the WalIndexHdr structure in the wal-index.
41772 */
41773 static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
41774   assert( pWal->nWiData>0 && pWal->apWiData[0] );
41775   return (volatile WalIndexHdr*)pWal->apWiData[0];
41776 }
41777
41778 /*
41779 ** The argument to this macro must be of type u32. On a little-endian
41780 ** architecture, it returns the u32 value that results from interpreting
41781 ** the 4 bytes as a big-endian value. On a big-endian architecture, it
41782 ** returns the value that would be produced by intepreting the 4 bytes
41783 ** of the input value as a little-endian integer.
41784 */
41785 #define BYTESWAP32(x) ( \
41786     (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8)  \
41787   + (((x)&0x00FF0000)>>8)  + (((x)&0xFF000000)>>24) \
41788 )
41789
41790 /*
41791 ** Generate or extend an 8 byte checksum based on the data in 
41792 ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
41793 ** initial values of 0 and 0 if aIn==NULL).
41794 **
41795 ** The checksum is written back into aOut[] before returning.
41796 **
41797 ** nByte must be a positive multiple of 8.
41798 */
41799 static void walChecksumBytes(
41800   int nativeCksum, /* True for native byte-order, false for non-native */
41801   u8 *a,           /* Content to be checksummed */
41802   int nByte,       /* Bytes of content in a[].  Must be a multiple of 8. */
41803   const u32 *aIn,  /* Initial checksum value input */
41804   u32 *aOut        /* OUT: Final checksum value output */
41805 ){
41806   u32 s1, s2;
41807   u32 *aData = (u32 *)a;
41808   u32 *aEnd = (u32 *)&a[nByte];
41809
41810   if( aIn ){
41811     s1 = aIn[0];
41812     s2 = aIn[1];
41813   }else{
41814     s1 = s2 = 0;
41815   }
41816
41817   assert( nByte>=8 );
41818   assert( (nByte&0x00000007)==0 );
41819
41820   if( nativeCksum ){
41821     do {
41822       s1 += *aData++ + s2;
41823       s2 += *aData++ + s1;
41824     }while( aData<aEnd );
41825   }else{
41826     do {
41827       s1 += BYTESWAP32(aData[0]) + s2;
41828       s2 += BYTESWAP32(aData[1]) + s1;
41829       aData += 2;
41830     }while( aData<aEnd );
41831   }
41832
41833   aOut[0] = s1;
41834   aOut[1] = s2;
41835 }
41836
41837 /*
41838 ** Write the header information in pWal->hdr into the wal-index.
41839 **
41840 ** The checksum on pWal->hdr is updated before it is written.
41841 */
41842 static void walIndexWriteHdr(Wal *pWal){
41843   volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
41844   const int nCksum = offsetof(WalIndexHdr, aCksum);
41845
41846   assert( pWal->writeLock );
41847   pWal->hdr.isInit = 1;
41848   pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
41849   walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
41850   memcpy((void *)&aHdr[1], (void *)&pWal->hdr, sizeof(WalIndexHdr));
41851   sqlite3OsShmBarrier(pWal->pDbFd);
41852   memcpy((void *)&aHdr[0], (void *)&pWal->hdr, sizeof(WalIndexHdr));
41853 }
41854
41855 /*
41856 ** This function encodes a single frame header and writes it to a buffer
41857 ** supplied by the caller. A frame-header is made up of a series of 
41858 ** 4-byte big-endian integers, as follows:
41859 **
41860 **     0: Page number.
41861 **     4: For commit records, the size of the database image in pages 
41862 **        after the commit. For all other records, zero.
41863 **     8: Salt-1 (copied from the wal-header)
41864 **    12: Salt-2 (copied from the wal-header)
41865 **    16: Checksum-1.
41866 **    20: Checksum-2.
41867 */
41868 static void walEncodeFrame(
41869   Wal *pWal,                      /* The write-ahead log */
41870   u32 iPage,                      /* Database page number for frame */
41871   u32 nTruncate,                  /* New db size (or 0 for non-commit frames) */
41872   u8 *aData,                      /* Pointer to page data */
41873   u8 *aFrame                      /* OUT: Write encoded frame here */
41874 ){
41875   int nativeCksum;                /* True for native byte-order checksums */
41876   u32 *aCksum = pWal->hdr.aFrameCksum;
41877   assert( WAL_FRAME_HDRSIZE==24 );
41878   sqlite3Put4byte(&aFrame[0], iPage);
41879   sqlite3Put4byte(&aFrame[4], nTruncate);
41880   memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
41881
41882   nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
41883   walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
41884   walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
41885
41886   sqlite3Put4byte(&aFrame[16], aCksum[0]);
41887   sqlite3Put4byte(&aFrame[20], aCksum[1]);
41888 }
41889
41890 /*
41891 ** Check to see if the frame with header in aFrame[] and content
41892 ** in aData[] is valid.  If it is a valid frame, fill *piPage and
41893 ** *pnTruncate and return true.  Return if the frame is not valid.
41894 */
41895 static int walDecodeFrame(
41896   Wal *pWal,                      /* The write-ahead log */
41897   u32 *piPage,                    /* OUT: Database page number for frame */
41898   u32 *pnTruncate,                /* OUT: New db size (or 0 if not commit) */
41899   u8 *aData,                      /* Pointer to page data (for checksum) */
41900   u8 *aFrame                      /* Frame data */
41901 ){
41902   int nativeCksum;                /* True for native byte-order checksums */
41903   u32 *aCksum = pWal->hdr.aFrameCksum;
41904   u32 pgno;                       /* Page number of the frame */
41905   assert( WAL_FRAME_HDRSIZE==24 );
41906
41907   /* A frame is only valid if the salt values in the frame-header
41908   ** match the salt values in the wal-header. 
41909   */
41910   if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
41911     return 0;
41912   }
41913
41914   /* A frame is only valid if the page number is creater than zero.
41915   */
41916   pgno = sqlite3Get4byte(&aFrame[0]);
41917   if( pgno==0 ){
41918     return 0;
41919   }
41920
41921   /* A frame is only valid if a checksum of the WAL header,
41922   ** all prior frams, the first 16 bytes of this frame-header, 
41923   ** and the frame-data matches the checksum in the last 8 
41924   ** bytes of this frame-header.
41925   */
41926   nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
41927   walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
41928   walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
41929   if( aCksum[0]!=sqlite3Get4byte(&aFrame[16]) 
41930    || aCksum[1]!=sqlite3Get4byte(&aFrame[20]) 
41931   ){
41932     /* Checksum failed. */
41933     return 0;
41934   }
41935
41936   /* If we reach this point, the frame is valid.  Return the page number
41937   ** and the new database size.
41938   */
41939   *piPage = pgno;
41940   *pnTruncate = sqlite3Get4byte(&aFrame[4]);
41941   return 1;
41942 }
41943
41944
41945 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
41946 /*
41947 ** Names of locks.  This routine is used to provide debugging output and is not
41948 ** a part of an ordinary build.
41949 */
41950 static const char *walLockName(int lockIdx){
41951   if( lockIdx==WAL_WRITE_LOCK ){
41952     return "WRITE-LOCK";
41953   }else if( lockIdx==WAL_CKPT_LOCK ){
41954     return "CKPT-LOCK";
41955   }else if( lockIdx==WAL_RECOVER_LOCK ){
41956     return "RECOVER-LOCK";
41957   }else{
41958     static char zName[15];
41959     sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
41960                      lockIdx-WAL_READ_LOCK(0));
41961     return zName;
41962   }
41963 }
41964 #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
41965     
41966
41967 /*
41968 ** Set or release locks on the WAL.  Locks are either shared or exclusive.
41969 ** A lock cannot be moved directly between shared and exclusive - it must go
41970 ** through the unlocked state first.
41971 **
41972 ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
41973 */
41974 static int walLockShared(Wal *pWal, int lockIdx){
41975   int rc;
41976   if( pWal->exclusiveMode ) return SQLITE_OK;
41977   rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
41978                         SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
41979   WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
41980             walLockName(lockIdx), rc ? "failed" : "ok"));
41981   VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
41982   return rc;
41983 }
41984 static void walUnlockShared(Wal *pWal, int lockIdx){
41985   if( pWal->exclusiveMode ) return;
41986   (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
41987                          SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
41988   WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
41989 }
41990 static int walLockExclusive(Wal *pWal, int lockIdx, int n){
41991   int rc;
41992   if( pWal->exclusiveMode ) return SQLITE_OK;
41993   rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
41994                         SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
41995   WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
41996             walLockName(lockIdx), n, rc ? "failed" : "ok"));
41997   VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
41998   return rc;
41999 }
42000 static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
42001   if( pWal->exclusiveMode ) return;
42002   (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
42003                          SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
42004   WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
42005              walLockName(lockIdx), n));
42006 }
42007
42008 /*
42009 ** Compute a hash on a page number.  The resulting hash value must land
42010 ** between 0 and (HASHTABLE_NSLOT-1).  The walHashNext() function advances
42011 ** the hash to the next value in the event of a collision.
42012 */
42013 static int walHash(u32 iPage){
42014   assert( iPage>0 );
42015   assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
42016   return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
42017 }
42018 static int walNextHash(int iPriorHash){
42019   return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
42020 }
42021
42022 /* 
42023 ** Return pointers to the hash table and page number array stored on
42024 ** page iHash of the wal-index. The wal-index is broken into 32KB pages
42025 ** numbered starting from 0.
42026 **
42027 ** Set output variable *paHash to point to the start of the hash table
42028 ** in the wal-index file. Set *piZero to one less than the frame 
42029 ** number of the first frame indexed by this hash table. If a
42030 ** slot in the hash table is set to N, it refers to frame number 
42031 ** (*piZero+N) in the log.
42032 **
42033 ** Finally, set *paPgno so that *paPgno[1] is the page number of the
42034 ** first frame indexed by the hash table, frame (*piZero+1).
42035 */
42036 static int walHashGet(
42037   Wal *pWal,                      /* WAL handle */
42038   int iHash,                      /* Find the iHash'th table */
42039   volatile ht_slot **paHash,      /* OUT: Pointer to hash index */
42040   volatile u32 **paPgno,          /* OUT: Pointer to page number array */
42041   u32 *piZero                     /* OUT: Frame associated with *paPgno[0] */
42042 ){
42043   int rc;                         /* Return code */
42044   volatile u32 *aPgno;
42045
42046   rc = walIndexPage(pWal, iHash, &aPgno);
42047   assert( rc==SQLITE_OK || iHash>0 );
42048
42049   if( rc==SQLITE_OK ){
42050     u32 iZero;
42051     volatile ht_slot *aHash;
42052
42053     aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
42054     if( iHash==0 ){
42055       aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
42056       iZero = 0;
42057     }else{
42058       iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
42059     }
42060   
42061     *paPgno = &aPgno[-1];
42062     *paHash = aHash;
42063     *piZero = iZero;
42064   }
42065   return rc;
42066 }
42067
42068 /*
42069 ** Return the number of the wal-index page that contains the hash-table
42070 ** and page-number array that contain entries corresponding to WAL frame
42071 ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages 
42072 ** are numbered starting from 0.
42073 */
42074 static int walFramePage(u32 iFrame){
42075   int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
42076   assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
42077        && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
42078        && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
42079        && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
42080        && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
42081   );
42082   return iHash;
42083 }
42084
42085 /*
42086 ** Return the page number associated with frame iFrame in this WAL.
42087 */
42088 static u32 walFramePgno(Wal *pWal, u32 iFrame){
42089   int iHash = walFramePage(iFrame);
42090   if( iHash==0 ){
42091     return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
42092   }
42093   return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
42094 }
42095
42096 /*
42097 ** Remove entries from the hash table that point to WAL slots greater
42098 ** than pWal->hdr.mxFrame.
42099 **
42100 ** This function is called whenever pWal->hdr.mxFrame is decreased due
42101 ** to a rollback or savepoint.
42102 **
42103 ** At most only the hash table containing pWal->hdr.mxFrame needs to be
42104 ** updated.  Any later hash tables will be automatically cleared when
42105 ** pWal->hdr.mxFrame advances to the point where those hash tables are
42106 ** actually needed.
42107 */
42108 static void walCleanupHash(Wal *pWal){
42109   volatile ht_slot *aHash = 0;    /* Pointer to hash table to clear */
42110   volatile u32 *aPgno = 0;        /* Page number array for hash table */
42111   u32 iZero = 0;                  /* frame == (aHash[x]+iZero) */
42112   int iLimit = 0;                 /* Zero values greater than this */
42113   int nByte;                      /* Number of bytes to zero in aPgno[] */
42114   int i;                          /* Used to iterate through aHash[] */
42115
42116   assert( pWal->writeLock );
42117   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
42118   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
42119   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
42120
42121   if( pWal->hdr.mxFrame==0 ) return;
42122
42123   /* Obtain pointers to the hash-table and page-number array containing 
42124   ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
42125   ** that the page said hash-table and array reside on is already mapped.
42126   */
42127   assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
42128   assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
42129   walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
42130
42131   /* Zero all hash-table entries that correspond to frame numbers greater
42132   ** than pWal->hdr.mxFrame.
42133   */
42134   iLimit = pWal->hdr.mxFrame - iZero;
42135   assert( iLimit>0 );
42136   for(i=0; i<HASHTABLE_NSLOT; i++){
42137     if( aHash[i]>iLimit ){
42138       aHash[i] = 0;
42139     }
42140   }
42141   
42142   /* Zero the entries in the aPgno array that correspond to frames with
42143   ** frame numbers greater than pWal->hdr.mxFrame. 
42144   */
42145   nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
42146   memset((void *)&aPgno[iLimit+1], 0, nByte);
42147
42148 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
42149   /* Verify that the every entry in the mapping region is still reachable
42150   ** via the hash table even after the cleanup.
42151   */
42152   if( iLimit ){
42153     int i;           /* Loop counter */
42154     int iKey;        /* Hash key */
42155     for(i=1; i<=iLimit; i++){
42156       for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
42157         if( aHash[iKey]==i ) break;
42158       }
42159       assert( aHash[iKey]==i );
42160     }
42161   }
42162 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
42163 }
42164
42165
42166 /*
42167 ** Set an entry in the wal-index that will map database page number
42168 ** pPage into WAL frame iFrame.
42169 */
42170 static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
42171   int rc;                         /* Return code */
42172   u32 iZero = 0;                  /* One less than frame number of aPgno[1] */
42173   volatile u32 *aPgno = 0;        /* Page number array */
42174   volatile ht_slot *aHash = 0;    /* Hash table */
42175
42176   rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
42177
42178   /* Assuming the wal-index file was successfully mapped, populate the
42179   ** page number array and hash table entry.
42180   */
42181   if( rc==SQLITE_OK ){
42182     int iKey;                     /* Hash table key */
42183     int idx;                      /* Value to write to hash-table slot */
42184     int nCollide;                 /* Number of hash collisions */
42185
42186     idx = iFrame - iZero;
42187     assert( idx <= HASHTABLE_NSLOT/2 + 1 );
42188     
42189     /* If this is the first entry to be added to this hash-table, zero the
42190     ** entire hash table and aPgno[] array before proceding. 
42191     */
42192     if( idx==1 ){
42193       int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
42194       memset((void*)&aPgno[1], 0, nByte);
42195     }
42196
42197     /* If the entry in aPgno[] is already set, then the previous writer
42198     ** must have exited unexpectedly in the middle of a transaction (after
42199     ** writing one or more dirty pages to the WAL to free up memory). 
42200     ** Remove the remnants of that writers uncommitted transaction from 
42201     ** the hash-table before writing any new entries.
42202     */
42203     if( aPgno[idx] ){
42204       walCleanupHash(pWal);
42205       assert( !aPgno[idx] );
42206     }
42207
42208     /* Write the aPgno[] array entry and the hash-table slot. */
42209     nCollide = idx;
42210     for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
42211       if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
42212     }
42213     aPgno[idx] = iPage;
42214     aHash[iKey] = (ht_slot)idx;
42215
42216 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
42217     /* Verify that the number of entries in the hash table exactly equals
42218     ** the number of entries in the mapping region.
42219     */
42220     {
42221       int i;           /* Loop counter */
42222       int nEntry = 0;  /* Number of entries in the hash table */
42223       for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
42224       assert( nEntry==idx );
42225     }
42226
42227     /* Verify that the every entry in the mapping region is reachable
42228     ** via the hash table.  This turns out to be a really, really expensive
42229     ** thing to check, so only do this occasionally - not on every
42230     ** iteration.
42231     */
42232     if( (idx&0x3ff)==0 ){
42233       int i;           /* Loop counter */
42234       for(i=1; i<=idx; i++){
42235         for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
42236           if( aHash[iKey]==i ) break;
42237         }
42238         assert( aHash[iKey]==i );
42239       }
42240     }
42241 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
42242   }
42243
42244
42245   return rc;
42246 }
42247
42248
42249 /*
42250 ** Recover the wal-index by reading the write-ahead log file. 
42251 **
42252 ** This routine first tries to establish an exclusive lock on the
42253 ** wal-index to prevent other threads/processes from doing anything
42254 ** with the WAL or wal-index while recovery is running.  The
42255 ** WAL_RECOVER_LOCK is also held so that other threads will know
42256 ** that this thread is running recovery.  If unable to establish
42257 ** the necessary locks, this routine returns SQLITE_BUSY.
42258 */
42259 static int walIndexRecover(Wal *pWal){
42260   int rc;                         /* Return Code */
42261   i64 nSize;                      /* Size of log file */
42262   u32 aFrameCksum[2] = {0, 0};
42263   int iLock;                      /* Lock offset to lock for checkpoint */
42264   int nLock;                      /* Number of locks to hold */
42265
42266   /* Obtain an exclusive lock on all byte in the locking range not already
42267   ** locked by the caller. The caller is guaranteed to have locked the
42268   ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
42269   ** If successful, the same bytes that are locked here are unlocked before
42270   ** this function returns.
42271   */
42272   assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
42273   assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
42274   assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
42275   assert( pWal->writeLock );
42276   iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
42277   nLock = SQLITE_SHM_NLOCK - iLock;
42278   rc = walLockExclusive(pWal, iLock, nLock);
42279   if( rc ){
42280     return rc;
42281   }
42282   WALTRACE(("WAL%p: recovery begin...\n", pWal));
42283
42284   memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
42285
42286   rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
42287   if( rc!=SQLITE_OK ){
42288     goto recovery_error;
42289   }
42290
42291   if( nSize>WAL_HDRSIZE ){
42292     u8 aBuf[WAL_HDRSIZE];         /* Buffer to load WAL header into */
42293     u8 *aFrame = 0;               /* Malloc'd buffer to load entire frame */
42294     int szFrame;                  /* Number of bytes in buffer aFrame[] */
42295     u8 *aData;                    /* Pointer to data part of aFrame buffer */
42296     int iFrame;                   /* Index of last frame read */
42297     i64 iOffset;                  /* Next offset to read from log file */
42298     int szPage;                   /* Page size according to the log */
42299     u32 magic;                    /* Magic value read from WAL header */
42300     u32 version;                  /* Magic value read from WAL header */
42301
42302     /* Read in the WAL header. */
42303     rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
42304     if( rc!=SQLITE_OK ){
42305       goto recovery_error;
42306     }
42307
42308     /* If the database page size is not a power of two, or is greater than
42309     ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid 
42310     ** data. Similarly, if the 'magic' value is invalid, ignore the whole
42311     ** WAL file.
42312     */
42313     magic = sqlite3Get4byte(&aBuf[0]);
42314     szPage = sqlite3Get4byte(&aBuf[8]);
42315     if( (magic&0xFFFFFFFE)!=WAL_MAGIC 
42316      || szPage&(szPage-1) 
42317      || szPage>SQLITE_MAX_PAGE_SIZE 
42318      || szPage<512 
42319     ){
42320       goto finished;
42321     }
42322     pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
42323     pWal->szPage = szPage;
42324     pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
42325     memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
42326
42327     /* Verify that the WAL header checksum is correct */
42328     walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN, 
42329         aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
42330     );
42331     if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
42332      || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
42333     ){
42334       goto finished;
42335     }
42336
42337     /* Verify that the version number on the WAL format is one that
42338     ** are able to understand */
42339     version = sqlite3Get4byte(&aBuf[4]);
42340     if( version!=WAL_MAX_VERSION ){
42341       rc = SQLITE_CANTOPEN_BKPT;
42342       goto finished;
42343     }
42344
42345     /* Malloc a buffer to read frames into. */
42346     szFrame = szPage + WAL_FRAME_HDRSIZE;
42347     aFrame = (u8 *)sqlite3_malloc(szFrame);
42348     if( !aFrame ){
42349       rc = SQLITE_NOMEM;
42350       goto recovery_error;
42351     }
42352     aData = &aFrame[WAL_FRAME_HDRSIZE];
42353
42354     /* Read all frames from the log file. */
42355     iFrame = 0;
42356     for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
42357       u32 pgno;                   /* Database page number for frame */
42358       u32 nTruncate;              /* dbsize field from frame header */
42359       int isValid;                /* True if this frame is valid */
42360
42361       /* Read and decode the next log frame. */
42362       rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
42363       if( rc!=SQLITE_OK ) break;
42364       isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
42365       if( !isValid ) break;
42366       rc = walIndexAppend(pWal, ++iFrame, pgno);
42367       if( rc!=SQLITE_OK ) break;
42368
42369       /* If nTruncate is non-zero, this is a commit record. */
42370       if( nTruncate ){
42371         pWal->hdr.mxFrame = iFrame;
42372         pWal->hdr.nPage = nTruncate;
42373         pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
42374         testcase( szPage<=32768 );
42375         testcase( szPage>=65536 );
42376         aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
42377         aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
42378       }
42379     }
42380
42381     sqlite3_free(aFrame);
42382   }
42383
42384 finished:
42385   if( rc==SQLITE_OK ){
42386     volatile WalCkptInfo *pInfo;
42387     int i;
42388     pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
42389     pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
42390     walIndexWriteHdr(pWal);
42391
42392     /* Reset the checkpoint-header. This is safe because this thread is 
42393     ** currently holding locks that exclude all other readers, writers and
42394     ** checkpointers.
42395     */
42396     pInfo = walCkptInfo(pWal);
42397     pInfo->nBackfill = 0;
42398     pInfo->aReadMark[0] = 0;
42399     for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
42400
42401     /* If more than one frame was recovered from the log file, report an
42402     ** event via sqlite3_log(). This is to help with identifying performance
42403     ** problems caused by applications routinely shutting down without
42404     ** checkpointing the log file.
42405     */
42406     if( pWal->hdr.nPage ){
42407       sqlite3_log(SQLITE_OK, "Recovered %d frames from WAL file %s",
42408           pWal->hdr.nPage, pWal->zWalName
42409       );
42410     }
42411   }
42412
42413 recovery_error:
42414   WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
42415   walUnlockExclusive(pWal, iLock, nLock);
42416   return rc;
42417 }
42418
42419 /*
42420 ** Close an open wal-index.
42421 */
42422 static void walIndexClose(Wal *pWal, int isDelete){
42423   sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
42424 }
42425
42426 /* 
42427 ** Open a connection to the WAL file zWalName. The database file must 
42428 ** already be opened on connection pDbFd. The buffer that zWalName points
42429 ** to must remain valid for the lifetime of the returned Wal* handle.
42430 **
42431 ** A SHARED lock should be held on the database file when this function
42432 ** is called. The purpose of this SHARED lock is to prevent any other
42433 ** client from unlinking the WAL or wal-index file. If another process
42434 ** were to do this just after this client opened one of these files, the
42435 ** system would be badly broken.
42436 **
42437 ** If the log file is successfully opened, SQLITE_OK is returned and 
42438 ** *ppWal is set to point to a new WAL handle. If an error occurs,
42439 ** an SQLite error code is returned and *ppWal is left unmodified.
42440 */
42441 SQLITE_PRIVATE int sqlite3WalOpen(
42442   sqlite3_vfs *pVfs,              /* vfs module to open wal and wal-index */
42443   sqlite3_file *pDbFd,            /* The open database file */
42444   const char *zWalName,           /* Name of the WAL file */
42445   Wal **ppWal                     /* OUT: Allocated Wal handle */
42446 ){
42447   int rc;                         /* Return Code */
42448   Wal *pRet;                      /* Object to allocate and return */
42449   int flags;                      /* Flags passed to OsOpen() */
42450
42451   assert( zWalName && zWalName[0] );
42452   assert( pDbFd );
42453
42454   /* In the amalgamation, the os_unix.c and os_win.c source files come before
42455   ** this source file.  Verify that the #defines of the locking byte offsets
42456   ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
42457   */
42458 #ifdef WIN_SHM_BASE
42459   assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
42460 #endif
42461 #ifdef UNIX_SHM_BASE
42462   assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
42463 #endif
42464
42465
42466   /* Allocate an instance of struct Wal to return. */
42467   *ppWal = 0;
42468   pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
42469   if( !pRet ){
42470     return SQLITE_NOMEM;
42471   }
42472
42473   pRet->pVfs = pVfs;
42474   pRet->pWalFd = (sqlite3_file *)&pRet[1];
42475   pRet->pDbFd = pDbFd;
42476   pRet->readLock = -1;
42477   pRet->zWalName = zWalName;
42478
42479   /* Open file handle on the write-ahead log file. */
42480   flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
42481   rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
42482   if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
42483     pRet->readOnly = 1;
42484   }
42485
42486   if( rc!=SQLITE_OK ){
42487     walIndexClose(pRet, 0);
42488     sqlite3OsClose(pRet->pWalFd);
42489     sqlite3_free(pRet);
42490   }else{
42491     *ppWal = pRet;
42492     WALTRACE(("WAL%d: opened\n", pRet));
42493   }
42494   return rc;
42495 }
42496
42497 /*
42498 ** Find the smallest page number out of all pages held in the WAL that
42499 ** has not been returned by any prior invocation of this method on the
42500 ** same WalIterator object.   Write into *piFrame the frame index where
42501 ** that page was last written into the WAL.  Write into *piPage the page
42502 ** number.
42503 **
42504 ** Return 0 on success.  If there are no pages in the WAL with a page
42505 ** number larger than *piPage, then return 1.
42506 */
42507 static int walIteratorNext(
42508   WalIterator *p,               /* Iterator */
42509   u32 *piPage,                  /* OUT: The page number of the next page */
42510   u32 *piFrame                  /* OUT: Wal frame index of next page */
42511 ){
42512   u32 iMin;                     /* Result pgno must be greater than iMin */
42513   u32 iRet = 0xFFFFFFFF;        /* 0xffffffff is never a valid page number */
42514   int i;                        /* For looping through segments */
42515
42516   iMin = p->iPrior;
42517   assert( iMin<0xffffffff );
42518   for(i=p->nSegment-1; i>=0; i--){
42519     struct WalSegment *pSegment = &p->aSegment[i];
42520     while( pSegment->iNext<pSegment->nEntry ){
42521       u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
42522       if( iPg>iMin ){
42523         if( iPg<iRet ){
42524           iRet = iPg;
42525           *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
42526         }
42527         break;
42528       }
42529       pSegment->iNext++;
42530     }
42531   }
42532
42533   *piPage = p->iPrior = iRet;
42534   return (iRet==0xFFFFFFFF);
42535 }
42536
42537 /*
42538 ** This function merges two sorted lists into a single sorted list.
42539 */
42540 static void walMerge(
42541   u32 *aContent,                  /* Pages in wal */
42542   ht_slot *aLeft,                 /* IN: Left hand input list */
42543   int nLeft,                      /* IN: Elements in array *paLeft */
42544   ht_slot **paRight,              /* IN/OUT: Right hand input list */
42545   int *pnRight,                   /* IN/OUT: Elements in *paRight */
42546   ht_slot *aTmp                   /* Temporary buffer */
42547 ){
42548   int iLeft = 0;                  /* Current index in aLeft */
42549   int iRight = 0;                 /* Current index in aRight */
42550   int iOut = 0;                   /* Current index in output buffer */
42551   int nRight = *pnRight;
42552   ht_slot *aRight = *paRight;
42553
42554   assert( nLeft>0 && nRight>0 );
42555   while( iRight<nRight || iLeft<nLeft ){
42556     ht_slot logpage;
42557     Pgno dbpage;
42558
42559     if( (iLeft<nLeft) 
42560      && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
42561     ){
42562       logpage = aLeft[iLeft++];
42563     }else{
42564       logpage = aRight[iRight++];
42565     }
42566     dbpage = aContent[logpage];
42567
42568     aTmp[iOut++] = logpage;
42569     if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
42570
42571     assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
42572     assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
42573   }
42574
42575   *paRight = aLeft;
42576   *pnRight = iOut;
42577   memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
42578 }
42579
42580 /*
42581 ** Sort the elements in list aList, removing any duplicates.
42582 */
42583 static void walMergesort(
42584   u32 *aContent,                  /* Pages in wal */
42585   ht_slot *aBuffer,               /* Buffer of at least *pnList items to use */
42586   ht_slot *aList,                 /* IN/OUT: List to sort */
42587   int *pnList                     /* IN/OUT: Number of elements in aList[] */
42588 ){
42589   struct Sublist {
42590     int nList;                    /* Number of elements in aList */
42591     ht_slot *aList;               /* Pointer to sub-list content */
42592   };
42593
42594   const int nList = *pnList;      /* Size of input list */
42595   int nMerge = 0;                 /* Number of elements in list aMerge */
42596   ht_slot *aMerge = 0;            /* List to be merged */
42597   int iList;                      /* Index into input list */
42598   int iSub = 0;                   /* Index into aSub array */
42599   struct Sublist aSub[13];        /* Array of sub-lists */
42600
42601   memset(aSub, 0, sizeof(aSub));
42602   assert( nList<=HASHTABLE_NPAGE && nList>0 );
42603   assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
42604
42605   for(iList=0; iList<nList; iList++){
42606     nMerge = 1;
42607     aMerge = &aList[iList];
42608     for(iSub=0; iList & (1<<iSub); iSub++){
42609       struct Sublist *p = &aSub[iSub];
42610       assert( p->aList && p->nList<=(1<<iSub) );
42611       assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
42612       walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
42613     }
42614     aSub[iSub].aList = aMerge;
42615     aSub[iSub].nList = nMerge;
42616   }
42617
42618   for(iSub++; iSub<ArraySize(aSub); iSub++){
42619     if( nList & (1<<iSub) ){
42620       struct Sublist *p = &aSub[iSub];
42621       assert( p->nList<=(1<<iSub) );
42622       assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
42623       walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
42624     }
42625   }
42626   assert( aMerge==aList );
42627   *pnList = nMerge;
42628
42629 #ifdef SQLITE_DEBUG
42630   {
42631     int i;
42632     for(i=1; i<*pnList; i++){
42633       assert( aContent[aList[i]] > aContent[aList[i-1]] );
42634     }
42635   }
42636 #endif
42637 }
42638
42639 /* 
42640 ** Free an iterator allocated by walIteratorInit().
42641 */
42642 static void walIteratorFree(WalIterator *p){
42643   sqlite3ScratchFree(p);
42644 }
42645
42646 /*
42647 ** Construct a WalInterator object that can be used to loop over all 
42648 ** pages in the WAL in ascending order. The caller must hold the checkpoint
42649 **
42650 ** On success, make *pp point to the newly allocated WalInterator object
42651 ** return SQLITE_OK. Otherwise, return an error code. If this routine
42652 ** returns an error, the value of *pp is undefined.
42653 **
42654 ** The calling routine should invoke walIteratorFree() to destroy the
42655 ** WalIterator object when it has finished with it.
42656 */
42657 static int walIteratorInit(Wal *pWal, WalIterator **pp){
42658   WalIterator *p;                 /* Return value */
42659   int nSegment;                   /* Number of segments to merge */
42660   u32 iLast;                      /* Last frame in log */
42661   int nByte;                      /* Number of bytes to allocate */
42662   int i;                          /* Iterator variable */
42663   ht_slot *aTmp;                  /* Temp space used by merge-sort */
42664   int rc = SQLITE_OK;             /* Return Code */
42665
42666   /* This routine only runs while holding the checkpoint lock. And
42667   ** it only runs if there is actually content in the log (mxFrame>0).
42668   */
42669   assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
42670   iLast = pWal->hdr.mxFrame;
42671
42672   /* Allocate space for the WalIterator object. */
42673   nSegment = walFramePage(iLast) + 1;
42674   nByte = sizeof(WalIterator) 
42675         + (nSegment-1)*sizeof(struct WalSegment)
42676         + iLast*sizeof(ht_slot);
42677   p = (WalIterator *)sqlite3ScratchMalloc(nByte);
42678   if( !p ){
42679     return SQLITE_NOMEM;
42680   }
42681   memset(p, 0, nByte);
42682   p->nSegment = nSegment;
42683
42684   /* Allocate temporary space used by the merge-sort routine. This block
42685   ** of memory will be freed before this function returns.
42686   */
42687   aTmp = (ht_slot *)sqlite3ScratchMalloc(
42688       sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
42689   );
42690   if( !aTmp ){
42691     rc = SQLITE_NOMEM;
42692   }
42693
42694   for(i=0; rc==SQLITE_OK && i<nSegment; i++){
42695     volatile ht_slot *aHash;
42696     u32 iZero;
42697     volatile u32 *aPgno;
42698
42699     rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
42700     if( rc==SQLITE_OK ){
42701       int j;                      /* Counter variable */
42702       int nEntry;                 /* Number of entries in this segment */
42703       ht_slot *aIndex;            /* Sorted index for this segment */
42704
42705       aPgno++;
42706       if( (i+1)==nSegment ){
42707         nEntry = (int)(iLast - iZero);
42708       }else{
42709         nEntry = (int)((u32*)aHash - (u32*)aPgno);
42710       }
42711       aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
42712       iZero++;
42713   
42714       for(j=0; j<nEntry; j++){
42715         aIndex[j] = (ht_slot)j;
42716       }
42717       walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
42718       p->aSegment[i].iZero = iZero;
42719       p->aSegment[i].nEntry = nEntry;
42720       p->aSegment[i].aIndex = aIndex;
42721       p->aSegment[i].aPgno = (u32 *)aPgno;
42722     }
42723   }
42724   sqlite3ScratchFree(aTmp);
42725
42726   if( rc!=SQLITE_OK ){
42727     walIteratorFree(p);
42728   }
42729   *pp = p;
42730   return rc;
42731 }
42732
42733 /*
42734 ** Copy as much content as we can from the WAL back into the database file
42735 ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
42736 **
42737 ** The amount of information copies from WAL to database might be limited
42738 ** by active readers.  This routine will never overwrite a database page
42739 ** that a concurrent reader might be using.
42740 **
42741 ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
42742 ** SQLite is in WAL-mode in synchronous=NORMAL.  That means that if 
42743 ** checkpoints are always run by a background thread or background 
42744 ** process, foreground threads will never block on a lengthy fsync call.
42745 **
42746 ** Fsync is called on the WAL before writing content out of the WAL and
42747 ** into the database.  This ensures that if the new content is persistent
42748 ** in the WAL and can be recovered following a power-loss or hard reset.
42749 **
42750 ** Fsync is also called on the database file if (and only if) the entire
42751 ** WAL content is copied into the database file.  This second fsync makes
42752 ** it safe to delete the WAL since the new content will persist in the
42753 ** database file.
42754 **
42755 ** This routine uses and updates the nBackfill field of the wal-index header.
42756 ** This is the only routine tha will increase the value of nBackfill.  
42757 ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
42758 ** its value.)
42759 **
42760 ** The caller must be holding sufficient locks to ensure that no other
42761 ** checkpoint is running (in any other thread or process) at the same
42762 ** time.
42763 */
42764 static int walCheckpoint(
42765   Wal *pWal,                      /* Wal connection */
42766   int sync_flags,                 /* Flags for OsSync() (or 0) */
42767   int nBuf,                       /* Size of zBuf in bytes */
42768   u8 *zBuf                        /* Temporary buffer to use */
42769 ){
42770   int rc;                         /* Return code */
42771   int szPage;                     /* Database page-size */
42772   WalIterator *pIter = 0;         /* Wal iterator context */
42773   u32 iDbpage = 0;                /* Next database page to write */
42774   u32 iFrame = 0;                 /* Wal frame containing data for iDbpage */
42775   u32 mxSafeFrame;                /* Max frame that can be backfilled */
42776   u32 mxPage;                     /* Max database page to write */
42777   int i;                          /* Loop counter */
42778   volatile WalCkptInfo *pInfo;    /* The checkpoint status information */
42779
42780   szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
42781   testcase( szPage<=32768 );
42782   testcase( szPage>=65536 );
42783   if( pWal->hdr.mxFrame==0 ) return SQLITE_OK;
42784
42785   /* Allocate the iterator */
42786   rc = walIteratorInit(pWal, &pIter);
42787   if( rc!=SQLITE_OK ){
42788     return rc;
42789   }
42790   assert( pIter );
42791
42792   /*** TODO:  Move this test out to the caller.  Make it an assert() here ***/
42793   if( szPage!=nBuf ){
42794     rc = SQLITE_CORRUPT_BKPT;
42795     goto walcheckpoint_out;
42796   }
42797
42798   /* Compute in mxSafeFrame the index of the last frame of the WAL that is
42799   ** safe to write into the database.  Frames beyond mxSafeFrame might
42800   ** overwrite database pages that are in use by active readers and thus
42801   ** cannot be backfilled from the WAL.
42802   */
42803   mxSafeFrame = pWal->hdr.mxFrame;
42804   mxPage = pWal->hdr.nPage;
42805   pInfo = walCkptInfo(pWal);
42806   for(i=1; i<WAL_NREADER; i++){
42807     u32 y = pInfo->aReadMark[i];
42808     if( mxSafeFrame>=y ){
42809       assert( y<=pWal->hdr.mxFrame );
42810       rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
42811       if( rc==SQLITE_OK ){
42812         pInfo->aReadMark[i] = READMARK_NOT_USED;
42813         walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
42814       }else if( rc==SQLITE_BUSY ){
42815         mxSafeFrame = y;
42816       }else{
42817         goto walcheckpoint_out;
42818       }
42819     }
42820   }
42821
42822   if( pInfo->nBackfill<mxSafeFrame
42823    && (rc = walLockExclusive(pWal, WAL_READ_LOCK(0), 1))==SQLITE_OK
42824   ){
42825     i64 nSize;                    /* Current size of database file */
42826     u32 nBackfill = pInfo->nBackfill;
42827
42828     /* Sync the WAL to disk */
42829     if( sync_flags ){
42830       rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
42831     }
42832
42833     /* If the database file may grow as a result of this checkpoint, hint
42834     ** about the eventual size of the db file to the VFS layer. 
42835     */
42836     if( rc==SQLITE_OK ){
42837       i64 nReq = ((i64)mxPage * szPage);
42838       rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
42839       if( rc==SQLITE_OK && nSize<nReq ){
42840         sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
42841       }
42842     }
42843
42844     /* Iterate through the contents of the WAL, copying data to the db file. */
42845     while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
42846       i64 iOffset;
42847       assert( walFramePgno(pWal, iFrame)==iDbpage );
42848       if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ) continue;
42849       iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
42850       /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
42851       rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
42852       if( rc!=SQLITE_OK ) break;
42853       iOffset = (iDbpage-1)*(i64)szPage;
42854       testcase( IS_BIG_INT(iOffset) );
42855       rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
42856       if( rc!=SQLITE_OK ) break;
42857     }
42858
42859     /* If work was actually accomplished... */
42860     if( rc==SQLITE_OK ){
42861       if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
42862         i64 szDb = pWal->hdr.nPage*(i64)szPage;
42863         testcase( IS_BIG_INT(szDb) );
42864         rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
42865         if( rc==SQLITE_OK && sync_flags ){
42866           rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
42867         }
42868       }
42869       if( rc==SQLITE_OK ){
42870         pInfo->nBackfill = mxSafeFrame;
42871       }
42872     }
42873
42874     /* Release the reader lock held while backfilling */
42875     walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
42876   }else if( rc==SQLITE_BUSY ){
42877     /* Reset the return code so as not to report a checkpoint failure
42878     ** just because active readers prevent any backfill.
42879     */
42880     rc = SQLITE_OK;
42881   }
42882
42883  walcheckpoint_out:
42884   walIteratorFree(pIter);
42885   return rc;
42886 }
42887
42888 /*
42889 ** Close a connection to a log file.
42890 */
42891 SQLITE_PRIVATE int sqlite3WalClose(
42892   Wal *pWal,                      /* Wal to close */
42893   int sync_flags,                 /* Flags to pass to OsSync() (or 0) */
42894   int nBuf,
42895   u8 *zBuf                        /* Buffer of at least nBuf bytes */
42896 ){
42897   int rc = SQLITE_OK;
42898   if( pWal ){
42899     int isDelete = 0;             /* True to unlink wal and wal-index files */
42900
42901     /* If an EXCLUSIVE lock can be obtained on the database file (using the
42902     ** ordinary, rollback-mode locking methods, this guarantees that the
42903     ** connection associated with this log file is the only connection to
42904     ** the database. In this case checkpoint the database and unlink both
42905     ** the wal and wal-index files.
42906     **
42907     ** The EXCLUSIVE lock is not released before returning.
42908     */
42909     rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
42910     if( rc==SQLITE_OK ){
42911       pWal->exclusiveMode = 1;
42912       rc = sqlite3WalCheckpoint(pWal, sync_flags, nBuf, zBuf);
42913       if( rc==SQLITE_OK ){
42914         isDelete = 1;
42915       }
42916     }
42917
42918     walIndexClose(pWal, isDelete);
42919     sqlite3OsClose(pWal->pWalFd);
42920     if( isDelete ){
42921       sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
42922     }
42923     WALTRACE(("WAL%p: closed\n", pWal));
42924     sqlite3_free((void *)pWal->apWiData);
42925     sqlite3_free(pWal);
42926   }
42927   return rc;
42928 }
42929
42930 /*
42931 ** Try to read the wal-index header.  Return 0 on success and 1 if
42932 ** there is a problem.
42933 **
42934 ** The wal-index is in shared memory.  Another thread or process might
42935 ** be writing the header at the same time this procedure is trying to
42936 ** read it, which might result in inconsistency.  A dirty read is detected
42937 ** by verifying that both copies of the header are the same and also by
42938 ** a checksum on the header.
42939 **
42940 ** If and only if the read is consistent and the header is different from
42941 ** pWal->hdr, then pWal->hdr is updated to the content of the new header
42942 ** and *pChanged is set to 1.
42943 **
42944 ** If the checksum cannot be verified return non-zero. If the header
42945 ** is read successfully and the checksum verified, return zero.
42946 */
42947 static int walIndexTryHdr(Wal *pWal, int *pChanged){
42948   u32 aCksum[2];                  /* Checksum on the header content */
42949   WalIndexHdr h1, h2;             /* Two copies of the header content */
42950   WalIndexHdr volatile *aHdr;     /* Header in shared memory */
42951
42952   /* The first page of the wal-index must be mapped at this point. */
42953   assert( pWal->nWiData>0 && pWal->apWiData[0] );
42954
42955   /* Read the header. This might happen concurrently with a write to the
42956   ** same area of shared memory on a different CPU in a SMP,
42957   ** meaning it is possible that an inconsistent snapshot is read
42958   ** from the file. If this happens, return non-zero.
42959   **
42960   ** There are two copies of the header at the beginning of the wal-index.
42961   ** When reading, read [0] first then [1].  Writes are in the reverse order.
42962   ** Memory barriers are used to prevent the compiler or the hardware from
42963   ** reordering the reads and writes.
42964   */
42965   aHdr = walIndexHdr(pWal);
42966   memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
42967   sqlite3OsShmBarrier(pWal->pDbFd);
42968   memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
42969
42970   if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
42971     return 1;   /* Dirty read */
42972   }  
42973   if( h1.isInit==0 ){
42974     return 1;   /* Malformed header - probably all zeros */
42975   }
42976   walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
42977   if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
42978     return 1;   /* Checksum does not match */
42979   }
42980
42981   if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
42982     *pChanged = 1;
42983     memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
42984     pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
42985     testcase( pWal->szPage<=32768 );
42986     testcase( pWal->szPage>=65536 );
42987   }
42988
42989   /* The header was successfully read. Return zero. */
42990   return 0;
42991 }
42992
42993 /*
42994 ** Read the wal-index header from the wal-index and into pWal->hdr.
42995 ** If the wal-header appears to be corrupt, try to reconstruct the
42996 ** wal-index from the WAL before returning.
42997 **
42998 ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
42999 ** changed by this opertion.  If pWal->hdr is unchanged, set *pChanged
43000 ** to 0.
43001 **
43002 ** If the wal-index header is successfully read, return SQLITE_OK. 
43003 ** Otherwise an SQLite error code.
43004 */
43005 static int walIndexReadHdr(Wal *pWal, int *pChanged){
43006   int rc;                         /* Return code */
43007   int badHdr;                     /* True if a header read failed */
43008   volatile u32 *page0;            /* Chunk of wal-index containing header */
43009
43010   /* Ensure that page 0 of the wal-index (the page that contains the 
43011   ** wal-index header) is mapped. Return early if an error occurs here.
43012   */
43013   assert( pChanged );
43014   rc = walIndexPage(pWal, 0, &page0);
43015   if( rc!=SQLITE_OK ){
43016     return rc;
43017   };
43018   assert( page0 || pWal->writeLock==0 );
43019
43020   /* If the first page of the wal-index has been mapped, try to read the
43021   ** wal-index header immediately, without holding any lock. This usually
43022   ** works, but may fail if the wal-index header is corrupt or currently 
43023   ** being modified by another thread or process.
43024   */
43025   badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
43026
43027   /* If the first attempt failed, it might have been due to a race
43028   ** with a writer.  So get a WRITE lock and try again.
43029   */
43030   assert( badHdr==0 || pWal->writeLock==0 );
43031   if( badHdr && SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
43032     pWal->writeLock = 1;
43033     if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
43034       badHdr = walIndexTryHdr(pWal, pChanged);
43035       if( badHdr ){
43036         /* If the wal-index header is still malformed even while holding
43037         ** a WRITE lock, it can only mean that the header is corrupted and
43038         ** needs to be reconstructed.  So run recovery to do exactly that.
43039         */
43040         rc = walIndexRecover(pWal);
43041         *pChanged = 1;
43042       }
43043     }
43044     pWal->writeLock = 0;
43045     walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
43046   }
43047
43048   /* If the header is read successfully, check the version number to make
43049   ** sure the wal-index was not constructed with some future format that
43050   ** this version of SQLite cannot understand.
43051   */
43052   if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
43053     rc = SQLITE_CANTOPEN_BKPT;
43054   }
43055
43056   return rc;
43057 }
43058
43059 /*
43060 ** This is the value that walTryBeginRead returns when it needs to
43061 ** be retried.
43062 */
43063 #define WAL_RETRY  (-1)
43064
43065 /*
43066 ** Attempt to start a read transaction.  This might fail due to a race or
43067 ** other transient condition.  When that happens, it returns WAL_RETRY to
43068 ** indicate to the caller that it is safe to retry immediately.
43069 **
43070 ** On success return SQLITE_OK.  On a permanent failure (such an
43071 ** I/O error or an SQLITE_BUSY because another process is running
43072 ** recovery) return a positive error code.
43073 **
43074 ** The useWal parameter is true to force the use of the WAL and disable
43075 ** the case where the WAL is bypassed because it has been completely
43076 ** checkpointed.  If useWal==0 then this routine calls walIndexReadHdr() 
43077 ** to make a copy of the wal-index header into pWal->hdr.  If the 
43078 ** wal-index header has changed, *pChanged is set to 1 (as an indication 
43079 ** to the caller that the local paget cache is obsolete and needs to be 
43080 ** flushed.)  When useWal==1, the wal-index header is assumed to already
43081 ** be loaded and the pChanged parameter is unused.
43082 **
43083 ** The caller must set the cnt parameter to the number of prior calls to
43084 ** this routine during the current read attempt that returned WAL_RETRY.
43085 ** This routine will start taking more aggressive measures to clear the
43086 ** race conditions after multiple WAL_RETRY returns, and after an excessive
43087 ** number of errors will ultimately return SQLITE_PROTOCOL.  The
43088 ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
43089 ** and is not honoring the locking protocol.  There is a vanishingly small
43090 ** chance that SQLITE_PROTOCOL could be returned because of a run of really
43091 ** bad luck when there is lots of contention for the wal-index, but that
43092 ** possibility is so small that it can be safely neglected, we believe.
43093 **
43094 ** On success, this routine obtains a read lock on 
43095 ** WAL_READ_LOCK(pWal->readLock).  The pWal->readLock integer is
43096 ** in the range 0 <= pWal->readLock < WAL_NREADER.  If pWal->readLock==(-1)
43097 ** that means the Wal does not hold any read lock.  The reader must not
43098 ** access any database page that is modified by a WAL frame up to and
43099 ** including frame number aReadMark[pWal->readLock].  The reader will
43100 ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
43101 ** Or if pWal->readLock==0, then the reader will ignore the WAL
43102 ** completely and get all content directly from the database file.
43103 ** If the useWal parameter is 1 then the WAL will never be ignored and
43104 ** this routine will always set pWal->readLock>0 on success.
43105 ** When the read transaction is completed, the caller must release the
43106 ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
43107 **
43108 ** This routine uses the nBackfill and aReadMark[] fields of the header
43109 ** to select a particular WAL_READ_LOCK() that strives to let the
43110 ** checkpoint process do as much work as possible.  This routine might
43111 ** update values of the aReadMark[] array in the header, but if it does
43112 ** so it takes care to hold an exclusive lock on the corresponding
43113 ** WAL_READ_LOCK() while changing values.
43114 */
43115 static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
43116   volatile WalCkptInfo *pInfo;    /* Checkpoint information in wal-index */
43117   u32 mxReadMark;                 /* Largest aReadMark[] value */
43118   int mxI;                        /* Index of largest aReadMark[] value */
43119   int i;                          /* Loop counter */
43120   int rc = SQLITE_OK;             /* Return code  */
43121
43122   assert( pWal->readLock<0 );     /* Not currently locked */
43123
43124   /* Take steps to avoid spinning forever if there is a protocol error. */
43125   if( cnt>5 ){
43126     if( cnt>100 ) return SQLITE_PROTOCOL;
43127     sqlite3OsSleep(pWal->pVfs, 1);
43128   }
43129
43130   if( !useWal ){
43131     rc = walIndexReadHdr(pWal, pChanged);
43132     if( rc==SQLITE_BUSY ){
43133       /* If there is not a recovery running in another thread or process
43134       ** then convert BUSY errors to WAL_RETRY.  If recovery is known to
43135       ** be running, convert BUSY to BUSY_RECOVERY.  There is a race here
43136       ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
43137       ** would be technically correct.  But the race is benign since with
43138       ** WAL_RETRY this routine will be called again and will probably be
43139       ** right on the second iteration.
43140       */
43141       if( pWal->apWiData[0]==0 ){
43142         /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
43143         ** We assume this is a transient condition, so return WAL_RETRY. The
43144         ** xShmMap() implementation used by the default unix and win32 VFS 
43145         ** modules may return SQLITE_BUSY due to a race condition in the 
43146         ** code that determines whether or not the shared-memory region 
43147         ** must be zeroed before the requested page is returned.
43148         */
43149         rc = WAL_RETRY;
43150       }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
43151         walUnlockShared(pWal, WAL_RECOVER_LOCK);
43152         rc = WAL_RETRY;
43153       }else if( rc==SQLITE_BUSY ){
43154         rc = SQLITE_BUSY_RECOVERY;
43155       }
43156     }
43157     if( rc!=SQLITE_OK ){
43158       return rc;
43159     }
43160   }
43161
43162   pInfo = walCkptInfo(pWal);
43163   if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame ){
43164     /* The WAL has been completely backfilled (or it is empty).
43165     ** and can be safely ignored.
43166     */
43167     rc = walLockShared(pWal, WAL_READ_LOCK(0));
43168     sqlite3OsShmBarrier(pWal->pDbFd);
43169     if( rc==SQLITE_OK ){
43170       if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
43171         /* It is not safe to allow the reader to continue here if frames
43172         ** may have been appended to the log before READ_LOCK(0) was obtained.
43173         ** When holding READ_LOCK(0), the reader ignores the entire log file,
43174         ** which implies that the database file contains a trustworthy
43175         ** snapshoT. Since holding READ_LOCK(0) prevents a checkpoint from
43176         ** happening, this is usually correct.
43177         **
43178         ** However, if frames have been appended to the log (or if the log 
43179         ** is wrapped and written for that matter) before the READ_LOCK(0)
43180         ** is obtained, that is not necessarily true. A checkpointer may
43181         ** have started to backfill the appended frames but crashed before
43182         ** it finished. Leaving a corrupt image in the database file.
43183         */
43184         walUnlockShared(pWal, WAL_READ_LOCK(0));
43185         return WAL_RETRY;
43186       }
43187       pWal->readLock = 0;
43188       return SQLITE_OK;
43189     }else if( rc!=SQLITE_BUSY ){
43190       return rc;
43191     }
43192   }
43193
43194   /* If we get this far, it means that the reader will want to use
43195   ** the WAL to get at content from recent commits.  The job now is
43196   ** to select one of the aReadMark[] entries that is closest to
43197   ** but not exceeding pWal->hdr.mxFrame and lock that entry.
43198   */
43199   mxReadMark = 0;
43200   mxI = 0;
43201   for(i=1; i<WAL_NREADER; i++){
43202     u32 thisMark = pInfo->aReadMark[i];
43203     if( mxReadMark<=thisMark && thisMark<=pWal->hdr.mxFrame ){
43204       assert( thisMark!=READMARK_NOT_USED );
43205       mxReadMark = thisMark;
43206       mxI = i;
43207     }
43208   }
43209   if( mxI==0 ){
43210     /* If we get here, it means that all of the aReadMark[] entries between
43211     ** 1 and WAL_NREADER-1 are zero.  Try to initialize aReadMark[1] to
43212     ** be mxFrame, then retry.
43213     */
43214     rc = walLockExclusive(pWal, WAL_READ_LOCK(1), 1);
43215     if( rc==SQLITE_OK ){
43216       pInfo->aReadMark[1] = pWal->hdr.mxFrame;
43217       walUnlockExclusive(pWal, WAL_READ_LOCK(1), 1);
43218       rc = WAL_RETRY;
43219     }else if( rc==SQLITE_BUSY ){
43220       rc = WAL_RETRY;
43221     }
43222     return rc;
43223   }else{
43224     if( mxReadMark < pWal->hdr.mxFrame ){
43225       for(i=1; i<WAL_NREADER; i++){
43226         rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
43227         if( rc==SQLITE_OK ){
43228           mxReadMark = pInfo->aReadMark[i] = pWal->hdr.mxFrame;
43229           mxI = i;
43230           walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
43231           break;
43232         }else if( rc!=SQLITE_BUSY ){
43233           return rc;
43234         }
43235       }
43236     }
43237
43238     rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
43239     if( rc ){
43240       return rc==SQLITE_BUSY ? WAL_RETRY : rc;
43241     }
43242     /* Now that the read-lock has been obtained, check that neither the
43243     ** value in the aReadMark[] array or the contents of the wal-index
43244     ** header have changed.
43245     **
43246     ** It is necessary to check that the wal-index header did not change
43247     ** between the time it was read and when the shared-lock was obtained
43248     ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
43249     ** that the log file may have been wrapped by a writer, or that frames
43250     ** that occur later in the log than pWal->hdr.mxFrame may have been
43251     ** copied into the database by a checkpointer. If either of these things
43252     ** happened, then reading the database with the current value of
43253     ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
43254     ** instead.
43255     **
43256     ** This does not guarantee that the copy of the wal-index header is up to
43257     ** date before proceeding. That would not be possible without somehow
43258     ** blocking writers. It only guarantees that a dangerous checkpoint or 
43259     ** log-wrap (either of which would require an exclusive lock on
43260     ** WAL_READ_LOCK(mxI)) has not occurred since the snapshot was valid.
43261     */
43262     sqlite3OsShmBarrier(pWal->pDbFd);
43263     if( pInfo->aReadMark[mxI]!=mxReadMark
43264      || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
43265     ){
43266       walUnlockShared(pWal, WAL_READ_LOCK(mxI));
43267       return WAL_RETRY;
43268     }else{
43269       assert( mxReadMark<=pWal->hdr.mxFrame );
43270       pWal->readLock = (i16)mxI;
43271     }
43272   }
43273   return rc;
43274 }
43275
43276 /*
43277 ** Begin a read transaction on the database.
43278 **
43279 ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
43280 ** it takes a snapshot of the state of the WAL and wal-index for the current
43281 ** instant in time.  The current thread will continue to use this snapshot.
43282 ** Other threads might append new content to the WAL and wal-index but
43283 ** that extra content is ignored by the current thread.
43284 **
43285 ** If the database contents have changes since the previous read
43286 ** transaction, then *pChanged is set to 1 before returning.  The
43287 ** Pager layer will use this to know that is cache is stale and
43288 ** needs to be flushed.
43289 */
43290 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
43291   int rc;                         /* Return code */
43292   int cnt = 0;                    /* Number of TryBeginRead attempts */
43293
43294   do{
43295     rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
43296   }while( rc==WAL_RETRY );
43297   return rc;
43298 }
43299
43300 /*
43301 ** Finish with a read transaction.  All this does is release the
43302 ** read-lock.
43303 */
43304 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
43305   sqlite3WalEndWriteTransaction(pWal);
43306   if( pWal->readLock>=0 ){
43307     walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
43308     pWal->readLock = -1;
43309   }
43310 }
43311
43312 /*
43313 ** Read a page from the WAL, if it is present in the WAL and if the 
43314 ** current read transaction is configured to use the WAL.  
43315 **
43316 ** The *pInWal is set to 1 if the requested page is in the WAL and
43317 ** has been loaded.  Or *pInWal is set to 0 if the page was not in 
43318 ** the WAL and needs to be read out of the database.
43319 */
43320 SQLITE_PRIVATE int sqlite3WalRead(
43321   Wal *pWal,                      /* WAL handle */
43322   Pgno pgno,                      /* Database page number to read data for */
43323   int *pInWal,                    /* OUT: True if data is read from WAL */
43324   int nOut,                       /* Size of buffer pOut in bytes */
43325   u8 *pOut                        /* Buffer to write page data to */
43326 ){
43327   u32 iRead = 0;                  /* If !=0, WAL frame to return data from */
43328   u32 iLast = pWal->hdr.mxFrame;  /* Last page in WAL for this reader */
43329   int iHash;                      /* Used to loop through N hash tables */
43330
43331   /* This routine is only be called from within a read transaction. */
43332   assert( pWal->readLock>=0 || pWal->lockError );
43333
43334   /* If the "last page" field of the wal-index header snapshot is 0, then
43335   ** no data will be read from the wal under any circumstances. Return early
43336   ** in this case as an optimization.  Likewise, if pWal->readLock==0, 
43337   ** then the WAL is ignored by the reader so return early, as if the 
43338   ** WAL were empty.
43339   */
43340   if( iLast==0 || pWal->readLock==0 ){
43341     *pInWal = 0;
43342     return SQLITE_OK;
43343   }
43344
43345   /* Search the hash table or tables for an entry matching page number
43346   ** pgno. Each iteration of the following for() loop searches one
43347   ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
43348   **
43349   ** This code might run concurrently to the code in walIndexAppend()
43350   ** that adds entries to the wal-index (and possibly to this hash 
43351   ** table). This means the value just read from the hash 
43352   ** slot (aHash[iKey]) may have been added before or after the 
43353   ** current read transaction was opened. Values added after the
43354   ** read transaction was opened may have been written incorrectly -
43355   ** i.e. these slots may contain garbage data. However, we assume
43356   ** that any slots written before the current read transaction was
43357   ** opened remain unmodified.
43358   **
43359   ** For the reasons above, the if(...) condition featured in the inner
43360   ** loop of the following block is more stringent that would be required 
43361   ** if we had exclusive access to the hash-table:
43362   **
43363   **   (aPgno[iFrame]==pgno): 
43364   **     This condition filters out normal hash-table collisions.
43365   **
43366   **   (iFrame<=iLast): 
43367   **     This condition filters out entries that were added to the hash
43368   **     table after the current read-transaction had started.
43369   */
43370   for(iHash=walFramePage(iLast); iHash>=0 && iRead==0; iHash--){
43371     volatile ht_slot *aHash;      /* Pointer to hash table */
43372     volatile u32 *aPgno;          /* Pointer to array of page numbers */
43373     u32 iZero;                    /* Frame number corresponding to aPgno[0] */
43374     int iKey;                     /* Hash slot index */
43375     int nCollide;                 /* Number of hash collisions remaining */
43376     int rc;                       /* Error code */
43377
43378     rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
43379     if( rc!=SQLITE_OK ){
43380       return rc;
43381     }
43382     nCollide = HASHTABLE_NSLOT;
43383     for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
43384       u32 iFrame = aHash[iKey] + iZero;
43385       if( iFrame<=iLast && aPgno[aHash[iKey]]==pgno ){
43386         assert( iFrame>iRead );
43387         iRead = iFrame;
43388       }
43389       if( (nCollide--)==0 ){
43390         return SQLITE_CORRUPT_BKPT;
43391       }
43392     }
43393   }
43394
43395 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
43396   /* If expensive assert() statements are available, do a linear search
43397   ** of the wal-index file content. Make sure the results agree with the
43398   ** result obtained using the hash indexes above.  */
43399   {
43400     u32 iRead2 = 0;
43401     u32 iTest;
43402     for(iTest=iLast; iTest>0; iTest--){
43403       if( walFramePgno(pWal, iTest)==pgno ){
43404         iRead2 = iTest;
43405         break;
43406       }
43407     }
43408     assert( iRead==iRead2 );
43409   }
43410 #endif
43411
43412   /* If iRead is non-zero, then it is the log frame number that contains the
43413   ** required page. Read and return data from the log file.
43414   */
43415   if( iRead ){
43416     int sz;
43417     i64 iOffset;
43418     sz = pWal->hdr.szPage;
43419     sz = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
43420     testcase( sz<=32768 );
43421     testcase( sz>=65536 );
43422     iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
43423     *pInWal = 1;
43424     /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
43425     return sqlite3OsRead(pWal->pWalFd, pOut, nOut, iOffset);
43426   }
43427
43428   *pInWal = 0;
43429   return SQLITE_OK;
43430 }
43431
43432
43433 /* 
43434 ** Return the size of the database in pages (or zero, if unknown).
43435 */
43436 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
43437   if( pWal && ALWAYS(pWal->readLock>=0) ){
43438     return pWal->hdr.nPage;
43439   }
43440   return 0;
43441 }
43442
43443
43444 /* 
43445 ** This function starts a write transaction on the WAL.
43446 **
43447 ** A read transaction must have already been started by a prior call
43448 ** to sqlite3WalBeginReadTransaction().
43449 **
43450 ** If another thread or process has written into the database since
43451 ** the read transaction was started, then it is not possible for this
43452 ** thread to write as doing so would cause a fork.  So this routine
43453 ** returns SQLITE_BUSY in that case and no write transaction is started.
43454 **
43455 ** There can only be a single writer active at a time.
43456 */
43457 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
43458   int rc;
43459
43460   /* Cannot start a write transaction without first holding a read
43461   ** transaction. */
43462   assert( pWal->readLock>=0 );
43463
43464   if( pWal->readOnly ){
43465     return SQLITE_READONLY;
43466   }
43467
43468   /* Only one writer allowed at a time.  Get the write lock.  Return
43469   ** SQLITE_BUSY if unable.
43470   */
43471   rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
43472   if( rc ){
43473     return rc;
43474   }
43475   pWal->writeLock = 1;
43476
43477   /* If another connection has written to the database file since the
43478   ** time the read transaction on this connection was started, then
43479   ** the write is disallowed.
43480   */
43481   if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
43482     walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
43483     pWal->writeLock = 0;
43484     rc = SQLITE_BUSY;
43485   }
43486
43487   return rc;
43488 }
43489
43490 /*
43491 ** End a write transaction.  The commit has already been done.  This
43492 ** routine merely releases the lock.
43493 */
43494 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
43495   if( pWal->writeLock ){
43496     walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
43497     pWal->writeLock = 0;
43498   }
43499   return SQLITE_OK;
43500 }
43501
43502 /*
43503 ** If any data has been written (but not committed) to the log file, this
43504 ** function moves the write-pointer back to the start of the transaction.
43505 **
43506 ** Additionally, the callback function is invoked for each frame written
43507 ** to the WAL since the start of the transaction. If the callback returns
43508 ** other than SQLITE_OK, it is not invoked again and the error code is
43509 ** returned to the caller.
43510 **
43511 ** Otherwise, if the callback function does not return an error, this
43512 ** function returns SQLITE_OK.
43513 */
43514 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
43515   int rc = SQLITE_OK;
43516   if( ALWAYS(pWal->writeLock) ){
43517     Pgno iMax = pWal->hdr.mxFrame;
43518     Pgno iFrame;
43519   
43520     /* Restore the clients cache of the wal-index header to the state it
43521     ** was in before the client began writing to the database. 
43522     */
43523     memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
43524
43525     for(iFrame=pWal->hdr.mxFrame+1; 
43526         ALWAYS(rc==SQLITE_OK) && iFrame<=iMax; 
43527         iFrame++
43528     ){
43529       /* This call cannot fail. Unless the page for which the page number
43530       ** is passed as the second argument is (a) in the cache and 
43531       ** (b) has an outstanding reference, then xUndo is either a no-op
43532       ** (if (a) is false) or simply expels the page from the cache (if (b)
43533       ** is false).
43534       **
43535       ** If the upper layer is doing a rollback, it is guaranteed that there
43536       ** are no outstanding references to any page other than page 1. And
43537       ** page 1 is never written to the log until the transaction is
43538       ** committed. As a result, the call to xUndo may not fail.
43539       */
43540       assert( walFramePgno(pWal, iFrame)!=1 );
43541       rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
43542     }
43543     walCleanupHash(pWal);
43544   }
43545   assert( rc==SQLITE_OK );
43546   return rc;
43547 }
43548
43549 /* 
43550 ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32 
43551 ** values. This function populates the array with values required to 
43552 ** "rollback" the write position of the WAL handle back to the current 
43553 ** point in the event of a savepoint rollback (via WalSavepointUndo()).
43554 */
43555 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
43556   assert( pWal->writeLock );
43557   aWalData[0] = pWal->hdr.mxFrame;
43558   aWalData[1] = pWal->hdr.aFrameCksum[0];
43559   aWalData[2] = pWal->hdr.aFrameCksum[1];
43560   aWalData[3] = pWal->nCkpt;
43561 }
43562
43563 /* 
43564 ** Move the write position of the WAL back to the point identified by
43565 ** the values in the aWalData[] array. aWalData must point to an array
43566 ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
43567 ** by a call to WalSavepoint().
43568 */
43569 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
43570   int rc = SQLITE_OK;
43571
43572   assert( pWal->writeLock );
43573   assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
43574
43575   if( aWalData[3]!=pWal->nCkpt ){
43576     /* This savepoint was opened immediately after the write-transaction
43577     ** was started. Right after that, the writer decided to wrap around
43578     ** to the start of the log. Update the savepoint values to match.
43579     */
43580     aWalData[0] = 0;
43581     aWalData[3] = pWal->nCkpt;
43582   }
43583
43584   if( aWalData[0]<pWal->hdr.mxFrame ){
43585     pWal->hdr.mxFrame = aWalData[0];
43586     pWal->hdr.aFrameCksum[0] = aWalData[1];
43587     pWal->hdr.aFrameCksum[1] = aWalData[2];
43588     walCleanupHash(pWal);
43589   }
43590
43591   return rc;
43592 }
43593
43594 /*
43595 ** This function is called just before writing a set of frames to the log
43596 ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
43597 ** to the current log file, it is possible to overwrite the start of the
43598 ** existing log file with the new frames (i.e. "reset" the log). If so,
43599 ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
43600 ** unchanged.
43601 **
43602 ** SQLITE_OK is returned if no error is encountered (regardless of whether
43603 ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
43604 ** if an error occurs.
43605 */
43606 static int walRestartLog(Wal *pWal){
43607   int rc = SQLITE_OK;
43608   int cnt;
43609
43610   if( pWal->readLock==0 ){
43611     volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
43612     assert( pInfo->nBackfill==pWal->hdr.mxFrame );
43613     if( pInfo->nBackfill>0 ){
43614       rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
43615       if( rc==SQLITE_OK ){
43616         /* If all readers are using WAL_READ_LOCK(0) (in other words if no
43617         ** readers are currently using the WAL), then the transactions
43618         ** frames will overwrite the start of the existing log. Update the
43619         ** wal-index header to reflect this.
43620         **
43621         ** In theory it would be Ok to update the cache of the header only
43622         ** at this point. But updating the actual wal-index header is also
43623         ** safe and means there is no special case for sqlite3WalUndo()
43624         ** to handle if this transaction is rolled back.
43625         */
43626         int i;                    /* Loop counter */
43627         u32 *aSalt = pWal->hdr.aSalt;       /* Big-endian salt values */
43628         pWal->nCkpt++;
43629         pWal->hdr.mxFrame = 0;
43630         sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
43631         sqlite3_randomness(4, &aSalt[1]);
43632         walIndexWriteHdr(pWal);
43633         pInfo->nBackfill = 0;
43634         for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
43635         assert( pInfo->aReadMark[0]==0 );
43636         walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
43637       }else if( rc!=SQLITE_BUSY ){
43638         return rc;
43639       }
43640     }
43641     walUnlockShared(pWal, WAL_READ_LOCK(0));
43642     pWal->readLock = -1;
43643     cnt = 0;
43644     do{
43645       int notUsed;
43646       rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
43647     }while( rc==WAL_RETRY );
43648   }
43649   return rc;
43650 }
43651
43652 /* 
43653 ** Write a set of frames to the log. The caller must hold the write-lock
43654 ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
43655 */
43656 SQLITE_PRIVATE int sqlite3WalFrames(
43657   Wal *pWal,                      /* Wal handle to write to */
43658   int szPage,                     /* Database page-size in bytes */
43659   PgHdr *pList,                   /* List of dirty pages to write */
43660   Pgno nTruncate,                 /* Database size after this commit */
43661   int isCommit,                   /* True if this is a commit */
43662   int sync_flags                  /* Flags to pass to OsSync() (or 0) */
43663 ){
43664   int rc;                         /* Used to catch return codes */
43665   u32 iFrame;                     /* Next frame address */
43666   u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-header in */
43667   PgHdr *p;                       /* Iterator to run through pList with. */
43668   PgHdr *pLast = 0;               /* Last frame in list */
43669   int nLast = 0;                  /* Number of extra copies of last page */
43670
43671   assert( pList );
43672   assert( pWal->writeLock );
43673
43674 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
43675   { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
43676     WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
43677               pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
43678   }
43679 #endif
43680
43681   /* See if it is possible to write these frames into the start of the
43682   ** log file, instead of appending to it at pWal->hdr.mxFrame.
43683   */
43684   if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
43685     return rc;
43686   }
43687
43688   /* If this is the first frame written into the log, write the WAL
43689   ** header to the start of the WAL file. See comments at the top of
43690   ** this source file for a description of the WAL header format.
43691   */
43692   iFrame = pWal->hdr.mxFrame;
43693   if( iFrame==0 ){
43694     u8 aWalHdr[WAL_HDRSIZE];      /* Buffer to assemble wal-header in */
43695     u32 aCksum[2];                /* Checksum for wal-header */
43696
43697     sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
43698     sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
43699     sqlite3Put4byte(&aWalHdr[8], szPage);
43700     sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
43701     sqlite3_randomness(8, pWal->hdr.aSalt);
43702     memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
43703     walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
43704     sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
43705     sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
43706     
43707     pWal->szPage = szPage;
43708     pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
43709     pWal->hdr.aFrameCksum[0] = aCksum[0];
43710     pWal->hdr.aFrameCksum[1] = aCksum[1];
43711
43712     rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
43713     WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
43714     if( rc!=SQLITE_OK ){
43715       return rc;
43716     }
43717   }
43718   assert( (int)pWal->szPage==szPage );
43719
43720   /* Write the log file. */
43721   for(p=pList; p; p=p->pDirty){
43722     u32 nDbsize;                  /* Db-size field for frame header */
43723     i64 iOffset;                  /* Write offset in log file */
43724     void *pData;
43725    
43726     iOffset = walFrameOffset(++iFrame, szPage);
43727     /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
43728     
43729     /* Populate and write the frame header */
43730     nDbsize = (isCommit && p->pDirty==0) ? nTruncate : 0;
43731 #if defined(SQLITE_HAS_CODEC)
43732     if( (pData = sqlite3PagerCodec(p))==0 ) return SQLITE_NOMEM;
43733 #else
43734     pData = p->pData;
43735 #endif
43736     walEncodeFrame(pWal, p->pgno, nDbsize, pData, aFrame);
43737     rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOffset);
43738     if( rc!=SQLITE_OK ){
43739       return rc;
43740     }
43741
43742     /* Write the page data */
43743     rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOffset+sizeof(aFrame));
43744     if( rc!=SQLITE_OK ){
43745       return rc;
43746     }
43747     pLast = p;
43748   }
43749
43750   /* Sync the log file if the 'isSync' flag was specified. */
43751   if( sync_flags ){
43752     i64 iSegment = sqlite3OsSectorSize(pWal->pWalFd);
43753     i64 iOffset = walFrameOffset(iFrame+1, szPage);
43754
43755     assert( isCommit );
43756     assert( iSegment>0 );
43757
43758     iSegment = (((iOffset+iSegment-1)/iSegment) * iSegment);
43759     while( iOffset<iSegment ){
43760       void *pData;
43761 #if defined(SQLITE_HAS_CODEC)
43762       if( (pData = sqlite3PagerCodec(pLast))==0 ) return SQLITE_NOMEM;
43763 #else
43764       pData = pLast->pData;
43765 #endif
43766       walEncodeFrame(pWal, pLast->pgno, nTruncate, pData, aFrame);
43767       /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
43768       rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOffset);
43769       if( rc!=SQLITE_OK ){
43770         return rc;
43771       }
43772       iOffset += WAL_FRAME_HDRSIZE;
43773       rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOffset); 
43774       if( rc!=SQLITE_OK ){
43775         return rc;
43776       }
43777       nLast++;
43778       iOffset += szPage;
43779     }
43780
43781     rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
43782   }
43783
43784   /* Append data to the wal-index. It is not necessary to lock the 
43785   ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
43786   ** guarantees that there are no other writers, and no data that may
43787   ** be in use by existing readers is being overwritten.
43788   */
43789   iFrame = pWal->hdr.mxFrame;
43790   for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
43791     iFrame++;
43792     rc = walIndexAppend(pWal, iFrame, p->pgno);
43793   }
43794   while( nLast>0 && rc==SQLITE_OK ){
43795     iFrame++;
43796     nLast--;
43797     rc = walIndexAppend(pWal, iFrame, pLast->pgno);
43798   }
43799
43800   if( rc==SQLITE_OK ){
43801     /* Update the private copy of the header. */
43802     pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
43803     testcase( szPage<=32768 );
43804     testcase( szPage>=65536 );
43805     pWal->hdr.mxFrame = iFrame;
43806     if( isCommit ){
43807       pWal->hdr.iChange++;
43808       pWal->hdr.nPage = nTruncate;
43809     }
43810     /* If this is a commit, update the wal-index header too. */
43811     if( isCommit ){
43812       walIndexWriteHdr(pWal);
43813       pWal->iCallback = iFrame;
43814     }
43815   }
43816
43817   WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
43818   return rc;
43819 }
43820
43821 /* 
43822 ** This routine is called to implement sqlite3_wal_checkpoint() and
43823 ** related interfaces.
43824 **
43825 ** Obtain a CHECKPOINT lock and then backfill as much information as
43826 ** we can from WAL into the database.
43827 */
43828 SQLITE_PRIVATE int sqlite3WalCheckpoint(
43829   Wal *pWal,                      /* Wal connection */
43830   int sync_flags,                 /* Flags to sync db file with (or 0) */
43831   int nBuf,                       /* Size of temporary buffer */
43832   u8 *zBuf                        /* Temporary buffer to use */
43833 ){
43834   int rc;                         /* Return code */
43835   int isChanged = 0;              /* True if a new wal-index header is loaded */
43836
43837   assert( pWal->ckptLock==0 );
43838
43839   WALTRACE(("WAL%p: checkpoint begins\n", pWal));
43840   rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
43841   if( rc ){
43842     /* Usually this is SQLITE_BUSY meaning that another thread or process
43843     ** is already running a checkpoint, or maybe a recovery.  But it might
43844     ** also be SQLITE_IOERR. */
43845     return rc;
43846   }
43847   pWal->ckptLock = 1;
43848
43849   /* Copy data from the log to the database file. */
43850   rc = walIndexReadHdr(pWal, &isChanged);
43851   if( rc==SQLITE_OK ){
43852     rc = walCheckpoint(pWal, sync_flags, nBuf, zBuf);
43853   }
43854   if( isChanged ){
43855     /* If a new wal-index header was loaded before the checkpoint was 
43856     ** performed, then the pager-cache associated with pWal is now
43857     ** out of date. So zero the cached wal-index header to ensure that
43858     ** next time the pager opens a snapshot on this database it knows that
43859     ** the cache needs to be reset.
43860     */
43861     memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
43862   }
43863
43864   /* Release the locks. */
43865   walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
43866   pWal->ckptLock = 0;
43867   WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
43868   return rc;
43869 }
43870
43871 /* Return the value to pass to a sqlite3_wal_hook callback, the
43872 ** number of frames in the WAL at the point of the last commit since
43873 ** sqlite3WalCallback() was called.  If no commits have occurred since
43874 ** the last call, then return 0.
43875 */
43876 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
43877   u32 ret = 0;
43878   if( pWal ){
43879     ret = pWal->iCallback;
43880     pWal->iCallback = 0;
43881   }
43882   return (int)ret;
43883 }
43884
43885 /*
43886 ** This function is called to change the WAL subsystem into or out
43887 ** of locking_mode=EXCLUSIVE.
43888 **
43889 ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
43890 ** into locking_mode=NORMAL.  This means that we must acquire a lock
43891 ** on the pWal->readLock byte.  If the WAL is already in locking_mode=NORMAL
43892 ** or if the acquisition of the lock fails, then return 0.  If the
43893 ** transition out of exclusive-mode is successful, return 1.  This
43894 ** operation must occur while the pager is still holding the exclusive
43895 ** lock on the main database file.
43896 **
43897 ** If op is one, then change from locking_mode=NORMAL into 
43898 ** locking_mode=EXCLUSIVE.  This means that the pWal->readLock must
43899 ** be released.  Return 1 if the transition is made and 0 if the
43900 ** WAL is already in exclusive-locking mode - meaning that this
43901 ** routine is a no-op.  The pager must already hold the exclusive lock
43902 ** on the main database file before invoking this operation.
43903 **
43904 ** If op is negative, then do a dry-run of the op==1 case but do
43905 ** not actually change anything.  The pager uses this to see if it
43906 ** should acquire the database exclusive lock prior to invoking
43907 ** the op==1 case.
43908 */
43909 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
43910   int rc;
43911   assert( pWal->writeLock==0 );
43912
43913   /* pWal->readLock is usually set, but might be -1 if there was a 
43914   ** prior error while attempting to acquire are read-lock. This cannot 
43915   ** happen if the connection is actually in exclusive mode (as no xShmLock
43916   ** locks are taken in this case). Nor should the pager attempt to
43917   ** upgrade to exclusive-mode following such an error.
43918   */
43919   assert( pWal->readLock>=0 || pWal->lockError );
43920   assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
43921
43922   if( op==0 ){
43923     if( pWal->exclusiveMode ){
43924       pWal->exclusiveMode = 0;
43925       if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
43926         pWal->exclusiveMode = 1;
43927       }
43928       rc = pWal->exclusiveMode==0;
43929     }else{
43930       /* Already in locking_mode=NORMAL */
43931       rc = 0;
43932     }
43933   }else if( op>0 ){
43934     assert( pWal->exclusiveMode==0 );
43935     assert( pWal->readLock>=0 );
43936     walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
43937     pWal->exclusiveMode = 1;
43938     rc = 1;
43939   }else{
43940     rc = pWal->exclusiveMode==0;
43941   }
43942   return rc;
43943 }
43944
43945 #endif /* #ifndef SQLITE_OMIT_WAL */
43946
43947 /************** End of wal.c *************************************************/
43948 /************** Begin file btmutex.c *****************************************/
43949 /*
43950 ** 2007 August 27
43951 **
43952 ** The author disclaims copyright to this source code.  In place of
43953 ** a legal notice, here is a blessing:
43954 **
43955 **    May you do good and not evil.
43956 **    May you find forgiveness for yourself and forgive others.
43957 **    May you share freely, never taking more than you give.
43958 **
43959 *************************************************************************
43960 **
43961 ** This file contains code used to implement mutexes on Btree objects.
43962 ** This code really belongs in btree.c.  But btree.c is getting too
43963 ** big and we want to break it down some.  This packaged seemed like
43964 ** a good breakout.
43965 */
43966 /************** Include btreeInt.h in the middle of btmutex.c ****************/
43967 /************** Begin file btreeInt.h ****************************************/
43968 /*
43969 ** 2004 April 6
43970 **
43971 ** The author disclaims copyright to this source code.  In place of
43972 ** a legal notice, here is a blessing:
43973 **
43974 **    May you do good and not evil.
43975 **    May you find forgiveness for yourself and forgive others.
43976 **    May you share freely, never taking more than you give.
43977 **
43978 *************************************************************************
43979 ** This file implements a external (disk-based) database using BTrees.
43980 ** For a detailed discussion of BTrees, refer to
43981 **
43982 **     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
43983 **     "Sorting And Searching", pages 473-480. Addison-Wesley
43984 **     Publishing Company, Reading, Massachusetts.
43985 **
43986 ** The basic idea is that each page of the file contains N database
43987 ** entries and N+1 pointers to subpages.
43988 **
43989 **   ----------------------------------------------------------------
43990 **   |  Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
43991 **   ----------------------------------------------------------------
43992 **
43993 ** All of the keys on the page that Ptr(0) points to have values less
43994 ** than Key(0).  All of the keys on page Ptr(1) and its subpages have
43995 ** values greater than Key(0) and less than Key(1).  All of the keys
43996 ** on Ptr(N) and its subpages have values greater than Key(N-1).  And
43997 ** so forth.
43998 **
43999 ** Finding a particular key requires reading O(log(M)) pages from the 
44000 ** disk where M is the number of entries in the tree.
44001 **
44002 ** In this implementation, a single file can hold one or more separate 
44003 ** BTrees.  Each BTree is identified by the index of its root page.  The
44004 ** key and data for any entry are combined to form the "payload".  A
44005 ** fixed amount of payload can be carried directly on the database
44006 ** page.  If the payload is larger than the preset amount then surplus
44007 ** bytes are stored on overflow pages.  The payload for an entry
44008 ** and the preceding pointer are combined to form a "Cell".  Each 
44009 ** page has a small header which contains the Ptr(N) pointer and other
44010 ** information such as the size of key and data.
44011 **
44012 ** FORMAT DETAILS
44013 **
44014 ** The file is divided into pages.  The first page is called page 1,
44015 ** the second is page 2, and so forth.  A page number of zero indicates
44016 ** "no such page".  The page size can be any power of 2 between 512 and 65536.
44017 ** Each page can be either a btree page, a freelist page, an overflow
44018 ** page, or a pointer-map page.
44019 **
44020 ** The first page is always a btree page.  The first 100 bytes of the first
44021 ** page contain a special header (the "file header") that describes the file.
44022 ** The format of the file header is as follows:
44023 **
44024 **   OFFSET   SIZE    DESCRIPTION
44025 **      0      16     Header string: "SQLite format 3\000"
44026 **     16       2     Page size in bytes.  
44027 **     18       1     File format write version
44028 **     19       1     File format read version
44029 **     20       1     Bytes of unused space at the end of each page
44030 **     21       1     Max embedded payload fraction
44031 **     22       1     Min embedded payload fraction
44032 **     23       1     Min leaf payload fraction
44033 **     24       4     File change counter
44034 **     28       4     Reserved for future use
44035 **     32       4     First freelist page
44036 **     36       4     Number of freelist pages in the file
44037 **     40      60     15 4-byte meta values passed to higher layers
44038 **
44039 **     40       4     Schema cookie
44040 **     44       4     File format of schema layer
44041 **     48       4     Size of page cache
44042 **     52       4     Largest root-page (auto/incr_vacuum)
44043 **     56       4     1=UTF-8 2=UTF16le 3=UTF16be
44044 **     60       4     User version
44045 **     64       4     Incremental vacuum mode
44046 **     68       4     unused
44047 **     72       4     unused
44048 **     76       4     unused
44049 **
44050 ** All of the integer values are big-endian (most significant byte first).
44051 **
44052 ** The file change counter is incremented when the database is changed
44053 ** This counter allows other processes to know when the file has changed
44054 ** and thus when they need to flush their cache.
44055 **
44056 ** The max embedded payload fraction is the amount of the total usable
44057 ** space in a page that can be consumed by a single cell for standard
44058 ** B-tree (non-LEAFDATA) tables.  A value of 255 means 100%.  The default
44059 ** is to limit the maximum cell size so that at least 4 cells will fit
44060 ** on one page.  Thus the default max embedded payload fraction is 64.
44061 **
44062 ** If the payload for a cell is larger than the max payload, then extra
44063 ** payload is spilled to overflow pages.  Once an overflow page is allocated,
44064 ** as many bytes as possible are moved into the overflow pages without letting
44065 ** the cell size drop below the min embedded payload fraction.
44066 **
44067 ** The min leaf payload fraction is like the min embedded payload fraction
44068 ** except that it applies to leaf nodes in a LEAFDATA tree.  The maximum
44069 ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
44070 ** not specified in the header.
44071 **
44072 ** Each btree pages is divided into three sections:  The header, the
44073 ** cell pointer array, and the cell content area.  Page 1 also has a 100-byte
44074 ** file header that occurs before the page header.
44075 **
44076 **      |----------------|
44077 **      | file header    |   100 bytes.  Page 1 only.
44078 **      |----------------|
44079 **      | page header    |   8 bytes for leaves.  12 bytes for interior nodes
44080 **      |----------------|
44081 **      | cell pointer   |   |  2 bytes per cell.  Sorted order.
44082 **      | array          |   |  Grows downward
44083 **      |                |   v
44084 **      |----------------|
44085 **      | unallocated    |
44086 **      | space          |
44087 **      |----------------|   ^  Grows upwards
44088 **      | cell content   |   |  Arbitrary order interspersed with freeblocks.
44089 **      | area           |   |  and free space fragments.
44090 **      |----------------|
44091 **
44092 ** The page headers looks like this:
44093 **
44094 **   OFFSET   SIZE     DESCRIPTION
44095 **      0       1      Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
44096 **      1       2      byte offset to the first freeblock
44097 **      3       2      number of cells on this page
44098 **      5       2      first byte of the cell content area
44099 **      7       1      number of fragmented free bytes
44100 **      8       4      Right child (the Ptr(N) value).  Omitted on leaves.
44101 **
44102 ** The flags define the format of this btree page.  The leaf flag means that
44103 ** this page has no children.  The zerodata flag means that this page carries
44104 ** only keys and no data.  The intkey flag means that the key is a integer
44105 ** which is stored in the key size entry of the cell header rather than in
44106 ** the payload area.
44107 **
44108 ** The cell pointer array begins on the first byte after the page header.
44109 ** The cell pointer array contains zero or more 2-byte numbers which are
44110 ** offsets from the beginning of the page to the cell content in the cell
44111 ** content area.  The cell pointers occur in sorted order.  The system strives
44112 ** to keep free space after the last cell pointer so that new cells can
44113 ** be easily added without having to defragment the page.
44114 **
44115 ** Cell content is stored at the very end of the page and grows toward the
44116 ** beginning of the page.
44117 **
44118 ** Unused space within the cell content area is collected into a linked list of
44119 ** freeblocks.  Each freeblock is at least 4 bytes in size.  The byte offset
44120 ** to the first freeblock is given in the header.  Freeblocks occur in
44121 ** increasing order.  Because a freeblock must be at least 4 bytes in size,
44122 ** any group of 3 or fewer unused bytes in the cell content area cannot
44123 ** exist on the freeblock chain.  A group of 3 or fewer free bytes is called
44124 ** a fragment.  The total number of bytes in all fragments is recorded.
44125 ** in the page header at offset 7.
44126 **
44127 **    SIZE    DESCRIPTION
44128 **      2     Byte offset of the next freeblock
44129 **      2     Bytes in this freeblock
44130 **
44131 ** Cells are of variable length.  Cells are stored in the cell content area at
44132 ** the end of the page.  Pointers to the cells are in the cell pointer array
44133 ** that immediately follows the page header.  Cells is not necessarily
44134 ** contiguous or in order, but cell pointers are contiguous and in order.
44135 **
44136 ** Cell content makes use of variable length integers.  A variable
44137 ** length integer is 1 to 9 bytes where the lower 7 bits of each 
44138 ** byte are used.  The integer consists of all bytes that have bit 8 set and
44139 ** the first byte with bit 8 clear.  The most significant byte of the integer
44140 ** appears first.  A variable-length integer may not be more than 9 bytes long.
44141 ** As a special case, all 8 bytes of the 9th byte are used as data.  This
44142 ** allows a 64-bit integer to be encoded in 9 bytes.
44143 **
44144 **    0x00                      becomes  0x00000000
44145 **    0x7f                      becomes  0x0000007f
44146 **    0x81 0x00                 becomes  0x00000080
44147 **    0x82 0x00                 becomes  0x00000100
44148 **    0x80 0x7f                 becomes  0x0000007f
44149 **    0x8a 0x91 0xd1 0xac 0x78  becomes  0x12345678
44150 **    0x81 0x81 0x81 0x81 0x01  becomes  0x10204081
44151 **
44152 ** Variable length integers are used for rowids and to hold the number of
44153 ** bytes of key and data in a btree cell.
44154 **
44155 ** The content of a cell looks like this:
44156 **
44157 **    SIZE    DESCRIPTION
44158 **      4     Page number of the left child. Omitted if leaf flag is set.
44159 **     var    Number of bytes of data. Omitted if the zerodata flag is set.
44160 **     var    Number of bytes of key. Or the key itself if intkey flag is set.
44161 **      *     Payload
44162 **      4     First page of the overflow chain.  Omitted if no overflow
44163 **
44164 ** Overflow pages form a linked list.  Each page except the last is completely
44165 ** filled with data (pagesize - 4 bytes).  The last page can have as little
44166 ** as 1 byte of data.
44167 **
44168 **    SIZE    DESCRIPTION
44169 **      4     Page number of next overflow page
44170 **      *     Data
44171 **
44172 ** Freelist pages come in two subtypes: trunk pages and leaf pages.  The
44173 ** file header points to the first in a linked list of trunk page.  Each trunk
44174 ** page points to multiple leaf pages.  The content of a leaf page is
44175 ** unspecified.  A trunk page looks like this:
44176 **
44177 **    SIZE    DESCRIPTION
44178 **      4     Page number of next trunk page
44179 **      4     Number of leaf pointers on this page
44180 **      *     zero or more pages numbers of leaves
44181 */
44182
44183
44184 /* The following value is the maximum cell size assuming a maximum page
44185 ** size give above.
44186 */
44187 #define MX_CELL_SIZE(pBt)  (pBt->pageSize-8)
44188
44189 /* The maximum number of cells on a single page of the database.  This
44190 ** assumes a minimum cell size of 6 bytes  (4 bytes for the cell itself
44191 ** plus 2 bytes for the index to the cell in the page header).  Such
44192 ** small cells will be rare, but they are possible.
44193 */
44194 #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
44195
44196 /* Forward declarations */
44197 typedef struct MemPage MemPage;
44198 typedef struct BtLock BtLock;
44199
44200 /*
44201 ** This is a magic string that appears at the beginning of every
44202 ** SQLite database in order to identify the file as a real database.
44203 **
44204 ** You can change this value at compile-time by specifying a
44205 ** -DSQLITE_FILE_HEADER="..." on the compiler command-line.  The
44206 ** header must be exactly 16 bytes including the zero-terminator so
44207 ** the string itself should be 15 characters long.  If you change
44208 ** the header, then your custom library will not be able to read 
44209 ** databases generated by the standard tools and the standard tools
44210 ** will not be able to read databases created by your custom library.
44211 */
44212 #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
44213 #  define SQLITE_FILE_HEADER "SQLite format 3"
44214 #endif
44215
44216 /*
44217 ** Page type flags.  An ORed combination of these flags appear as the
44218 ** first byte of on-disk image of every BTree page.
44219 */
44220 #define PTF_INTKEY    0x01
44221 #define PTF_ZERODATA  0x02
44222 #define PTF_LEAFDATA  0x04
44223 #define PTF_LEAF      0x08
44224
44225 /*
44226 ** As each page of the file is loaded into memory, an instance of the following
44227 ** structure is appended and initialized to zero.  This structure stores
44228 ** information about the page that is decoded from the raw file page.
44229 **
44230 ** The pParent field points back to the parent page.  This allows us to
44231 ** walk up the BTree from any leaf to the root.  Care must be taken to
44232 ** unref() the parent page pointer when this page is no longer referenced.
44233 ** The pageDestructor() routine handles that chore.
44234 **
44235 ** Access to all fields of this structure is controlled by the mutex
44236 ** stored in MemPage.pBt->mutex.
44237 */
44238 struct MemPage {
44239   u8 isInit;           /* True if previously initialized. MUST BE FIRST! */
44240   u8 nOverflow;        /* Number of overflow cell bodies in aCell[] */
44241   u8 intKey;           /* True if intkey flag is set */
44242   u8 leaf;             /* True if leaf flag is set */
44243   u8 hasData;          /* True if this page stores data */
44244   u8 hdrOffset;        /* 100 for page 1.  0 otherwise */
44245   u8 childPtrSize;     /* 0 if leaf==1.  4 if leaf==0 */
44246   u16 maxLocal;        /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
44247   u16 minLocal;        /* Copy of BtShared.minLocal or BtShared.minLeaf */
44248   u16 cellOffset;      /* Index in aData of first cell pointer */
44249   u16 nFree;           /* Number of free bytes on the page */
44250   u16 nCell;           /* Number of cells on this page, local and ovfl */
44251   u16 maskPage;        /* Mask for page offset */
44252   struct _OvflCell {   /* Cells that will not fit on aData[] */
44253     u8 *pCell;          /* Pointers to the body of the overflow cell */
44254     u16 idx;            /* Insert this cell before idx-th non-overflow cell */
44255   } aOvfl[5];
44256   BtShared *pBt;       /* Pointer to BtShared that this page is part of */
44257   u8 *aData;           /* Pointer to disk image of the page data */
44258   DbPage *pDbPage;     /* Pager page handle */
44259   Pgno pgno;           /* Page number for this page */
44260 };
44261
44262 /*
44263 ** The in-memory image of a disk page has the auxiliary information appended
44264 ** to the end.  EXTRA_SIZE is the number of bytes of space needed to hold
44265 ** that extra information.
44266 */
44267 #define EXTRA_SIZE sizeof(MemPage)
44268
44269 /*
44270 ** A linked list of the following structures is stored at BtShared.pLock.
44271 ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor 
44272 ** is opened on the table with root page BtShared.iTable. Locks are removed
44273 ** from this list when a transaction is committed or rolled back, or when
44274 ** a btree handle is closed.
44275 */
44276 struct BtLock {
44277   Btree *pBtree;        /* Btree handle holding this lock */
44278   Pgno iTable;          /* Root page of table */
44279   u8 eLock;             /* READ_LOCK or WRITE_LOCK */
44280   BtLock *pNext;        /* Next in BtShared.pLock list */
44281 };
44282
44283 /* Candidate values for BtLock.eLock */
44284 #define READ_LOCK     1
44285 #define WRITE_LOCK    2
44286
44287 /* A Btree handle
44288 **
44289 ** A database connection contains a pointer to an instance of
44290 ** this object for every database file that it has open.  This structure
44291 ** is opaque to the database connection.  The database connection cannot
44292 ** see the internals of this structure and only deals with pointers to
44293 ** this structure.
44294 **
44295 ** For some database files, the same underlying database cache might be 
44296 ** shared between multiple connections.  In that case, each connection
44297 ** has it own instance of this object.  But each instance of this object
44298 ** points to the same BtShared object.  The database cache and the
44299 ** schema associated with the database file are all contained within
44300 ** the BtShared object.
44301 **
44302 ** All fields in this structure are accessed under sqlite3.mutex.
44303 ** The pBt pointer itself may not be changed while there exists cursors 
44304 ** in the referenced BtShared that point back to this Btree since those
44305 ** cursors have to do go through this Btree to find their BtShared and
44306 ** they often do so without holding sqlite3.mutex.
44307 */
44308 struct Btree {
44309   sqlite3 *db;       /* The database connection holding this btree */
44310   BtShared *pBt;     /* Sharable content of this btree */
44311   u8 inTrans;        /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
44312   u8 sharable;       /* True if we can share pBt with another db */
44313   u8 locked;         /* True if db currently has pBt locked */
44314   int wantToLock;    /* Number of nested calls to sqlite3BtreeEnter() */
44315   int nBackup;       /* Number of backup operations reading this btree */
44316   Btree *pNext;      /* List of other sharable Btrees from the same db */
44317   Btree *pPrev;      /* Back pointer of the same list */
44318 #ifndef SQLITE_OMIT_SHARED_CACHE
44319   BtLock lock;       /* Object used to lock page 1 */
44320 #endif
44321 };
44322
44323 /*
44324 ** Btree.inTrans may take one of the following values.
44325 **
44326 ** If the shared-data extension is enabled, there may be multiple users
44327 ** of the Btree structure. At most one of these may open a write transaction,
44328 ** but any number may have active read transactions.
44329 */
44330 #define TRANS_NONE  0
44331 #define TRANS_READ  1
44332 #define TRANS_WRITE 2
44333
44334 /*
44335 ** An instance of this object represents a single database file.
44336 ** 
44337 ** A single database file can be in use as the same time by two
44338 ** or more database connections.  When two or more connections are
44339 ** sharing the same database file, each connection has it own
44340 ** private Btree object for the file and each of those Btrees points
44341 ** to this one BtShared object.  BtShared.nRef is the number of
44342 ** connections currently sharing this database file.
44343 **
44344 ** Fields in this structure are accessed under the BtShared.mutex
44345 ** mutex, except for nRef and pNext which are accessed under the
44346 ** global SQLITE_MUTEX_STATIC_MASTER mutex.  The pPager field
44347 ** may not be modified once it is initially set as long as nRef>0.
44348 ** The pSchema field may be set once under BtShared.mutex and
44349 ** thereafter is unchanged as long as nRef>0.
44350 **
44351 ** isPending:
44352 **
44353 **   If a BtShared client fails to obtain a write-lock on a database
44354 **   table (because there exists one or more read-locks on the table),
44355 **   the shared-cache enters 'pending-lock' state and isPending is
44356 **   set to true.
44357 **
44358 **   The shared-cache leaves the 'pending lock' state when either of
44359 **   the following occur:
44360 **
44361 **     1) The current writer (BtShared.pWriter) concludes its transaction, OR
44362 **     2) The number of locks held by other connections drops to zero.
44363 **
44364 **   while in the 'pending-lock' state, no connection may start a new
44365 **   transaction.
44366 **
44367 **   This feature is included to help prevent writer-starvation.
44368 */
44369 struct BtShared {
44370   Pager *pPager;        /* The page cache */
44371   sqlite3 *db;          /* Database connection currently using this Btree */
44372   BtCursor *pCursor;    /* A list of all open cursors */
44373   MemPage *pPage1;      /* First page of the database */
44374   u8 readOnly;          /* True if the underlying file is readonly */
44375   u8 pageSizeFixed;     /* True if the page size can no longer be changed */
44376   u8 secureDelete;      /* True if secure_delete is enabled */
44377   u8 initiallyEmpty;    /* Database is empty at start of transaction */
44378   u8 openFlags;         /* Flags to sqlite3BtreeOpen() */
44379 #ifndef SQLITE_OMIT_AUTOVACUUM
44380   u8 autoVacuum;        /* True if auto-vacuum is enabled */
44381   u8 incrVacuum;        /* True if incr-vacuum is enabled */
44382 #endif
44383   u16 maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
44384   u16 minLocal;         /* Minimum local payload in non-LEAFDATA tables */
44385   u16 maxLeaf;          /* Maximum local payload in a LEAFDATA table */
44386   u16 minLeaf;          /* Minimum local payload in a LEAFDATA table */
44387   u8 inTransaction;     /* Transaction state */
44388   u8 doNotUseWAL;       /* If true, do not open write-ahead-log file */
44389   u32 pageSize;         /* Total number of bytes on a page */
44390   u32 usableSize;       /* Number of usable bytes on each page */
44391   int nTransaction;     /* Number of open transactions (read + write) */
44392   u32 nPage;            /* Number of pages in the database */
44393   void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */
44394   void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
44395   sqlite3_mutex *mutex; /* Non-recursive mutex required to access this struct */
44396   Bitvec *pHasContent;  /* Set of pages moved to free-list this transaction */
44397 #ifndef SQLITE_OMIT_SHARED_CACHE
44398   int nRef;             /* Number of references to this structure */
44399   BtShared *pNext;      /* Next on a list of sharable BtShared structs */
44400   BtLock *pLock;        /* List of locks held on this shared-btree struct */
44401   Btree *pWriter;       /* Btree with currently open write transaction */
44402   u8 isExclusive;       /* True if pWriter has an EXCLUSIVE lock on the db */
44403   u8 isPending;         /* If waiting for read-locks to clear */
44404 #endif
44405   u8 *pTmpSpace;        /* BtShared.pageSize bytes of space for tmp use */
44406 };
44407
44408 /*
44409 ** An instance of the following structure is used to hold information
44410 ** about a cell.  The parseCellPtr() function fills in this structure
44411 ** based on information extract from the raw disk page.
44412 */
44413 typedef struct CellInfo CellInfo;
44414 struct CellInfo {
44415   u8 *pCell;     /* Pointer to the start of cell content */
44416   i64 nKey;      /* The key for INTKEY tables, or number of bytes in key */
44417   u32 nData;     /* Number of bytes of data */
44418   u32 nPayload;  /* Total amount of payload */
44419   u16 nHeader;   /* Size of the cell content header in bytes */
44420   u16 nLocal;    /* Amount of payload held locally */
44421   u16 iOverflow; /* Offset to overflow page number.  Zero if no overflow */
44422   u16 nSize;     /* Size of the cell content on the main b-tree page */
44423 };
44424
44425 /*
44426 ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
44427 ** this will be declared corrupt. This value is calculated based on a
44428 ** maximum database size of 2^31 pages a minimum fanout of 2 for a
44429 ** root-node and 3 for all other internal nodes.
44430 **
44431 ** If a tree that appears to be taller than this is encountered, it is
44432 ** assumed that the database is corrupt.
44433 */
44434 #define BTCURSOR_MAX_DEPTH 20
44435
44436 /*
44437 ** A cursor is a pointer to a particular entry within a particular
44438 ** b-tree within a database file.
44439 **
44440 ** The entry is identified by its MemPage and the index in
44441 ** MemPage.aCell[] of the entry.
44442 **
44443 ** A single database file can shared by two more database connections,
44444 ** but cursors cannot be shared.  Each cursor is associated with a
44445 ** particular database connection identified BtCursor.pBtree.db.
44446 **
44447 ** Fields in this structure are accessed under the BtShared.mutex
44448 ** found at self->pBt->mutex. 
44449 */
44450 struct BtCursor {
44451   Btree *pBtree;            /* The Btree to which this cursor belongs */
44452   BtShared *pBt;            /* The BtShared this cursor points to */
44453   BtCursor *pNext, *pPrev;  /* Forms a linked list of all cursors */
44454   struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
44455   Pgno pgnoRoot;            /* The root page of this tree */
44456   sqlite3_int64 cachedRowid; /* Next rowid cache.  0 means not valid */
44457   CellInfo info;            /* A parse of the cell we are pointing at */
44458   u8 wrFlag;                /* True if writable */
44459   u8 atLast;                /* Cursor pointing to the last entry */
44460   u8 validNKey;             /* True if info.nKey is valid */
44461   u8 eState;                /* One of the CURSOR_XXX constants (see below) */
44462   void *pKey;      /* Saved key that was cursor's last known position */
44463   i64 nKey;        /* Size of pKey, or last integer key */
44464   int skipNext;    /* Prev() is noop if negative. Next() is noop if positive */
44465 #ifndef SQLITE_OMIT_INCRBLOB
44466   u8 isIncrblobHandle;      /* True if this cursor is an incr. io handle */
44467   Pgno *aOverflow;          /* Cache of overflow page locations */
44468 #endif
44469   i16 iPage;                            /* Index of current page in apPage */
44470   MemPage *apPage[BTCURSOR_MAX_DEPTH];  /* Pages from root to current page */
44471   u16 aiIdx[BTCURSOR_MAX_DEPTH];        /* Current index in apPage[i] */
44472 };
44473
44474 /*
44475 ** Potential values for BtCursor.eState.
44476 **
44477 ** CURSOR_VALID:
44478 **   Cursor points to a valid entry. getPayload() etc. may be called.
44479 **
44480 ** CURSOR_INVALID:
44481 **   Cursor does not point to a valid entry. This can happen (for example) 
44482 **   because the table is empty or because BtreeCursorFirst() has not been
44483 **   called.
44484 **
44485 ** CURSOR_REQUIRESEEK:
44486 **   The table that this cursor was opened on still exists, but has been 
44487 **   modified since the cursor was last used. The cursor position is saved
44488 **   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in 
44489 **   this state, restoreCursorPosition() can be called to attempt to
44490 **   seek the cursor to the saved position.
44491 **
44492 ** CURSOR_FAULT:
44493 **   A unrecoverable error (an I/O error or a malloc failure) has occurred
44494 **   on a different connection that shares the BtShared cache with this
44495 **   cursor.  The error has left the cache in an inconsistent state.
44496 **   Do nothing else with this cursor.  Any attempt to use the cursor
44497 **   should return the error code stored in BtCursor.skip
44498 */
44499 #define CURSOR_INVALID           0
44500 #define CURSOR_VALID             1
44501 #define CURSOR_REQUIRESEEK       2
44502 #define CURSOR_FAULT             3
44503
44504 /* 
44505 ** The database page the PENDING_BYTE occupies. This page is never used.
44506 */
44507 # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
44508
44509 /*
44510 ** These macros define the location of the pointer-map entry for a 
44511 ** database page. The first argument to each is the number of usable
44512 ** bytes on each page of the database (often 1024). The second is the
44513 ** page number to look up in the pointer map.
44514 **
44515 ** PTRMAP_PAGENO returns the database page number of the pointer-map
44516 ** page that stores the required pointer. PTRMAP_PTROFFSET returns
44517 ** the offset of the requested map entry.
44518 **
44519 ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
44520 ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
44521 ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
44522 ** this test.
44523 */
44524 #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
44525 #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
44526 #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
44527
44528 /*
44529 ** The pointer map is a lookup table that identifies the parent page for
44530 ** each child page in the database file.  The parent page is the page that
44531 ** contains a pointer to the child.  Every page in the database contains
44532 ** 0 or 1 parent pages.  (In this context 'database page' refers
44533 ** to any page that is not part of the pointer map itself.)  Each pointer map
44534 ** entry consists of a single byte 'type' and a 4 byte parent page number.
44535 ** The PTRMAP_XXX identifiers below are the valid types.
44536 **
44537 ** The purpose of the pointer map is to facility moving pages from one
44538 ** position in the file to another as part of autovacuum.  When a page
44539 ** is moved, the pointer in its parent must be updated to point to the
44540 ** new location.  The pointer map is used to locate the parent page quickly.
44541 **
44542 ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
44543 **                  used in this case.
44544 **
44545 ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number 
44546 **                  is not used in this case.
44547 **
44548 ** PTRMAP_OVERFLOW1: The database page is the first page in a list of 
44549 **                   overflow pages. The page number identifies the page that
44550 **                   contains the cell with a pointer to this overflow page.
44551 **
44552 ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
44553 **                   overflow pages. The page-number identifies the previous
44554 **                   page in the overflow page list.
44555 **
44556 ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
44557 **               identifies the parent page in the btree.
44558 */
44559 #define PTRMAP_ROOTPAGE 1
44560 #define PTRMAP_FREEPAGE 2
44561 #define PTRMAP_OVERFLOW1 3
44562 #define PTRMAP_OVERFLOW2 4
44563 #define PTRMAP_BTREE 5
44564
44565 /* A bunch of assert() statements to check the transaction state variables
44566 ** of handle p (type Btree*) are internally consistent.
44567 */
44568 #define btreeIntegrity(p) \
44569   assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
44570   assert( p->pBt->inTransaction>=p->inTrans ); 
44571
44572
44573 /*
44574 ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
44575 ** if the database supports auto-vacuum or not. Because it is used
44576 ** within an expression that is an argument to another macro 
44577 ** (sqliteMallocRaw), it is not possible to use conditional compilation.
44578 ** So, this macro is defined instead.
44579 */
44580 #ifndef SQLITE_OMIT_AUTOVACUUM
44581 #define ISAUTOVACUUM (pBt->autoVacuum)
44582 #else
44583 #define ISAUTOVACUUM 0
44584 #endif
44585
44586
44587 /*
44588 ** This structure is passed around through all the sanity checking routines
44589 ** in order to keep track of some global state information.
44590 */
44591 typedef struct IntegrityCk IntegrityCk;
44592 struct IntegrityCk {
44593   BtShared *pBt;    /* The tree being checked out */
44594   Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */
44595   Pgno nPage;       /* Number of pages in the database */
44596   int *anRef;       /* Number of times each page is referenced */
44597   int mxErr;        /* Stop accumulating errors when this reaches zero */
44598   int nErr;         /* Number of messages written to zErrMsg so far */
44599   int mallocFailed; /* A memory allocation error has occurred */
44600   StrAccum errMsg;  /* Accumulate the error message text here */
44601 };
44602
44603 /*
44604 ** Read or write a two- and four-byte big-endian integer values.
44605 */
44606 #define get2byte(x)   ((x)[0]<<8 | (x)[1])
44607 #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
44608 #define get4byte sqlite3Get4byte
44609 #define put4byte sqlite3Put4byte
44610
44611 /************** End of btreeInt.h ********************************************/
44612 /************** Continuing where we left off in btmutex.c ********************/
44613 #ifndef SQLITE_OMIT_SHARED_CACHE
44614 #if SQLITE_THREADSAFE
44615
44616 /*
44617 ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
44618 ** set BtShared.db to the database handle associated with p and the
44619 ** p->locked boolean to true.
44620 */
44621 static void lockBtreeMutex(Btree *p){
44622   assert( p->locked==0 );
44623   assert( sqlite3_mutex_notheld(p->pBt->mutex) );
44624   assert( sqlite3_mutex_held(p->db->mutex) );
44625
44626   sqlite3_mutex_enter(p->pBt->mutex);
44627   p->pBt->db = p->db;
44628   p->locked = 1;
44629 }
44630
44631 /*
44632 ** Release the BtShared mutex associated with B-Tree handle p and
44633 ** clear the p->locked boolean.
44634 */
44635 static void unlockBtreeMutex(Btree *p){
44636   assert( p->locked==1 );
44637   assert( sqlite3_mutex_held(p->pBt->mutex) );
44638   assert( sqlite3_mutex_held(p->db->mutex) );
44639   assert( p->db==p->pBt->db );
44640
44641   sqlite3_mutex_leave(p->pBt->mutex);
44642   p->locked = 0;
44643 }
44644
44645 /*
44646 ** Enter a mutex on the given BTree object.
44647 **
44648 ** If the object is not sharable, then no mutex is ever required
44649 ** and this routine is a no-op.  The underlying mutex is non-recursive.
44650 ** But we keep a reference count in Btree.wantToLock so the behavior
44651 ** of this interface is recursive.
44652 **
44653 ** To avoid deadlocks, multiple Btrees are locked in the same order
44654 ** by all database connections.  The p->pNext is a list of other
44655 ** Btrees belonging to the same database connection as the p Btree
44656 ** which need to be locked after p.  If we cannot get a lock on
44657 ** p, then first unlock all of the others on p->pNext, then wait
44658 ** for the lock to become available on p, then relock all of the
44659 ** subsequent Btrees that desire a lock.
44660 */
44661 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
44662   Btree *pLater;
44663
44664   /* Some basic sanity checking on the Btree.  The list of Btrees
44665   ** connected by pNext and pPrev should be in sorted order by
44666   ** Btree.pBt value. All elements of the list should belong to
44667   ** the same connection. Only shared Btrees are on the list. */
44668   assert( p->pNext==0 || p->pNext->pBt>p->pBt );
44669   assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
44670   assert( p->pNext==0 || p->pNext->db==p->db );
44671   assert( p->pPrev==0 || p->pPrev->db==p->db );
44672   assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
44673
44674   /* Check for locking consistency */
44675   assert( !p->locked || p->wantToLock>0 );
44676   assert( p->sharable || p->wantToLock==0 );
44677
44678   /* We should already hold a lock on the database connection */
44679   assert( sqlite3_mutex_held(p->db->mutex) );
44680
44681   /* Unless the database is sharable and unlocked, then BtShared.db
44682   ** should already be set correctly. */
44683   assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
44684
44685   if( !p->sharable ) return;
44686   p->wantToLock++;
44687   if( p->locked ) return;
44688
44689   /* In most cases, we should be able to acquire the lock we
44690   ** want without having to go throught the ascending lock
44691   ** procedure that follows.  Just be sure not to block.
44692   */
44693   if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
44694     p->pBt->db = p->db;
44695     p->locked = 1;
44696     return;
44697   }
44698
44699   /* To avoid deadlock, first release all locks with a larger
44700   ** BtShared address.  Then acquire our lock.  Then reacquire
44701   ** the other BtShared locks that we used to hold in ascending
44702   ** order.
44703   */
44704   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
44705     assert( pLater->sharable );
44706     assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
44707     assert( !pLater->locked || pLater->wantToLock>0 );
44708     if( pLater->locked ){
44709       unlockBtreeMutex(pLater);
44710     }
44711   }
44712   lockBtreeMutex(p);
44713   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
44714     if( pLater->wantToLock ){
44715       lockBtreeMutex(pLater);
44716     }
44717   }
44718 }
44719
44720 /*
44721 ** Exit the recursive mutex on a Btree.
44722 */
44723 SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
44724   if( p->sharable ){
44725     assert( p->wantToLock>0 );
44726     p->wantToLock--;
44727     if( p->wantToLock==0 ){
44728       unlockBtreeMutex(p);
44729     }
44730   }
44731 }
44732
44733 #ifndef NDEBUG
44734 /*
44735 ** Return true if the BtShared mutex is held on the btree, or if the
44736 ** B-Tree is not marked as sharable.
44737 **
44738 ** This routine is used only from within assert() statements.
44739 */
44740 SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
44741   assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
44742   assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
44743   assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
44744   assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
44745
44746   return (p->sharable==0 || p->locked);
44747 }
44748 #endif
44749
44750
44751 #ifndef SQLITE_OMIT_INCRBLOB
44752 /*
44753 ** Enter and leave a mutex on a Btree given a cursor owned by that
44754 ** Btree.  These entry points are used by incremental I/O and can be
44755 ** omitted if that module is not used.
44756 */
44757 SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
44758   sqlite3BtreeEnter(pCur->pBtree);
44759 }
44760 SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
44761   sqlite3BtreeLeave(pCur->pBtree);
44762 }
44763 #endif /* SQLITE_OMIT_INCRBLOB */
44764
44765
44766 /*
44767 ** Enter the mutex on every Btree associated with a database
44768 ** connection.  This is needed (for example) prior to parsing
44769 ** a statement since we will be comparing table and column names
44770 ** against all schemas and we do not want those schemas being
44771 ** reset out from under us.
44772 **
44773 ** There is a corresponding leave-all procedures.
44774 **
44775 ** Enter the mutexes in accending order by BtShared pointer address
44776 ** to avoid the possibility of deadlock when two threads with
44777 ** two or more btrees in common both try to lock all their btrees
44778 ** at the same instant.
44779 */
44780 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
44781   int i;
44782   Btree *p, *pLater;
44783   assert( sqlite3_mutex_held(db->mutex) );
44784   for(i=0; i<db->nDb; i++){
44785     p = db->aDb[i].pBt;
44786     assert( !p || (p->locked==0 && p->sharable) || p->pBt->db==p->db );
44787     if( p && p->sharable ){
44788       p->wantToLock++;
44789       if( !p->locked ){
44790         assert( p->wantToLock==1 );
44791         while( p->pPrev ) p = p->pPrev;
44792         /* Reason for ALWAYS:  There must be at least on unlocked Btree in
44793         ** the chain.  Otherwise the !p->locked test above would have failed */
44794         while( p->locked && ALWAYS(p->pNext) ) p = p->pNext;
44795         for(pLater = p->pNext; pLater; pLater=pLater->pNext){
44796           if( pLater->locked ){
44797             unlockBtreeMutex(pLater);
44798           }
44799         }
44800         while( p ){
44801           lockBtreeMutex(p);
44802           p = p->pNext;
44803         }
44804       }
44805     }
44806   }
44807 }
44808 SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
44809   int i;
44810   Btree *p;
44811   assert( sqlite3_mutex_held(db->mutex) );
44812   for(i=0; i<db->nDb; i++){
44813     p = db->aDb[i].pBt;
44814     if( p && p->sharable ){
44815       assert( p->wantToLock>0 );
44816       p->wantToLock--;
44817       if( p->wantToLock==0 ){
44818         unlockBtreeMutex(p);
44819       }
44820     }
44821   }
44822 }
44823
44824 #ifndef NDEBUG
44825 /*
44826 ** Return true if the current thread holds the database connection
44827 ** mutex and all required BtShared mutexes.
44828 **
44829 ** This routine is used inside assert() statements only.
44830 */
44831 SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
44832   int i;
44833   if( !sqlite3_mutex_held(db->mutex) ){
44834     return 0;
44835   }
44836   for(i=0; i<db->nDb; i++){
44837     Btree *p;
44838     p = db->aDb[i].pBt;
44839     if( p && p->sharable &&
44840          (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
44841       return 0;
44842     }
44843   }
44844   return 1;
44845 }
44846 #endif /* NDEBUG */
44847
44848 /*
44849 ** Add a new Btree pointer to a BtreeMutexArray. 
44850 ** if the pointer can possibly be shared with
44851 ** another database connection.
44852 **
44853 ** The pointers are kept in sorted order by pBtree->pBt.  That
44854 ** way when we go to enter all the mutexes, we can enter them
44855 ** in order without every having to backup and retry and without
44856 ** worrying about deadlock.
44857 **
44858 ** The number of shared btrees will always be small (usually 0 or 1)
44859 ** so an insertion sort is an adequate algorithm here.
44860 */
44861 SQLITE_PRIVATE void sqlite3BtreeMutexArrayInsert(BtreeMutexArray *pArray, Btree *pBtree){
44862   int i, j;
44863   BtShared *pBt;
44864   if( pBtree==0 || pBtree->sharable==0 ) return;
44865 #ifndef NDEBUG
44866   {
44867     for(i=0; i<pArray->nMutex; i++){
44868       assert( pArray->aBtree[i]!=pBtree );
44869     }
44870   }
44871 #endif
44872   assert( pArray->nMutex>=0 );
44873   assert( pArray->nMutex<ArraySize(pArray->aBtree)-1 );
44874   pBt = pBtree->pBt;
44875   for(i=0; i<pArray->nMutex; i++){
44876     assert( pArray->aBtree[i]!=pBtree );
44877     if( pArray->aBtree[i]->pBt>pBt ){
44878       for(j=pArray->nMutex; j>i; j--){
44879         pArray->aBtree[j] = pArray->aBtree[j-1];
44880       }
44881       pArray->aBtree[i] = pBtree;
44882       pArray->nMutex++;
44883       return;
44884     }
44885   }
44886   pArray->aBtree[pArray->nMutex++] = pBtree;
44887 }
44888
44889 /*
44890 ** Enter the mutex of every btree in the array.  This routine is
44891 ** called at the beginning of sqlite3VdbeExec().  The mutexes are
44892 ** exited at the end of the same function.
44893 */
44894 SQLITE_PRIVATE void sqlite3BtreeMutexArrayEnter(BtreeMutexArray *pArray){
44895   int i;
44896   for(i=0; i<pArray->nMutex; i++){
44897     Btree *p = pArray->aBtree[i];
44898     /* Some basic sanity checking */
44899     assert( i==0 || pArray->aBtree[i-1]->pBt<p->pBt );
44900     assert( !p->locked || p->wantToLock>0 );
44901
44902     /* We should already hold a lock on the database connection */
44903     assert( sqlite3_mutex_held(p->db->mutex) );
44904
44905     /* The Btree is sharable because only sharable Btrees are entered
44906     ** into the array in the first place. */
44907     assert( p->sharable );
44908
44909     p->wantToLock++;
44910     if( !p->locked ){
44911       lockBtreeMutex(p);
44912     }
44913   }
44914 }
44915
44916 /*
44917 ** Leave the mutex of every btree in the group.
44918 */
44919 SQLITE_PRIVATE void sqlite3BtreeMutexArrayLeave(BtreeMutexArray *pArray){
44920   int i;
44921   for(i=0; i<pArray->nMutex; i++){
44922     Btree *p = pArray->aBtree[i];
44923     /* Some basic sanity checking */
44924     assert( i==0 || pArray->aBtree[i-1]->pBt<p->pBt );
44925     assert( p->locked );
44926     assert( p->wantToLock>0 );
44927
44928     /* We should already hold a lock on the database connection */
44929     assert( sqlite3_mutex_held(p->db->mutex) );
44930
44931     p->wantToLock--;
44932     if( p->wantToLock==0 ){
44933       unlockBtreeMutex(p);
44934     }
44935   }
44936 }
44937
44938 #else
44939 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
44940   p->pBt->db = p->db;
44941 }
44942 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
44943   int i;
44944   for(i=0; i<db->nDb; i++){
44945     Btree *p = db->aDb[i].pBt;
44946     if( p ){
44947       p->pBt->db = p->db;
44948     }
44949   }
44950 }
44951 #endif /* if SQLITE_THREADSAFE */
44952 #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
44953
44954 /************** End of btmutex.c *********************************************/
44955 /************** Begin file btree.c *******************************************/
44956 /*
44957 ** 2004 April 6
44958 **
44959 ** The author disclaims copyright to this source code.  In place of
44960 ** a legal notice, here is a blessing:
44961 **
44962 **    May you do good and not evil.
44963 **    May you find forgiveness for yourself and forgive others.
44964 **    May you share freely, never taking more than you give.
44965 **
44966 *************************************************************************
44967 ** This file implements a external (disk-based) database using BTrees.
44968 ** See the header comment on "btreeInt.h" for additional information.
44969 ** Including a description of file format and an overview of operation.
44970 */
44971
44972 /*
44973 ** The header string that appears at the beginning of every
44974 ** SQLite database.
44975 */
44976 static const char zMagicHeader[] = SQLITE_FILE_HEADER;
44977
44978 /*
44979 ** Set this global variable to 1 to enable tracing using the TRACE
44980 ** macro.
44981 */
44982 #if 0
44983 int sqlite3BtreeTrace=1;  /* True to enable tracing */
44984 # define TRACE(X)  if(sqlite3BtreeTrace){printf X;fflush(stdout);}
44985 #else
44986 # define TRACE(X)
44987 #endif
44988
44989 /*
44990 ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
44991 ** But if the value is zero, make it 65536.
44992 **
44993 ** This routine is used to extract the "offset to cell content area" value
44994 ** from the header of a btree page.  If the page size is 65536 and the page
44995 ** is empty, the offset should be 65536, but the 2-byte value stores zero.
44996 ** This routine makes the necessary adjustment to 65536.
44997 */
44998 #define get2byteNotZero(X)  (((((int)get2byte(X))-1)&0xffff)+1)
44999
45000 #ifndef SQLITE_OMIT_SHARED_CACHE
45001 /*
45002 ** A list of BtShared objects that are eligible for participation
45003 ** in shared cache.  This variable has file scope during normal builds,
45004 ** but the test harness needs to access it so we make it global for 
45005 ** test builds.
45006 **
45007 ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
45008 */
45009 #ifdef SQLITE_TEST
45010 SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
45011 #else
45012 static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
45013 #endif
45014 #endif /* SQLITE_OMIT_SHARED_CACHE */
45015
45016 #ifndef SQLITE_OMIT_SHARED_CACHE
45017 /*
45018 ** Enable or disable the shared pager and schema features.
45019 **
45020 ** This routine has no effect on existing database connections.
45021 ** The shared cache setting effects only future calls to
45022 ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
45023 */
45024 SQLITE_API int sqlite3_enable_shared_cache(int enable){
45025   sqlite3GlobalConfig.sharedCacheEnabled = enable;
45026   return SQLITE_OK;
45027 }
45028 #endif
45029
45030
45031
45032 #ifdef SQLITE_OMIT_SHARED_CACHE
45033   /*
45034   ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
45035   ** and clearAllSharedCacheTableLocks()
45036   ** manipulate entries in the BtShared.pLock linked list used to store
45037   ** shared-cache table level locks. If the library is compiled with the
45038   ** shared-cache feature disabled, then there is only ever one user
45039   ** of each BtShared structure and so this locking is not necessary. 
45040   ** So define the lock related functions as no-ops.
45041   */
45042   #define querySharedCacheTableLock(a,b,c) SQLITE_OK
45043   #define setSharedCacheTableLock(a,b,c) SQLITE_OK
45044   #define clearAllSharedCacheTableLocks(a)
45045   #define downgradeAllSharedCacheTableLocks(a)
45046   #define hasSharedCacheTableLock(a,b,c,d) 1
45047   #define hasReadConflicts(a, b) 0
45048 #endif
45049
45050 #ifndef SQLITE_OMIT_SHARED_CACHE
45051
45052 #ifdef SQLITE_DEBUG
45053 /*
45054 **** This function is only used as part of an assert() statement. ***
45055 **
45056 ** Check to see if pBtree holds the required locks to read or write to the 
45057 ** table with root page iRoot.   Return 1 if it does and 0 if not.
45058 **
45059 ** For example, when writing to a table with root-page iRoot via 
45060 ** Btree connection pBtree:
45061 **
45062 **    assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
45063 **
45064 ** When writing to an index that resides in a sharable database, the 
45065 ** caller should have first obtained a lock specifying the root page of
45066 ** the corresponding table. This makes things a bit more complicated,
45067 ** as this module treats each table as a separate structure. To determine
45068 ** the table corresponding to the index being written, this
45069 ** function has to search through the database schema.
45070 **
45071 ** Instead of a lock on the table/index rooted at page iRoot, the caller may
45072 ** hold a write-lock on the schema table (root page 1). This is also
45073 ** acceptable.
45074 */
45075 static int hasSharedCacheTableLock(
45076   Btree *pBtree,         /* Handle that must hold lock */
45077   Pgno iRoot,            /* Root page of b-tree */
45078   int isIndex,           /* True if iRoot is the root of an index b-tree */
45079   int eLockType          /* Required lock type (READ_LOCK or WRITE_LOCK) */
45080 ){
45081   Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
45082   Pgno iTab = 0;
45083   BtLock *pLock;
45084
45085   /* If this database is not shareable, or if the client is reading
45086   ** and has the read-uncommitted flag set, then no lock is required. 
45087   ** Return true immediately.
45088   */
45089   if( (pBtree->sharable==0)
45090    || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
45091   ){
45092     return 1;
45093   }
45094
45095   /* If the client is reading  or writing an index and the schema is
45096   ** not loaded, then it is too difficult to actually check to see if
45097   ** the correct locks are held.  So do not bother - just return true.
45098   ** This case does not come up very often anyhow.
45099   */
45100   if( isIndex && (!pSchema || (pSchema->flags&DB_SchemaLoaded)==0) ){
45101     return 1;
45102   }
45103
45104   /* Figure out the root-page that the lock should be held on. For table
45105   ** b-trees, this is just the root page of the b-tree being read or
45106   ** written. For index b-trees, it is the root page of the associated
45107   ** table.  */
45108   if( isIndex ){
45109     HashElem *p;
45110     for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
45111       Index *pIdx = (Index *)sqliteHashData(p);
45112       if( pIdx->tnum==(int)iRoot ){
45113         iTab = pIdx->pTable->tnum;
45114       }
45115     }
45116   }else{
45117     iTab = iRoot;
45118   }
45119
45120   /* Search for the required lock. Either a write-lock on root-page iTab, a 
45121   ** write-lock on the schema table, or (if the client is reading) a
45122   ** read-lock on iTab will suffice. Return 1 if any of these are found.  */
45123   for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
45124     if( pLock->pBtree==pBtree 
45125      && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
45126      && pLock->eLock>=eLockType 
45127     ){
45128       return 1;
45129     }
45130   }
45131
45132   /* Failed to find the required lock. */
45133   return 0;
45134 }
45135 #endif /* SQLITE_DEBUG */
45136
45137 #ifdef SQLITE_DEBUG
45138 /*
45139 **** This function may be used as part of assert() statements only. ****
45140 **
45141 ** Return true if it would be illegal for pBtree to write into the
45142 ** table or index rooted at iRoot because other shared connections are
45143 ** simultaneously reading that same table or index.
45144 **
45145 ** It is illegal for pBtree to write if some other Btree object that
45146 ** shares the same BtShared object is currently reading or writing
45147 ** the iRoot table.  Except, if the other Btree object has the
45148 ** read-uncommitted flag set, then it is OK for the other object to
45149 ** have a read cursor.
45150 **
45151 ** For example, before writing to any part of the table or index
45152 ** rooted at page iRoot, one should call:
45153 **
45154 **    assert( !hasReadConflicts(pBtree, iRoot) );
45155 */
45156 static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
45157   BtCursor *p;
45158   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
45159     if( p->pgnoRoot==iRoot 
45160      && p->pBtree!=pBtree
45161      && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
45162     ){
45163       return 1;
45164     }
45165   }
45166   return 0;
45167 }
45168 #endif    /* #ifdef SQLITE_DEBUG */
45169
45170 /*
45171 ** Query to see if Btree handle p may obtain a lock of type eLock 
45172 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
45173 ** SQLITE_OK if the lock may be obtained (by calling
45174 ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
45175 */
45176 static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
45177   BtShared *pBt = p->pBt;
45178   BtLock *pIter;
45179
45180   assert( sqlite3BtreeHoldsMutex(p) );
45181   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
45182   assert( p->db!=0 );
45183   assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
45184   
45185   /* If requesting a write-lock, then the Btree must have an open write
45186   ** transaction on this file. And, obviously, for this to be so there 
45187   ** must be an open write transaction on the file itself.
45188   */
45189   assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
45190   assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
45191   
45192   /* This routine is a no-op if the shared-cache is not enabled */
45193   if( !p->sharable ){
45194     return SQLITE_OK;
45195   }
45196
45197   /* If some other connection is holding an exclusive lock, the
45198   ** requested lock may not be obtained.
45199   */
45200   if( pBt->pWriter!=p && pBt->isExclusive ){
45201     sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
45202     return SQLITE_LOCKED_SHAREDCACHE;
45203   }
45204
45205   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
45206     /* The condition (pIter->eLock!=eLock) in the following if(...) 
45207     ** statement is a simplification of:
45208     **
45209     **   (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
45210     **
45211     ** since we know that if eLock==WRITE_LOCK, then no other connection
45212     ** may hold a WRITE_LOCK on any table in this file (since there can
45213     ** only be a single writer).
45214     */
45215     assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
45216     assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
45217     if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
45218       sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
45219       if( eLock==WRITE_LOCK ){
45220         assert( p==pBt->pWriter );
45221         pBt->isPending = 1;
45222       }
45223       return SQLITE_LOCKED_SHAREDCACHE;
45224     }
45225   }
45226   return SQLITE_OK;
45227 }
45228 #endif /* !SQLITE_OMIT_SHARED_CACHE */
45229
45230 #ifndef SQLITE_OMIT_SHARED_CACHE
45231 /*
45232 ** Add a lock on the table with root-page iTable to the shared-btree used
45233 ** by Btree handle p. Parameter eLock must be either READ_LOCK or 
45234 ** WRITE_LOCK.
45235 **
45236 ** This function assumes the following:
45237 **
45238 **   (a) The specified Btree object p is connected to a sharable
45239 **       database (one with the BtShared.sharable flag set), and
45240 **
45241 **   (b) No other Btree objects hold a lock that conflicts
45242 **       with the requested lock (i.e. querySharedCacheTableLock() has
45243 **       already been called and returned SQLITE_OK).
45244 **
45245 ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM 
45246 ** is returned if a malloc attempt fails.
45247 */
45248 static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
45249   BtShared *pBt = p->pBt;
45250   BtLock *pLock = 0;
45251   BtLock *pIter;
45252
45253   assert( sqlite3BtreeHoldsMutex(p) );
45254   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
45255   assert( p->db!=0 );
45256
45257   /* A connection with the read-uncommitted flag set will never try to
45258   ** obtain a read-lock using this function. The only read-lock obtained
45259   ** by a connection in read-uncommitted mode is on the sqlite_master 
45260   ** table, and that lock is obtained in BtreeBeginTrans().  */
45261   assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
45262
45263   /* This function should only be called on a sharable b-tree after it 
45264   ** has been determined that no other b-tree holds a conflicting lock.  */
45265   assert( p->sharable );
45266   assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
45267
45268   /* First search the list for an existing lock on this table. */
45269   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
45270     if( pIter->iTable==iTable && pIter->pBtree==p ){
45271       pLock = pIter;
45272       break;
45273     }
45274   }
45275
45276   /* If the above search did not find a BtLock struct associating Btree p
45277   ** with table iTable, allocate one and link it into the list.
45278   */
45279   if( !pLock ){
45280     pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
45281     if( !pLock ){
45282       return SQLITE_NOMEM;
45283     }
45284     pLock->iTable = iTable;
45285     pLock->pBtree = p;
45286     pLock->pNext = pBt->pLock;
45287     pBt->pLock = pLock;
45288   }
45289
45290   /* Set the BtLock.eLock variable to the maximum of the current lock
45291   ** and the requested lock. This means if a write-lock was already held
45292   ** and a read-lock requested, we don't incorrectly downgrade the lock.
45293   */
45294   assert( WRITE_LOCK>READ_LOCK );
45295   if( eLock>pLock->eLock ){
45296     pLock->eLock = eLock;
45297   }
45298
45299   return SQLITE_OK;
45300 }
45301 #endif /* !SQLITE_OMIT_SHARED_CACHE */
45302
45303 #ifndef SQLITE_OMIT_SHARED_CACHE
45304 /*
45305 ** Release all the table locks (locks obtained via calls to
45306 ** the setSharedCacheTableLock() procedure) held by Btree object p.
45307 **
45308 ** This function assumes that Btree p has an open read or write 
45309 ** transaction. If it does not, then the BtShared.isPending variable
45310 ** may be incorrectly cleared.
45311 */
45312 static void clearAllSharedCacheTableLocks(Btree *p){
45313   BtShared *pBt = p->pBt;
45314   BtLock **ppIter = &pBt->pLock;
45315
45316   assert( sqlite3BtreeHoldsMutex(p) );
45317   assert( p->sharable || 0==*ppIter );
45318   assert( p->inTrans>0 );
45319
45320   while( *ppIter ){
45321     BtLock *pLock = *ppIter;
45322     assert( pBt->isExclusive==0 || pBt->pWriter==pLock->pBtree );
45323     assert( pLock->pBtree->inTrans>=pLock->eLock );
45324     if( pLock->pBtree==p ){
45325       *ppIter = pLock->pNext;
45326       assert( pLock->iTable!=1 || pLock==&p->lock );
45327       if( pLock->iTable!=1 ){
45328         sqlite3_free(pLock);
45329       }
45330     }else{
45331       ppIter = &pLock->pNext;
45332     }
45333   }
45334
45335   assert( pBt->isPending==0 || pBt->pWriter );
45336   if( pBt->pWriter==p ){
45337     pBt->pWriter = 0;
45338     pBt->isExclusive = 0;
45339     pBt->isPending = 0;
45340   }else if( pBt->nTransaction==2 ){
45341     /* This function is called when Btree p is concluding its 
45342     ** transaction. If there currently exists a writer, and p is not
45343     ** that writer, then the number of locks held by connections other
45344     ** than the writer must be about to drop to zero. In this case
45345     ** set the isPending flag to 0.
45346     **
45347     ** If there is not currently a writer, then BtShared.isPending must
45348     ** be zero already. So this next line is harmless in that case.
45349     */
45350     pBt->isPending = 0;
45351   }
45352 }
45353
45354 /*
45355 ** This function changes all write-locks held by Btree p into read-locks.
45356 */
45357 static void downgradeAllSharedCacheTableLocks(Btree *p){
45358   BtShared *pBt = p->pBt;
45359   if( pBt->pWriter==p ){
45360     BtLock *pLock;
45361     pBt->pWriter = 0;
45362     pBt->isExclusive = 0;
45363     pBt->isPending = 0;
45364     for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
45365       assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
45366       pLock->eLock = READ_LOCK;
45367     }
45368   }
45369 }
45370
45371 #endif /* SQLITE_OMIT_SHARED_CACHE */
45372
45373 static void releasePage(MemPage *pPage);  /* Forward reference */
45374
45375 /*
45376 ***** This routine is used inside of assert() only ****
45377 **
45378 ** Verify that the cursor holds the mutex on its BtShared
45379 */
45380 #ifdef SQLITE_DEBUG
45381 static int cursorHoldsMutex(BtCursor *p){
45382   return sqlite3_mutex_held(p->pBt->mutex);
45383 }
45384 #endif
45385
45386
45387 #ifndef SQLITE_OMIT_INCRBLOB
45388 /*
45389 ** Invalidate the overflow page-list cache for cursor pCur, if any.
45390 */
45391 static void invalidateOverflowCache(BtCursor *pCur){
45392   assert( cursorHoldsMutex(pCur) );
45393   sqlite3_free(pCur->aOverflow);
45394   pCur->aOverflow = 0;
45395 }
45396
45397 /*
45398 ** Invalidate the overflow page-list cache for all cursors opened
45399 ** on the shared btree structure pBt.
45400 */
45401 static void invalidateAllOverflowCache(BtShared *pBt){
45402   BtCursor *p;
45403   assert( sqlite3_mutex_held(pBt->mutex) );
45404   for(p=pBt->pCursor; p; p=p->pNext){
45405     invalidateOverflowCache(p);
45406   }
45407 }
45408
45409 /*
45410 ** This function is called before modifying the contents of a table
45411 ** to invalidate any incrblob cursors that are open on the
45412 ** row or one of the rows being modified.
45413 **
45414 ** If argument isClearTable is true, then the entire contents of the
45415 ** table is about to be deleted. In this case invalidate all incrblob
45416 ** cursors open on any row within the table with root-page pgnoRoot.
45417 **
45418 ** Otherwise, if argument isClearTable is false, then the row with
45419 ** rowid iRow is being replaced or deleted. In this case invalidate
45420 ** only those incrblob cursors open on that specific row.
45421 */
45422 static void invalidateIncrblobCursors(
45423   Btree *pBtree,          /* The database file to check */
45424   i64 iRow,               /* The rowid that might be changing */
45425   int isClearTable        /* True if all rows are being deleted */
45426 ){
45427   BtCursor *p;
45428   BtShared *pBt = pBtree->pBt;
45429   assert( sqlite3BtreeHoldsMutex(pBtree) );
45430   for(p=pBt->pCursor; p; p=p->pNext){
45431     if( p->isIncrblobHandle && (isClearTable || p->info.nKey==iRow) ){
45432       p->eState = CURSOR_INVALID;
45433     }
45434   }
45435 }
45436
45437 #else
45438   /* Stub functions when INCRBLOB is omitted */
45439   #define invalidateOverflowCache(x)
45440   #define invalidateAllOverflowCache(x)
45441   #define invalidateIncrblobCursors(x,y,z)
45442 #endif /* SQLITE_OMIT_INCRBLOB */
45443
45444 /*
45445 ** Set bit pgno of the BtShared.pHasContent bitvec. This is called 
45446 ** when a page that previously contained data becomes a free-list leaf 
45447 ** page.
45448 **
45449 ** The BtShared.pHasContent bitvec exists to work around an obscure
45450 ** bug caused by the interaction of two useful IO optimizations surrounding
45451 ** free-list leaf pages:
45452 **
45453 **   1) When all data is deleted from a page and the page becomes
45454 **      a free-list leaf page, the page is not written to the database
45455 **      (as free-list leaf pages contain no meaningful data). Sometimes
45456 **      such a page is not even journalled (as it will not be modified,
45457 **      why bother journalling it?).
45458 **
45459 **   2) When a free-list leaf page is reused, its content is not read
45460 **      from the database or written to the journal file (why should it
45461 **      be, if it is not at all meaningful?).
45462 **
45463 ** By themselves, these optimizations work fine and provide a handy
45464 ** performance boost to bulk delete or insert operations. However, if
45465 ** a page is moved to the free-list and then reused within the same
45466 ** transaction, a problem comes up. If the page is not journalled when
45467 ** it is moved to the free-list and it is also not journalled when it
45468 ** is extracted from the free-list and reused, then the original data
45469 ** may be lost. In the event of a rollback, it may not be possible
45470 ** to restore the database to its original configuration.
45471 **
45472 ** The solution is the BtShared.pHasContent bitvec. Whenever a page is 
45473 ** moved to become a free-list leaf page, the corresponding bit is
45474 ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
45475 ** optimization 2 above is omitted if the corresponding bit is already
45476 ** set in BtShared.pHasContent. The contents of the bitvec are cleared
45477 ** at the end of every transaction.
45478 */
45479 static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
45480   int rc = SQLITE_OK;
45481   if( !pBt->pHasContent ){
45482     assert( pgno<=pBt->nPage );
45483     pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
45484     if( !pBt->pHasContent ){
45485       rc = SQLITE_NOMEM;
45486     }
45487   }
45488   if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
45489     rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
45490   }
45491   return rc;
45492 }
45493
45494 /*
45495 ** Query the BtShared.pHasContent vector.
45496 **
45497 ** This function is called when a free-list leaf page is removed from the
45498 ** free-list for reuse. It returns false if it is safe to retrieve the
45499 ** page from the pager layer with the 'no-content' flag set. True otherwise.
45500 */
45501 static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
45502   Bitvec *p = pBt->pHasContent;
45503   return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
45504 }
45505
45506 /*
45507 ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
45508 ** invoked at the conclusion of each write-transaction.
45509 */
45510 static void btreeClearHasContent(BtShared *pBt){
45511   sqlite3BitvecDestroy(pBt->pHasContent);
45512   pBt->pHasContent = 0;
45513 }
45514
45515 /*
45516 ** Save the current cursor position in the variables BtCursor.nKey 
45517 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
45518 **
45519 ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
45520 ** prior to calling this routine.  
45521 */
45522 static int saveCursorPosition(BtCursor *pCur){
45523   int rc;
45524
45525   assert( CURSOR_VALID==pCur->eState );
45526   assert( 0==pCur->pKey );
45527   assert( cursorHoldsMutex(pCur) );
45528
45529   rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
45530   assert( rc==SQLITE_OK );  /* KeySize() cannot fail */
45531
45532   /* If this is an intKey table, then the above call to BtreeKeySize()
45533   ** stores the integer key in pCur->nKey. In this case this value is
45534   ** all that is required. Otherwise, if pCur is not open on an intKey
45535   ** table, then malloc space for and store the pCur->nKey bytes of key 
45536   ** data.
45537   */
45538   if( 0==pCur->apPage[0]->intKey ){
45539     void *pKey = sqlite3Malloc( (int)pCur->nKey );
45540     if( pKey ){
45541       rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
45542       if( rc==SQLITE_OK ){
45543         pCur->pKey = pKey;
45544       }else{
45545         sqlite3_free(pKey);
45546       }
45547     }else{
45548       rc = SQLITE_NOMEM;
45549     }
45550   }
45551   assert( !pCur->apPage[0]->intKey || !pCur->pKey );
45552
45553   if( rc==SQLITE_OK ){
45554     int i;
45555     for(i=0; i<=pCur->iPage; i++){
45556       releasePage(pCur->apPage[i]);
45557       pCur->apPage[i] = 0;
45558     }
45559     pCur->iPage = -1;
45560     pCur->eState = CURSOR_REQUIRESEEK;
45561   }
45562
45563   invalidateOverflowCache(pCur);
45564   return rc;
45565 }
45566
45567 /*
45568 ** Save the positions of all cursors (except pExcept) that are open on
45569 ** the table  with root-page iRoot. Usually, this is called just before cursor
45570 ** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
45571 */
45572 static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
45573   BtCursor *p;
45574   assert( sqlite3_mutex_held(pBt->mutex) );
45575   assert( pExcept==0 || pExcept->pBt==pBt );
45576   for(p=pBt->pCursor; p; p=p->pNext){
45577     if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) && 
45578         p->eState==CURSOR_VALID ){
45579       int rc = saveCursorPosition(p);
45580       if( SQLITE_OK!=rc ){
45581         return rc;
45582       }
45583     }
45584   }
45585   return SQLITE_OK;
45586 }
45587
45588 /*
45589 ** Clear the current cursor position.
45590 */
45591 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
45592   assert( cursorHoldsMutex(pCur) );
45593   sqlite3_free(pCur->pKey);
45594   pCur->pKey = 0;
45595   pCur->eState = CURSOR_INVALID;
45596 }
45597
45598 /*
45599 ** In this version of BtreeMoveto, pKey is a packed index record
45600 ** such as is generated by the OP_MakeRecord opcode.  Unpack the
45601 ** record and then call BtreeMovetoUnpacked() to do the work.
45602 */
45603 static int btreeMoveto(
45604   BtCursor *pCur,     /* Cursor open on the btree to be searched */
45605   const void *pKey,   /* Packed key if the btree is an index */
45606   i64 nKey,           /* Integer key for tables.  Size of pKey for indices */
45607   int bias,           /* Bias search to the high end */
45608   int *pRes           /* Write search results here */
45609 ){
45610   int rc;                    /* Status code */
45611   UnpackedRecord *pIdxKey;   /* Unpacked index key */
45612   char aSpace[150];          /* Temp space for pIdxKey - to avoid a malloc */
45613
45614   if( pKey ){
45615     assert( nKey==(i64)(int)nKey );
45616     pIdxKey = sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey,
45617                                       aSpace, sizeof(aSpace));
45618     if( pIdxKey==0 ) return SQLITE_NOMEM;
45619   }else{
45620     pIdxKey = 0;
45621   }
45622   rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
45623   if( pKey ){
45624     sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
45625   }
45626   return rc;
45627 }
45628
45629 /*
45630 ** Restore the cursor to the position it was in (or as close to as possible)
45631 ** when saveCursorPosition() was called. Note that this call deletes the 
45632 ** saved position info stored by saveCursorPosition(), so there can be
45633 ** at most one effective restoreCursorPosition() call after each 
45634 ** saveCursorPosition().
45635 */
45636 static int btreeRestoreCursorPosition(BtCursor *pCur){
45637   int rc;
45638   assert( cursorHoldsMutex(pCur) );
45639   assert( pCur->eState>=CURSOR_REQUIRESEEK );
45640   if( pCur->eState==CURSOR_FAULT ){
45641     return pCur->skipNext;
45642   }
45643   pCur->eState = CURSOR_INVALID;
45644   rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);
45645   if( rc==SQLITE_OK ){
45646     sqlite3_free(pCur->pKey);
45647     pCur->pKey = 0;
45648     assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
45649   }
45650   return rc;
45651 }
45652
45653 #define restoreCursorPosition(p) \
45654   (p->eState>=CURSOR_REQUIRESEEK ? \
45655          btreeRestoreCursorPosition(p) : \
45656          SQLITE_OK)
45657
45658 /*
45659 ** Determine whether or not a cursor has moved from the position it
45660 ** was last placed at.  Cursors can move when the row they are pointing
45661 ** at is deleted out from under them.
45662 **
45663 ** This routine returns an error code if something goes wrong.  The
45664 ** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
45665 */
45666 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
45667   int rc;
45668
45669   rc = restoreCursorPosition(pCur);
45670   if( rc ){
45671     *pHasMoved = 1;
45672     return rc;
45673   }
45674   if( pCur->eState!=CURSOR_VALID || pCur->skipNext!=0 ){
45675     *pHasMoved = 1;
45676   }else{
45677     *pHasMoved = 0;
45678   }
45679   return SQLITE_OK;
45680 }
45681
45682 #ifndef SQLITE_OMIT_AUTOVACUUM
45683 /*
45684 ** Given a page number of a regular database page, return the page
45685 ** number for the pointer-map page that contains the entry for the
45686 ** input page number.
45687 **
45688 ** Return 0 (not a valid page) for pgno==1 since there is
45689 ** no pointer map associated with page 1.  The integrity_check logic
45690 ** requires that ptrmapPageno(*,1)!=1.
45691 */
45692 static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
45693   int nPagesPerMapPage;
45694   Pgno iPtrMap, ret;
45695   assert( sqlite3_mutex_held(pBt->mutex) );
45696   if( pgno<2 ) return 0;
45697   nPagesPerMapPage = (pBt->usableSize/5)+1;
45698   iPtrMap = (pgno-2)/nPagesPerMapPage;
45699   ret = (iPtrMap*nPagesPerMapPage) + 2; 
45700   if( ret==PENDING_BYTE_PAGE(pBt) ){
45701     ret++;
45702   }
45703   return ret;
45704 }
45705
45706 /*
45707 ** Write an entry into the pointer map.
45708 **
45709 ** This routine updates the pointer map entry for page number 'key'
45710 ** so that it maps to type 'eType' and parent page number 'pgno'.
45711 **
45712 ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
45713 ** a no-op.  If an error occurs, the appropriate error code is written
45714 ** into *pRC.
45715 */
45716 static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
45717   DbPage *pDbPage;  /* The pointer map page */
45718   u8 *pPtrmap;      /* The pointer map data */
45719   Pgno iPtrmap;     /* The pointer map page number */
45720   int offset;       /* Offset in pointer map page */
45721   int rc;           /* Return code from subfunctions */
45722
45723   if( *pRC ) return;
45724
45725   assert( sqlite3_mutex_held(pBt->mutex) );
45726   /* The master-journal page number must never be used as a pointer map page */
45727   assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
45728
45729   assert( pBt->autoVacuum );
45730   if( key==0 ){
45731     *pRC = SQLITE_CORRUPT_BKPT;
45732     return;
45733   }
45734   iPtrmap = PTRMAP_PAGENO(pBt, key);
45735   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
45736   if( rc!=SQLITE_OK ){
45737     *pRC = rc;
45738     return;
45739   }
45740   offset = PTRMAP_PTROFFSET(iPtrmap, key);
45741   if( offset<0 ){
45742     *pRC = SQLITE_CORRUPT_BKPT;
45743     goto ptrmap_exit;
45744   }
45745   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
45746
45747   if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
45748     TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
45749     *pRC= rc = sqlite3PagerWrite(pDbPage);
45750     if( rc==SQLITE_OK ){
45751       pPtrmap[offset] = eType;
45752       put4byte(&pPtrmap[offset+1], parent);
45753     }
45754   }
45755
45756 ptrmap_exit:
45757   sqlite3PagerUnref(pDbPage);
45758 }
45759
45760 /*
45761 ** Read an entry from the pointer map.
45762 **
45763 ** This routine retrieves the pointer map entry for page 'key', writing
45764 ** the type and parent page number to *pEType and *pPgno respectively.
45765 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
45766 */
45767 static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
45768   DbPage *pDbPage;   /* The pointer map page */
45769   int iPtrmap;       /* Pointer map page index */
45770   u8 *pPtrmap;       /* Pointer map page data */
45771   int offset;        /* Offset of entry in pointer map */
45772   int rc;
45773
45774   assert( sqlite3_mutex_held(pBt->mutex) );
45775
45776   iPtrmap = PTRMAP_PAGENO(pBt, key);
45777   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
45778   if( rc!=0 ){
45779     return rc;
45780   }
45781   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
45782
45783   offset = PTRMAP_PTROFFSET(iPtrmap, key);
45784   assert( pEType!=0 );
45785   *pEType = pPtrmap[offset];
45786   if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
45787
45788   sqlite3PagerUnref(pDbPage);
45789   if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
45790   return SQLITE_OK;
45791 }
45792
45793 #else /* if defined SQLITE_OMIT_AUTOVACUUM */
45794   #define ptrmapPut(w,x,y,z,rc)
45795   #define ptrmapGet(w,x,y,z) SQLITE_OK
45796   #define ptrmapPutOvflPtr(x, y, rc)
45797 #endif
45798
45799 /*
45800 ** Given a btree page and a cell index (0 means the first cell on
45801 ** the page, 1 means the second cell, and so forth) return a pointer
45802 ** to the cell content.
45803 **
45804 ** This routine works only for pages that do not contain overflow cells.
45805 */
45806 #define findCell(P,I) \
45807   ((P)->aData + ((P)->maskPage & get2byte(&(P)->aData[(P)->cellOffset+2*(I)])))
45808
45809 /*
45810 ** This a more complex version of findCell() that works for
45811 ** pages that do contain overflow cells.
45812 */
45813 static u8 *findOverflowCell(MemPage *pPage, int iCell){
45814   int i;
45815   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
45816   for(i=pPage->nOverflow-1; i>=0; i--){
45817     int k;
45818     struct _OvflCell *pOvfl;
45819     pOvfl = &pPage->aOvfl[i];
45820     k = pOvfl->idx;
45821     if( k<=iCell ){
45822       if( k==iCell ){
45823         return pOvfl->pCell;
45824       }
45825       iCell--;
45826     }
45827   }
45828   return findCell(pPage, iCell);
45829 }
45830
45831 /*
45832 ** Parse a cell content block and fill in the CellInfo structure.  There
45833 ** are two versions of this function.  btreeParseCell() takes a 
45834 ** cell index as the second argument and btreeParseCellPtr() 
45835 ** takes a pointer to the body of the cell as its second argument.
45836 **
45837 ** Within this file, the parseCell() macro can be called instead of
45838 ** btreeParseCellPtr(). Using some compilers, this will be faster.
45839 */
45840 static void btreeParseCellPtr(
45841   MemPage *pPage,         /* Page containing the cell */
45842   u8 *pCell,              /* Pointer to the cell text. */
45843   CellInfo *pInfo         /* Fill in this structure */
45844 ){
45845   u16 n;                  /* Number bytes in cell content header */
45846   u32 nPayload;           /* Number of bytes of cell payload */
45847
45848   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
45849
45850   pInfo->pCell = pCell;
45851   assert( pPage->leaf==0 || pPage->leaf==1 );
45852   n = pPage->childPtrSize;
45853   assert( n==4-4*pPage->leaf );
45854   if( pPage->intKey ){
45855     if( pPage->hasData ){
45856       n += getVarint32(&pCell[n], nPayload);
45857     }else{
45858       nPayload = 0;
45859     }
45860     n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
45861     pInfo->nData = nPayload;
45862   }else{
45863     pInfo->nData = 0;
45864     n += getVarint32(&pCell[n], nPayload);
45865     pInfo->nKey = nPayload;
45866   }
45867   pInfo->nPayload = nPayload;
45868   pInfo->nHeader = n;
45869   testcase( nPayload==pPage->maxLocal );
45870   testcase( nPayload==pPage->maxLocal+1 );
45871   if( likely(nPayload<=pPage->maxLocal) ){
45872     /* This is the (easy) common case where the entire payload fits
45873     ** on the local page.  No overflow is required.
45874     */
45875     int nSize;          /* Total size of cell content in bytes */
45876     nSize = nPayload + n;
45877     pInfo->nLocal = (u16)nPayload;
45878     pInfo->iOverflow = 0;
45879     if( (nSize & ~3)==0 ){
45880       nSize = 4;        /* Minimum cell size is 4 */
45881     }
45882     pInfo->nSize = (u16)nSize;
45883   }else{
45884     /* If the payload will not fit completely on the local page, we have
45885     ** to decide how much to store locally and how much to spill onto
45886     ** overflow pages.  The strategy is to minimize the amount of unused
45887     ** space on overflow pages while keeping the amount of local storage
45888     ** in between minLocal and maxLocal.
45889     **
45890     ** Warning:  changing the way overflow payload is distributed in any
45891     ** way will result in an incompatible file format.
45892     */
45893     int minLocal;  /* Minimum amount of payload held locally */
45894     int maxLocal;  /* Maximum amount of payload held locally */
45895     int surplus;   /* Overflow payload available for local storage */
45896
45897     minLocal = pPage->minLocal;
45898     maxLocal = pPage->maxLocal;
45899     surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
45900     testcase( surplus==maxLocal );
45901     testcase( surplus==maxLocal+1 );
45902     if( surplus <= maxLocal ){
45903       pInfo->nLocal = (u16)surplus;
45904     }else{
45905       pInfo->nLocal = (u16)minLocal;
45906     }
45907     pInfo->iOverflow = (u16)(pInfo->nLocal + n);
45908     pInfo->nSize = pInfo->iOverflow + 4;
45909   }
45910 }
45911 #define parseCell(pPage, iCell, pInfo) \
45912   btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
45913 static void btreeParseCell(
45914   MemPage *pPage,         /* Page containing the cell */
45915   int iCell,              /* The cell index.  First cell is 0 */
45916   CellInfo *pInfo         /* Fill in this structure */
45917 ){
45918   parseCell(pPage, iCell, pInfo);
45919 }
45920
45921 /*
45922 ** Compute the total number of bytes that a Cell needs in the cell
45923 ** data area of the btree-page.  The return number includes the cell
45924 ** data header and the local payload, but not any overflow page or
45925 ** the space used by the cell pointer.
45926 */
45927 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
45928   u8 *pIter = &pCell[pPage->childPtrSize];
45929   u32 nSize;
45930
45931 #ifdef SQLITE_DEBUG
45932   /* The value returned by this function should always be the same as
45933   ** the (CellInfo.nSize) value found by doing a full parse of the
45934   ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
45935   ** this function verifies that this invariant is not violated. */
45936   CellInfo debuginfo;
45937   btreeParseCellPtr(pPage, pCell, &debuginfo);
45938 #endif
45939
45940   if( pPage->intKey ){
45941     u8 *pEnd;
45942     if( pPage->hasData ){
45943       pIter += getVarint32(pIter, nSize);
45944     }else{
45945       nSize = 0;
45946     }
45947
45948     /* pIter now points at the 64-bit integer key value, a variable length 
45949     ** integer. The following block moves pIter to point at the first byte
45950     ** past the end of the key value. */
45951     pEnd = &pIter[9];
45952     while( (*pIter++)&0x80 && pIter<pEnd );
45953   }else{
45954     pIter += getVarint32(pIter, nSize);
45955   }
45956
45957   testcase( nSize==pPage->maxLocal );
45958   testcase( nSize==pPage->maxLocal+1 );
45959   if( nSize>pPage->maxLocal ){
45960     int minLocal = pPage->minLocal;
45961     nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
45962     testcase( nSize==pPage->maxLocal );
45963     testcase( nSize==pPage->maxLocal+1 );
45964     if( nSize>pPage->maxLocal ){
45965       nSize = minLocal;
45966     }
45967     nSize += 4;
45968   }
45969   nSize += (u32)(pIter - pCell);
45970
45971   /* The minimum size of any cell is 4 bytes. */
45972   if( nSize<4 ){
45973     nSize = 4;
45974   }
45975
45976   assert( nSize==debuginfo.nSize );
45977   return (u16)nSize;
45978 }
45979
45980 #ifdef SQLITE_DEBUG
45981 /* This variation on cellSizePtr() is used inside of assert() statements
45982 ** only. */
45983 static u16 cellSize(MemPage *pPage, int iCell){
45984   return cellSizePtr(pPage, findCell(pPage, iCell));
45985 }
45986 #endif
45987
45988 #ifndef SQLITE_OMIT_AUTOVACUUM
45989 /*
45990 ** If the cell pCell, part of page pPage contains a pointer
45991 ** to an overflow page, insert an entry into the pointer-map
45992 ** for the overflow page.
45993 */
45994 static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
45995   CellInfo info;
45996   if( *pRC ) return;
45997   assert( pCell!=0 );
45998   btreeParseCellPtr(pPage, pCell, &info);
45999   assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
46000   if( info.iOverflow ){
46001     Pgno ovfl = get4byte(&pCell[info.iOverflow]);
46002     ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
46003   }
46004 }
46005 #endif
46006
46007
46008 /*
46009 ** Defragment the page given.  All Cells are moved to the
46010 ** end of the page and all free space is collected into one
46011 ** big FreeBlk that occurs in between the header and cell
46012 ** pointer array and the cell content area.
46013 */
46014 static int defragmentPage(MemPage *pPage){
46015   int i;                     /* Loop counter */
46016   int pc;                    /* Address of a i-th cell */
46017   int hdr;                   /* Offset to the page header */
46018   int size;                  /* Size of a cell */
46019   int usableSize;            /* Number of usable bytes on a page */
46020   int cellOffset;            /* Offset to the cell pointer array */
46021   int cbrk;                  /* Offset to the cell content area */
46022   int nCell;                 /* Number of cells on the page */
46023   unsigned char *data;       /* The page data */
46024   unsigned char *temp;       /* Temp area for cell content */
46025   int iCellFirst;            /* First allowable cell index */
46026   int iCellLast;             /* Last possible cell index */
46027
46028
46029   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
46030   assert( pPage->pBt!=0 );
46031   assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
46032   assert( pPage->nOverflow==0 );
46033   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
46034   temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
46035   data = pPage->aData;
46036   hdr = pPage->hdrOffset;
46037   cellOffset = pPage->cellOffset;
46038   nCell = pPage->nCell;
46039   assert( nCell==get2byte(&data[hdr+3]) );
46040   usableSize = pPage->pBt->usableSize;
46041   cbrk = get2byte(&data[hdr+5]);
46042   memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
46043   cbrk = usableSize;
46044   iCellFirst = cellOffset + 2*nCell;
46045   iCellLast = usableSize - 4;
46046   for(i=0; i<nCell; i++){
46047     u8 *pAddr;     /* The i-th cell pointer */
46048     pAddr = &data[cellOffset + i*2];
46049     pc = get2byte(pAddr);
46050     testcase( pc==iCellFirst );
46051     testcase( pc==iCellLast );
46052 #if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
46053     /* These conditions have already been verified in btreeInitPage()
46054     ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined 
46055     */
46056     if( pc<iCellFirst || pc>iCellLast ){
46057       return SQLITE_CORRUPT_BKPT;
46058     }
46059 #endif
46060     assert( pc>=iCellFirst && pc<=iCellLast );
46061     size = cellSizePtr(pPage, &temp[pc]);
46062     cbrk -= size;
46063 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
46064     if( cbrk<iCellFirst ){
46065       return SQLITE_CORRUPT_BKPT;
46066     }
46067 #else
46068     if( cbrk<iCellFirst || pc+size>usableSize ){
46069       return SQLITE_CORRUPT_BKPT;
46070     }
46071 #endif
46072     assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
46073     testcase( cbrk+size==usableSize );
46074     testcase( pc+size==usableSize );
46075     memcpy(&data[cbrk], &temp[pc], size);
46076     put2byte(pAddr, cbrk);
46077   }
46078   assert( cbrk>=iCellFirst );
46079   put2byte(&data[hdr+5], cbrk);
46080   data[hdr+1] = 0;
46081   data[hdr+2] = 0;
46082   data[hdr+7] = 0;
46083   memset(&data[iCellFirst], 0, cbrk-iCellFirst);
46084   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
46085   if( cbrk-iCellFirst!=pPage->nFree ){
46086     return SQLITE_CORRUPT_BKPT;
46087   }
46088   return SQLITE_OK;
46089 }
46090
46091 /*
46092 ** Allocate nByte bytes of space from within the B-Tree page passed
46093 ** as the first argument. Write into *pIdx the index into pPage->aData[]
46094 ** of the first byte of allocated space. Return either SQLITE_OK or
46095 ** an error code (usually SQLITE_CORRUPT).
46096 **
46097 ** The caller guarantees that there is sufficient space to make the
46098 ** allocation.  This routine might need to defragment in order to bring
46099 ** all the space together, however.  This routine will avoid using
46100 ** the first two bytes past the cell pointer area since presumably this
46101 ** allocation is being made in order to insert a new cell, so we will
46102 ** also end up needing a new cell pointer.
46103 */
46104 static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
46105   const int hdr = pPage->hdrOffset;    /* Local cache of pPage->hdrOffset */
46106   u8 * const data = pPage->aData;      /* Local cache of pPage->aData */
46107   int nFrag;                           /* Number of fragmented bytes on pPage */
46108   int top;                             /* First byte of cell content area */
46109   int gap;        /* First byte of gap between cell pointers and cell content */
46110   int rc;         /* Integer return code */
46111   int usableSize; /* Usable size of the page */
46112   
46113   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
46114   assert( pPage->pBt );
46115   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
46116   assert( nByte>=0 );  /* Minimum cell size is 4 */
46117   assert( pPage->nFree>=nByte );
46118   assert( pPage->nOverflow==0 );
46119   usableSize = pPage->pBt->usableSize;
46120   assert( nByte < usableSize-8 );
46121
46122   nFrag = data[hdr+7];
46123   assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
46124   gap = pPage->cellOffset + 2*pPage->nCell;
46125   top = get2byteNotZero(&data[hdr+5]);
46126   if( gap>top ) return SQLITE_CORRUPT_BKPT;
46127   testcase( gap+2==top );
46128   testcase( gap+1==top );
46129   testcase( gap==top );
46130
46131   if( nFrag>=60 ){
46132     /* Always defragment highly fragmented pages */
46133     rc = defragmentPage(pPage);
46134     if( rc ) return rc;
46135     top = get2byteNotZero(&data[hdr+5]);
46136   }else if( gap+2<=top ){
46137     /* Search the freelist looking for a free slot big enough to satisfy 
46138     ** the request. The allocation is made from the first free slot in 
46139     ** the list that is large enough to accomadate it.
46140     */
46141     int pc, addr;
46142     for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
46143       int size;            /* Size of the free slot */
46144       if( pc>usableSize-4 || pc<addr+4 ){
46145         return SQLITE_CORRUPT_BKPT;
46146       }
46147       size = get2byte(&data[pc+2]);
46148       if( size>=nByte ){
46149         int x = size - nByte;
46150         testcase( x==4 );
46151         testcase( x==3 );
46152         if( x<4 ){
46153           /* Remove the slot from the free-list. Update the number of
46154           ** fragmented bytes within the page. */
46155           memcpy(&data[addr], &data[pc], 2);
46156           data[hdr+7] = (u8)(nFrag + x);
46157         }else if( size+pc > usableSize ){
46158           return SQLITE_CORRUPT_BKPT;
46159         }else{
46160           /* The slot remains on the free-list. Reduce its size to account
46161           ** for the portion used by the new allocation. */
46162           put2byte(&data[pc+2], x);
46163         }
46164         *pIdx = pc + x;
46165         return SQLITE_OK;
46166       }
46167     }
46168   }
46169
46170   /* Check to make sure there is enough space in the gap to satisfy
46171   ** the allocation.  If not, defragment.
46172   */
46173   testcase( gap+2+nByte==top );
46174   if( gap+2+nByte>top ){
46175     rc = defragmentPage(pPage);
46176     if( rc ) return rc;
46177     top = get2byteNotZero(&data[hdr+5]);
46178     assert( gap+nByte<=top );
46179   }
46180
46181
46182   /* Allocate memory from the gap in between the cell pointer array
46183   ** and the cell content area.  The btreeInitPage() call has already
46184   ** validated the freelist.  Given that the freelist is valid, there
46185   ** is no way that the allocation can extend off the end of the page.
46186   ** The assert() below verifies the previous sentence.
46187   */
46188   top -= nByte;
46189   put2byte(&data[hdr+5], top);
46190   assert( top+nByte <= pPage->pBt->usableSize );
46191   *pIdx = top;
46192   return SQLITE_OK;
46193 }
46194
46195 /*
46196 ** Return a section of the pPage->aData to the freelist.
46197 ** The first byte of the new free block is pPage->aDisk[start]
46198 ** and the size of the block is "size" bytes.
46199 **
46200 ** Most of the effort here is involved in coalesing adjacent
46201 ** free blocks into a single big free block.
46202 */
46203 static int freeSpace(MemPage *pPage, int start, int size){
46204   int addr, pbegin, hdr;
46205   int iLast;                        /* Largest possible freeblock offset */
46206   unsigned char *data = pPage->aData;
46207
46208   assert( pPage->pBt!=0 );
46209   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
46210   assert( start>=pPage->hdrOffset+6+pPage->childPtrSize );
46211   assert( (start + size)<=pPage->pBt->usableSize );
46212   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
46213   assert( size>=0 );   /* Minimum cell size is 4 */
46214
46215   if( pPage->pBt->secureDelete ){
46216     /* Overwrite deleted information with zeros when the secure_delete
46217     ** option is enabled */
46218     memset(&data[start], 0, size);
46219   }
46220
46221   /* Add the space back into the linked list of freeblocks.  Note that
46222   ** even though the freeblock list was checked by btreeInitPage(),
46223   ** btreeInitPage() did not detect overlapping cells or
46224   ** freeblocks that overlapped cells.   Nor does it detect when the
46225   ** cell content area exceeds the value in the page header.  If these
46226   ** situations arise, then subsequent insert operations might corrupt
46227   ** the freelist.  So we do need to check for corruption while scanning
46228   ** the freelist.
46229   */
46230   hdr = pPage->hdrOffset;
46231   addr = hdr + 1;
46232   iLast = pPage->pBt->usableSize - 4;
46233   assert( start<=iLast );
46234   while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
46235     if( pbegin<addr+4 ){
46236       return SQLITE_CORRUPT_BKPT;
46237     }
46238     addr = pbegin;
46239   }
46240   if( pbegin>iLast ){
46241     return SQLITE_CORRUPT_BKPT;
46242   }
46243   assert( pbegin>addr || pbegin==0 );
46244   put2byte(&data[addr], start);
46245   put2byte(&data[start], pbegin);
46246   put2byte(&data[start+2], size);
46247   pPage->nFree = pPage->nFree + (u16)size;
46248
46249   /* Coalesce adjacent free blocks */
46250   addr = hdr + 1;
46251   while( (pbegin = get2byte(&data[addr]))>0 ){
46252     int pnext, psize, x;
46253     assert( pbegin>addr );
46254     assert( pbegin<=pPage->pBt->usableSize-4 );
46255     pnext = get2byte(&data[pbegin]);
46256     psize = get2byte(&data[pbegin+2]);
46257     if( pbegin + psize + 3 >= pnext && pnext>0 ){
46258       int frag = pnext - (pbegin+psize);
46259       if( (frag<0) || (frag>(int)data[hdr+7]) ){
46260         return SQLITE_CORRUPT_BKPT;
46261       }
46262       data[hdr+7] -= (u8)frag;
46263       x = get2byte(&data[pnext]);
46264       put2byte(&data[pbegin], x);
46265       x = pnext + get2byte(&data[pnext+2]) - pbegin;
46266       put2byte(&data[pbegin+2], x);
46267     }else{
46268       addr = pbegin;
46269     }
46270   }
46271
46272   /* If the cell content area begins with a freeblock, remove it. */
46273   if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
46274     int top;
46275     pbegin = get2byte(&data[hdr+1]);
46276     memcpy(&data[hdr+1], &data[pbegin], 2);
46277     top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);
46278     put2byte(&data[hdr+5], top);
46279   }
46280   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
46281   return SQLITE_OK;
46282 }
46283
46284 /*
46285 ** Decode the flags byte (the first byte of the header) for a page
46286 ** and initialize fields of the MemPage structure accordingly.
46287 **
46288 ** Only the following combinations are supported.  Anything different
46289 ** indicates a corrupt database files:
46290 **
46291 **         PTF_ZERODATA
46292 **         PTF_ZERODATA | PTF_LEAF
46293 **         PTF_LEAFDATA | PTF_INTKEY
46294 **         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
46295 */
46296 static int decodeFlags(MemPage *pPage, int flagByte){
46297   BtShared *pBt;     /* A copy of pPage->pBt */
46298
46299   assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
46300   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
46301   pPage->leaf = (u8)(flagByte>>3);  assert( PTF_LEAF == 1<<3 );
46302   flagByte &= ~PTF_LEAF;
46303   pPage->childPtrSize = 4-4*pPage->leaf;
46304   pBt = pPage->pBt;
46305   if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
46306     pPage->intKey = 1;
46307     pPage->hasData = pPage->leaf;
46308     pPage->maxLocal = pBt->maxLeaf;
46309     pPage->minLocal = pBt->minLeaf;
46310   }else if( flagByte==PTF_ZERODATA ){
46311     pPage->intKey = 0;
46312     pPage->hasData = 0;
46313     pPage->maxLocal = pBt->maxLocal;
46314     pPage->minLocal = pBt->minLocal;
46315   }else{
46316     return SQLITE_CORRUPT_BKPT;
46317   }
46318   return SQLITE_OK;
46319 }
46320
46321 /*
46322 ** Initialize the auxiliary information for a disk block.
46323 **
46324 ** Return SQLITE_OK on success.  If we see that the page does
46325 ** not contain a well-formed database page, then return 
46326 ** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
46327 ** guarantee that the page is well-formed.  It only shows that
46328 ** we failed to detect any corruption.
46329 */
46330 static int btreeInitPage(MemPage *pPage){
46331
46332   assert( pPage->pBt!=0 );
46333   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
46334   assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
46335   assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
46336   assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
46337
46338   if( !pPage->isInit ){
46339     u16 pc;            /* Address of a freeblock within pPage->aData[] */
46340     u8 hdr;            /* Offset to beginning of page header */
46341     u8 *data;          /* Equal to pPage->aData */
46342     BtShared *pBt;        /* The main btree structure */
46343     int usableSize;    /* Amount of usable space on each page */
46344     u16 cellOffset;    /* Offset from start of page to first cell pointer */
46345     int nFree;         /* Number of unused bytes on the page */
46346     int top;           /* First byte of the cell content area */
46347     int iCellFirst;    /* First allowable cell or freeblock offset */
46348     int iCellLast;     /* Last possible cell or freeblock offset */
46349
46350     pBt = pPage->pBt;
46351
46352     hdr = pPage->hdrOffset;
46353     data = pPage->aData;
46354     if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
46355     assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
46356     pPage->maskPage = (u16)(pBt->pageSize - 1);
46357     pPage->nOverflow = 0;
46358     usableSize = pBt->usableSize;
46359     pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
46360     top = get2byteNotZero(&data[hdr+5]);
46361     pPage->nCell = get2byte(&data[hdr+3]);
46362     if( pPage->nCell>MX_CELL(pBt) ){
46363       /* To many cells for a single page.  The page must be corrupt */
46364       return SQLITE_CORRUPT_BKPT;
46365     }
46366     testcase( pPage->nCell==MX_CELL(pBt) );
46367
46368     /* A malformed database page might cause us to read past the end
46369     ** of page when parsing a cell.  
46370     **
46371     ** The following block of code checks early to see if a cell extends
46372     ** past the end of a page boundary and causes SQLITE_CORRUPT to be 
46373     ** returned if it does.
46374     */
46375     iCellFirst = cellOffset + 2*pPage->nCell;
46376     iCellLast = usableSize - 4;
46377 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
46378     {
46379       int i;            /* Index into the cell pointer array */
46380       int sz;           /* Size of a cell */
46381
46382       if( !pPage->leaf ) iCellLast--;
46383       for(i=0; i<pPage->nCell; i++){
46384         pc = get2byte(&data[cellOffset+i*2]);
46385         testcase( pc==iCellFirst );
46386         testcase( pc==iCellLast );
46387         if( pc<iCellFirst || pc>iCellLast ){
46388           return SQLITE_CORRUPT_BKPT;
46389         }
46390         sz = cellSizePtr(pPage, &data[pc]);
46391         testcase( pc+sz==usableSize );
46392         if( pc+sz>usableSize ){
46393           return SQLITE_CORRUPT_BKPT;
46394         }
46395       }
46396       if( !pPage->leaf ) iCellLast++;
46397     }  
46398 #endif
46399
46400     /* Compute the total free space on the page */
46401     pc = get2byte(&data[hdr+1]);
46402     nFree = data[hdr+7] + top;
46403     while( pc>0 ){
46404       u16 next, size;
46405       if( pc<iCellFirst || pc>iCellLast ){
46406         /* Start of free block is off the page */
46407         return SQLITE_CORRUPT_BKPT; 
46408       }
46409       next = get2byte(&data[pc]);
46410       size = get2byte(&data[pc+2]);
46411       if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
46412         /* Free blocks must be in ascending order. And the last byte of
46413         ** the free-block must lie on the database page.  */
46414         return SQLITE_CORRUPT_BKPT; 
46415       }
46416       nFree = nFree + size;
46417       pc = next;
46418     }
46419
46420     /* At this point, nFree contains the sum of the offset to the start
46421     ** of the cell-content area plus the number of free bytes within
46422     ** the cell-content area. If this is greater than the usable-size
46423     ** of the page, then the page must be corrupted. This check also
46424     ** serves to verify that the offset to the start of the cell-content
46425     ** area, according to the page header, lies within the page.
46426     */
46427     if( nFree>usableSize ){
46428       return SQLITE_CORRUPT_BKPT; 
46429     }
46430     pPage->nFree = (u16)(nFree - iCellFirst);
46431     pPage->isInit = 1;
46432   }
46433   return SQLITE_OK;
46434 }
46435
46436 /*
46437 ** Set up a raw page so that it looks like a database page holding
46438 ** no entries.
46439 */
46440 static void zeroPage(MemPage *pPage, int flags){
46441   unsigned char *data = pPage->aData;
46442   BtShared *pBt = pPage->pBt;
46443   u8 hdr = pPage->hdrOffset;
46444   u16 first;
46445
46446   assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
46447   assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
46448   assert( sqlite3PagerGetData(pPage->pDbPage) == data );
46449   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
46450   assert( sqlite3_mutex_held(pBt->mutex) );
46451   if( pBt->secureDelete ){
46452     memset(&data[hdr], 0, pBt->usableSize - hdr);
46453   }
46454   data[hdr] = (char)flags;
46455   first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0);
46456   memset(&data[hdr+1], 0, 4);
46457   data[hdr+7] = 0;
46458   put2byte(&data[hdr+5], pBt->usableSize);
46459   pPage->nFree = (u16)(pBt->usableSize - first);
46460   decodeFlags(pPage, flags);
46461   pPage->hdrOffset = hdr;
46462   pPage->cellOffset = first;
46463   pPage->nOverflow = 0;
46464   assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
46465   pPage->maskPage = (u16)(pBt->pageSize - 1);
46466   pPage->nCell = 0;
46467   pPage->isInit = 1;
46468 }
46469
46470
46471 /*
46472 ** Convert a DbPage obtained from the pager into a MemPage used by
46473 ** the btree layer.
46474 */
46475 static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
46476   MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
46477   pPage->aData = sqlite3PagerGetData(pDbPage);
46478   pPage->pDbPage = pDbPage;
46479   pPage->pBt = pBt;
46480   pPage->pgno = pgno;
46481   pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
46482   return pPage; 
46483 }
46484
46485 /*
46486 ** Get a page from the pager.  Initialize the MemPage.pBt and
46487 ** MemPage.aData elements if needed.
46488 **
46489 ** If the noContent flag is set, it means that we do not care about
46490 ** the content of the page at this time.  So do not go to the disk
46491 ** to fetch the content.  Just fill in the content with zeros for now.
46492 ** If in the future we call sqlite3PagerWrite() on this page, that
46493 ** means we have started to be concerned about content and the disk
46494 ** read should occur at that point.
46495 */
46496 static int btreeGetPage(
46497   BtShared *pBt,       /* The btree */
46498   Pgno pgno,           /* Number of the page to fetch */
46499   MemPage **ppPage,    /* Return the page in this parameter */
46500   int noContent        /* Do not load page content if true */
46501 ){
46502   int rc;
46503   DbPage *pDbPage;
46504
46505   assert( sqlite3_mutex_held(pBt->mutex) );
46506   rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
46507   if( rc ) return rc;
46508   *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
46509   return SQLITE_OK;
46510 }
46511
46512 /*
46513 ** Retrieve a page from the pager cache. If the requested page is not
46514 ** already in the pager cache return NULL. Initialize the MemPage.pBt and
46515 ** MemPage.aData elements if needed.
46516 */
46517 static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
46518   DbPage *pDbPage;
46519   assert( sqlite3_mutex_held(pBt->mutex) );
46520   pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
46521   if( pDbPage ){
46522     return btreePageFromDbPage(pDbPage, pgno, pBt);
46523   }
46524   return 0;
46525 }
46526
46527 /*
46528 ** Return the size of the database file in pages. If there is any kind of
46529 ** error, return ((unsigned int)-1).
46530 */
46531 static Pgno btreePagecount(BtShared *pBt){
46532   return pBt->nPage;
46533 }
46534 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
46535   assert( sqlite3BtreeHoldsMutex(p) );
46536   assert( ((p->pBt->nPage)&0x8000000)==0 );
46537   return (int)btreePagecount(p->pBt);
46538 }
46539
46540 /*
46541 ** Get a page from the pager and initialize it.  This routine is just a
46542 ** convenience wrapper around separate calls to btreeGetPage() and 
46543 ** btreeInitPage().
46544 **
46545 ** If an error occurs, then the value *ppPage is set to is undefined. It
46546 ** may remain unchanged, or it may be set to an invalid value.
46547 */
46548 static int getAndInitPage(
46549   BtShared *pBt,          /* The database file */
46550   Pgno pgno,           /* Number of the page to get */
46551   MemPage **ppPage     /* Write the page pointer here */
46552 ){
46553   int rc;
46554   assert( sqlite3_mutex_held(pBt->mutex) );
46555
46556   if( pgno>btreePagecount(pBt) ){
46557     rc = SQLITE_CORRUPT_BKPT;
46558   }else{
46559     rc = btreeGetPage(pBt, pgno, ppPage, 0);
46560     if( rc==SQLITE_OK ){
46561       rc = btreeInitPage(*ppPage);
46562       if( rc!=SQLITE_OK ){
46563         releasePage(*ppPage);
46564       }
46565     }
46566   }
46567
46568   testcase( pgno==0 );
46569   assert( pgno!=0 || rc==SQLITE_CORRUPT );
46570   return rc;
46571 }
46572
46573 /*
46574 ** Release a MemPage.  This should be called once for each prior
46575 ** call to btreeGetPage.
46576 */
46577 static void releasePage(MemPage *pPage){
46578   if( pPage ){
46579     assert( pPage->aData );
46580     assert( pPage->pBt );
46581     assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
46582     assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
46583     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
46584     sqlite3PagerUnref(pPage->pDbPage);
46585   }
46586 }
46587
46588 /*
46589 ** During a rollback, when the pager reloads information into the cache
46590 ** so that the cache is restored to its original state at the start of
46591 ** the transaction, for each page restored this routine is called.
46592 **
46593 ** This routine needs to reset the extra data section at the end of the
46594 ** page to agree with the restored data.
46595 */
46596 static void pageReinit(DbPage *pData){
46597   MemPage *pPage;
46598   pPage = (MemPage *)sqlite3PagerGetExtra(pData);
46599   assert( sqlite3PagerPageRefcount(pData)>0 );
46600   if( pPage->isInit ){
46601     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
46602     pPage->isInit = 0;
46603     if( sqlite3PagerPageRefcount(pData)>1 ){
46604       /* pPage might not be a btree page;  it might be an overflow page
46605       ** or ptrmap page or a free page.  In those cases, the following
46606       ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
46607       ** But no harm is done by this.  And it is very important that
46608       ** btreeInitPage() be called on every btree page so we make
46609       ** the call for every page that comes in for re-initing. */
46610       btreeInitPage(pPage);
46611     }
46612   }
46613 }
46614
46615 /*
46616 ** Invoke the busy handler for a btree.
46617 */
46618 static int btreeInvokeBusyHandler(void *pArg){
46619   BtShared *pBt = (BtShared*)pArg;
46620   assert( pBt->db );
46621   assert( sqlite3_mutex_held(pBt->db->mutex) );
46622   return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
46623 }
46624
46625 /*
46626 ** Open a database file.
46627 ** 
46628 ** zFilename is the name of the database file.  If zFilename is NULL
46629 ** then an ephemeral database is created.  The ephemeral database might
46630 ** be exclusively in memory, or it might use a disk-based memory cache.
46631 ** Either way, the ephemeral database will be automatically deleted 
46632 ** when sqlite3BtreeClose() is called.
46633 **
46634 ** If zFilename is ":memory:" then an in-memory database is created
46635 ** that is automatically destroyed when it is closed.
46636 **
46637 ** The "flags" parameter is a bitmask that might contain bits
46638 ** BTREE_OMIT_JOURNAL and/or BTREE_NO_READLOCK.  The BTREE_NO_READLOCK
46639 ** bit is also set if the SQLITE_NoReadlock flags is set in db->flags.
46640 ** These flags are passed through into sqlite3PagerOpen() and must
46641 ** be the same values as PAGER_OMIT_JOURNAL and PAGER_NO_READLOCK.
46642 **
46643 ** If the database is already opened in the same database connection
46644 ** and we are in shared cache mode, then the open will fail with an
46645 ** SQLITE_CONSTRAINT error.  We cannot allow two or more BtShared
46646 ** objects in the same database connection since doing so will lead
46647 ** to problems with locking.
46648 */
46649 SQLITE_PRIVATE int sqlite3BtreeOpen(
46650   const char *zFilename,  /* Name of the file containing the BTree database */
46651   sqlite3 *db,            /* Associated database handle */
46652   Btree **ppBtree,        /* Pointer to new Btree object written here */
46653   int flags,              /* Options */
46654   int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
46655 ){
46656   sqlite3_vfs *pVfs;             /* The VFS to use for this btree */
46657   BtShared *pBt = 0;             /* Shared part of btree structure */
46658   Btree *p;                      /* Handle to return */
46659   sqlite3_mutex *mutexOpen = 0;  /* Prevents a race condition. Ticket #3537 */
46660   int rc = SQLITE_OK;            /* Result code from this function */
46661   u8 nReserve;                   /* Byte of unused space on each page */
46662   unsigned char zDbHeader[100];  /* Database header content */
46663
46664   /* True if opening an ephemeral, temporary database */
46665   const int isTempDb = zFilename==0 || zFilename[0]==0;
46666
46667   /* Set the variable isMemdb to true for an in-memory database, or 
46668   ** false for a file-based database. This symbol is only required if
46669   ** either of the shared-data or autovacuum features are compiled 
46670   ** into the library.
46671   */
46672 #if !defined(SQLITE_OMIT_SHARED_CACHE) || !defined(SQLITE_OMIT_AUTOVACUUM)
46673   #ifdef SQLITE_OMIT_MEMORYDB
46674     const int isMemdb = 0;
46675   #else
46676     const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
46677                          || (isTempDb && sqlite3TempInMemory(db));
46678   #endif
46679 #endif
46680
46681   assert( db!=0 );
46682   assert( sqlite3_mutex_held(db->mutex) );
46683   assert( (flags&0xff)==flags );   /* flags fit in 8 bits */
46684
46685   /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
46686   assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
46687
46688   /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
46689   assert( (flags & BTREE_SINGLE)==0 || isTempDb );
46690
46691   if( db->flags & SQLITE_NoReadlock ){
46692     flags |= BTREE_NO_READLOCK;
46693   }
46694   if( isMemdb ){
46695     flags |= BTREE_MEMORY;
46696   }
46697   if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
46698     vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
46699   }
46700   pVfs = db->pVfs;
46701   p = sqlite3MallocZero(sizeof(Btree));
46702   if( !p ){
46703     return SQLITE_NOMEM;
46704   }
46705   p->inTrans = TRANS_NONE;
46706   p->db = db;
46707 #ifndef SQLITE_OMIT_SHARED_CACHE
46708   p->lock.pBtree = p;
46709   p->lock.iTable = 1;
46710 #endif
46711
46712 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
46713   /*
46714   ** If this Btree is a candidate for shared cache, try to find an
46715   ** existing BtShared object that we can share with
46716   */
46717   if( isMemdb==0 && isTempDb==0 ){
46718     if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
46719       int nFullPathname = pVfs->mxPathname+1;
46720       char *zFullPathname = sqlite3Malloc(nFullPathname);
46721       sqlite3_mutex *mutexShared;
46722       p->sharable = 1;
46723       if( !zFullPathname ){
46724         sqlite3_free(p);
46725         return SQLITE_NOMEM;
46726       }
46727       sqlite3OsFullPathname(pVfs, zFilename, nFullPathname, zFullPathname);
46728       mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
46729       sqlite3_mutex_enter(mutexOpen);
46730       mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
46731       sqlite3_mutex_enter(mutexShared);
46732       for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
46733         assert( pBt->nRef>0 );
46734         if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager))
46735                  && sqlite3PagerVfs(pBt->pPager)==pVfs ){
46736           int iDb;
46737           for(iDb=db->nDb-1; iDb>=0; iDb--){
46738             Btree *pExisting = db->aDb[iDb].pBt;
46739             if( pExisting && pExisting->pBt==pBt ){
46740               sqlite3_mutex_leave(mutexShared);
46741               sqlite3_mutex_leave(mutexOpen);
46742               sqlite3_free(zFullPathname);
46743               sqlite3_free(p);
46744               return SQLITE_CONSTRAINT;
46745             }
46746           }
46747           p->pBt = pBt;
46748           pBt->nRef++;
46749           break;
46750         }
46751       }
46752       sqlite3_mutex_leave(mutexShared);
46753       sqlite3_free(zFullPathname);
46754     }
46755 #ifdef SQLITE_DEBUG
46756     else{
46757       /* In debug mode, we mark all persistent databases as sharable
46758       ** even when they are not.  This exercises the locking code and
46759       ** gives more opportunity for asserts(sqlite3_mutex_held())
46760       ** statements to find locking problems.
46761       */
46762       p->sharable = 1;
46763     }
46764 #endif
46765   }
46766 #endif
46767   if( pBt==0 ){
46768     /*
46769     ** The following asserts make sure that structures used by the btree are
46770     ** the right size.  This is to guard against size changes that result
46771     ** when compiling on a different architecture.
46772     */
46773     assert( sizeof(i64)==8 || sizeof(i64)==4 );
46774     assert( sizeof(u64)==8 || sizeof(u64)==4 );
46775     assert( sizeof(u32)==4 );
46776     assert( sizeof(u16)==2 );
46777     assert( sizeof(Pgno)==4 );
46778   
46779     pBt = sqlite3MallocZero( sizeof(*pBt) );
46780     if( pBt==0 ){
46781       rc = SQLITE_NOMEM;
46782       goto btree_open_out;
46783     }
46784     rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
46785                           EXTRA_SIZE, flags, vfsFlags, pageReinit);
46786     if( rc==SQLITE_OK ){
46787       rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
46788     }
46789     if( rc!=SQLITE_OK ){
46790       goto btree_open_out;
46791     }
46792     pBt->openFlags = (u8)flags;
46793     pBt->db = db;
46794     sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
46795     p->pBt = pBt;
46796   
46797     pBt->pCursor = 0;
46798     pBt->pPage1 = 0;
46799     pBt->readOnly = sqlite3PagerIsreadonly(pBt->pPager);
46800 #ifdef SQLITE_SECURE_DELETE
46801     pBt->secureDelete = 1;
46802 #endif
46803     pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
46804     if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
46805          || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
46806       pBt->pageSize = 0;
46807 #ifndef SQLITE_OMIT_AUTOVACUUM
46808       /* If the magic name ":memory:" will create an in-memory database, then
46809       ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
46810       ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
46811       ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
46812       ** regular file-name. In this case the auto-vacuum applies as per normal.
46813       */
46814       if( zFilename && !isMemdb ){
46815         pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
46816         pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
46817       }
46818 #endif
46819       nReserve = 0;
46820     }else{
46821       nReserve = zDbHeader[20];
46822       pBt->pageSizeFixed = 1;
46823 #ifndef SQLITE_OMIT_AUTOVACUUM
46824       pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
46825       pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
46826 #endif
46827     }
46828     rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
46829     if( rc ) goto btree_open_out;
46830     pBt->usableSize = pBt->pageSize - nReserve;
46831     assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
46832    
46833 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
46834     /* Add the new BtShared object to the linked list sharable BtShareds.
46835     */
46836     if( p->sharable ){
46837       sqlite3_mutex *mutexShared;
46838       pBt->nRef = 1;
46839       mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
46840       if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
46841         pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
46842         if( pBt->mutex==0 ){
46843           rc = SQLITE_NOMEM;
46844           db->mallocFailed = 0;
46845           goto btree_open_out;
46846         }
46847       }
46848       sqlite3_mutex_enter(mutexShared);
46849       pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
46850       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
46851       sqlite3_mutex_leave(mutexShared);
46852     }
46853 #endif
46854   }
46855
46856 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
46857   /* If the new Btree uses a sharable pBtShared, then link the new
46858   ** Btree into the list of all sharable Btrees for the same connection.
46859   ** The list is kept in ascending order by pBt address.
46860   */
46861   if( p->sharable ){
46862     int i;
46863     Btree *pSib;
46864     for(i=0; i<db->nDb; i++){
46865       if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
46866         while( pSib->pPrev ){ pSib = pSib->pPrev; }
46867         if( p->pBt<pSib->pBt ){
46868           p->pNext = pSib;
46869           p->pPrev = 0;
46870           pSib->pPrev = p;
46871         }else{
46872           while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
46873             pSib = pSib->pNext;
46874           }
46875           p->pNext = pSib->pNext;
46876           p->pPrev = pSib;
46877           if( p->pNext ){
46878             p->pNext->pPrev = p;
46879           }
46880           pSib->pNext = p;
46881         }
46882         break;
46883       }
46884     }
46885   }
46886 #endif
46887   *ppBtree = p;
46888
46889 btree_open_out:
46890   if( rc!=SQLITE_OK ){
46891     if( pBt && pBt->pPager ){
46892       sqlite3PagerClose(pBt->pPager);
46893     }
46894     sqlite3_free(pBt);
46895     sqlite3_free(p);
46896     *ppBtree = 0;
46897   }else{
46898     /* If the B-Tree was successfully opened, set the pager-cache size to the
46899     ** default value. Except, when opening on an existing shared pager-cache,
46900     ** do not change the pager-cache size.
46901     */
46902     if( sqlite3BtreeSchema(p, 0, 0)==0 ){
46903       sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
46904     }
46905   }
46906   if( mutexOpen ){
46907     assert( sqlite3_mutex_held(mutexOpen) );
46908     sqlite3_mutex_leave(mutexOpen);
46909   }
46910   return rc;
46911 }
46912
46913 /*
46914 ** Decrement the BtShared.nRef counter.  When it reaches zero,
46915 ** remove the BtShared structure from the sharing list.  Return
46916 ** true if the BtShared.nRef counter reaches zero and return
46917 ** false if it is still positive.
46918 */
46919 static int removeFromSharingList(BtShared *pBt){
46920 #ifndef SQLITE_OMIT_SHARED_CACHE
46921   sqlite3_mutex *pMaster;
46922   BtShared *pList;
46923   int removed = 0;
46924
46925   assert( sqlite3_mutex_notheld(pBt->mutex) );
46926   pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
46927   sqlite3_mutex_enter(pMaster);
46928   pBt->nRef--;
46929   if( pBt->nRef<=0 ){
46930     if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
46931       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
46932     }else{
46933       pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
46934       while( ALWAYS(pList) && pList->pNext!=pBt ){
46935         pList=pList->pNext;
46936       }
46937       if( ALWAYS(pList) ){
46938         pList->pNext = pBt->pNext;
46939       }
46940     }
46941     if( SQLITE_THREADSAFE ){
46942       sqlite3_mutex_free(pBt->mutex);
46943     }
46944     removed = 1;
46945   }
46946   sqlite3_mutex_leave(pMaster);
46947   return removed;
46948 #else
46949   return 1;
46950 #endif
46951 }
46952
46953 /*
46954 ** Make sure pBt->pTmpSpace points to an allocation of 
46955 ** MX_CELL_SIZE(pBt) bytes.
46956 */
46957 static void allocateTempSpace(BtShared *pBt){
46958   if( !pBt->pTmpSpace ){
46959     pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
46960   }
46961 }
46962
46963 /*
46964 ** Free the pBt->pTmpSpace allocation
46965 */
46966 static void freeTempSpace(BtShared *pBt){
46967   sqlite3PageFree( pBt->pTmpSpace);
46968   pBt->pTmpSpace = 0;
46969 }
46970
46971 /*
46972 ** Close an open database and invalidate all cursors.
46973 */
46974 SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
46975   BtShared *pBt = p->pBt;
46976   BtCursor *pCur;
46977
46978   /* Close all cursors opened via this handle.  */
46979   assert( sqlite3_mutex_held(p->db->mutex) );
46980   sqlite3BtreeEnter(p);
46981   pCur = pBt->pCursor;
46982   while( pCur ){
46983     BtCursor *pTmp = pCur;
46984     pCur = pCur->pNext;
46985     if( pTmp->pBtree==p ){
46986       sqlite3BtreeCloseCursor(pTmp);
46987     }
46988   }
46989
46990   /* Rollback any active transaction and free the handle structure.
46991   ** The call to sqlite3BtreeRollback() drops any table-locks held by
46992   ** this handle.
46993   */
46994   sqlite3BtreeRollback(p);
46995   sqlite3BtreeLeave(p);
46996
46997   /* If there are still other outstanding references to the shared-btree
46998   ** structure, return now. The remainder of this procedure cleans 
46999   ** up the shared-btree.
47000   */
47001   assert( p->wantToLock==0 && p->locked==0 );
47002   if( !p->sharable || removeFromSharingList(pBt) ){
47003     /* The pBt is no longer on the sharing list, so we can access
47004     ** it without having to hold the mutex.
47005     **
47006     ** Clean out and delete the BtShared object.
47007     */
47008     assert( !pBt->pCursor );
47009     sqlite3PagerClose(pBt->pPager);
47010     if( pBt->xFreeSchema && pBt->pSchema ){
47011       pBt->xFreeSchema(pBt->pSchema);
47012     }
47013     sqlite3DbFree(0, pBt->pSchema);
47014     freeTempSpace(pBt);
47015     sqlite3_free(pBt);
47016   }
47017
47018 #ifndef SQLITE_OMIT_SHARED_CACHE
47019   assert( p->wantToLock==0 );
47020   assert( p->locked==0 );
47021   if( p->pPrev ) p->pPrev->pNext = p->pNext;
47022   if( p->pNext ) p->pNext->pPrev = p->pPrev;
47023 #endif
47024
47025   sqlite3_free(p);
47026   return SQLITE_OK;
47027 }
47028
47029 /*
47030 ** Change the limit on the number of pages allowed in the cache.
47031 **
47032 ** The maximum number of cache pages is set to the absolute
47033 ** value of mxPage.  If mxPage is negative, the pager will
47034 ** operate asynchronously - it will not stop to do fsync()s
47035 ** to insure data is written to the disk surface before
47036 ** continuing.  Transactions still work if synchronous is off,
47037 ** and the database cannot be corrupted if this program
47038 ** crashes.  But if the operating system crashes or there is
47039 ** an abrupt power failure when synchronous is off, the database
47040 ** could be left in an inconsistent and unrecoverable state.
47041 ** Synchronous is on by default so database corruption is not
47042 ** normally a worry.
47043 */
47044 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
47045   BtShared *pBt = p->pBt;
47046   assert( sqlite3_mutex_held(p->db->mutex) );
47047   sqlite3BtreeEnter(p);
47048   sqlite3PagerSetCachesize(pBt->pPager, mxPage);
47049   sqlite3BtreeLeave(p);
47050   return SQLITE_OK;
47051 }
47052
47053 /*
47054 ** Change the way data is synced to disk in order to increase or decrease
47055 ** how well the database resists damage due to OS crashes and power
47056 ** failures.  Level 1 is the same as asynchronous (no syncs() occur and
47057 ** there is a high probability of damage)  Level 2 is the default.  There
47058 ** is a very low but non-zero probability of damage.  Level 3 reduces the
47059 ** probability of damage to near zero but with a write performance reduction.
47060 */
47061 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
47062 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree *p, int level, int fullSync){
47063   BtShared *pBt = p->pBt;
47064   assert( sqlite3_mutex_held(p->db->mutex) );
47065   sqlite3BtreeEnter(p);
47066   sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync);
47067   sqlite3BtreeLeave(p);
47068   return SQLITE_OK;
47069 }
47070 #endif
47071
47072 /*
47073 ** Return TRUE if the given btree is set to safety level 1.  In other
47074 ** words, return TRUE if no sync() occurs on the disk files.
47075 */
47076 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
47077   BtShared *pBt = p->pBt;
47078   int rc;
47079   assert( sqlite3_mutex_held(p->db->mutex) );  
47080   sqlite3BtreeEnter(p);
47081   assert( pBt && pBt->pPager );
47082   rc = sqlite3PagerNosync(pBt->pPager);
47083   sqlite3BtreeLeave(p);
47084   return rc;
47085 }
47086
47087 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
47088 /*
47089 ** Change the default pages size and the number of reserved bytes per page.
47090 ** Or, if the page size has already been fixed, return SQLITE_READONLY 
47091 ** without changing anything.
47092 **
47093 ** The page size must be a power of 2 between 512 and 65536.  If the page
47094 ** size supplied does not meet this constraint then the page size is not
47095 ** changed.
47096 **
47097 ** Page sizes are constrained to be a power of two so that the region
47098 ** of the database file used for locking (beginning at PENDING_BYTE,
47099 ** the first byte past the 1GB boundary, 0x40000000) needs to occur
47100 ** at the beginning of a page.
47101 **
47102 ** If parameter nReserve is less than zero, then the number of reserved
47103 ** bytes per page is left unchanged.
47104 **
47105 ** If the iFix!=0 then the pageSizeFixed flag is set so that the page size
47106 ** and autovacuum mode can no longer be changed.
47107 */
47108 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
47109   int rc = SQLITE_OK;
47110   BtShared *pBt = p->pBt;
47111   assert( nReserve>=-1 && nReserve<=255 );
47112   sqlite3BtreeEnter(p);
47113   if( pBt->pageSizeFixed ){
47114     sqlite3BtreeLeave(p);
47115     return SQLITE_READONLY;
47116   }
47117   if( nReserve<0 ){
47118     nReserve = pBt->pageSize - pBt->usableSize;
47119   }
47120   assert( nReserve>=0 && nReserve<=255 );
47121   if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
47122         ((pageSize-1)&pageSize)==0 ){
47123     assert( (pageSize & 7)==0 );
47124     assert( !pBt->pPage1 && !pBt->pCursor );
47125     pBt->pageSize = (u32)pageSize;
47126     freeTempSpace(pBt);
47127   }
47128   rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
47129   pBt->usableSize = pBt->pageSize - (u16)nReserve;
47130   if( iFix ) pBt->pageSizeFixed = 1;
47131   sqlite3BtreeLeave(p);
47132   return rc;
47133 }
47134
47135 /*
47136 ** Return the currently defined page size
47137 */
47138 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
47139   return p->pBt->pageSize;
47140 }
47141
47142 /*
47143 ** Return the number of bytes of space at the end of every page that
47144 ** are intentually left unused.  This is the "reserved" space that is
47145 ** sometimes used by extensions.
47146 */
47147 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
47148   int n;
47149   sqlite3BtreeEnter(p);
47150   n = p->pBt->pageSize - p->pBt->usableSize;
47151   sqlite3BtreeLeave(p);
47152   return n;
47153 }
47154
47155 /*
47156 ** Set the maximum page count for a database if mxPage is positive.
47157 ** No changes are made if mxPage is 0 or negative.
47158 ** Regardless of the value of mxPage, return the maximum page count.
47159 */
47160 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
47161   int n;
47162   sqlite3BtreeEnter(p);
47163   n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
47164   sqlite3BtreeLeave(p);
47165   return n;
47166 }
47167
47168 /*
47169 ** Set the secureDelete flag if newFlag is 0 or 1.  If newFlag is -1,
47170 ** then make no changes.  Always return the value of the secureDelete
47171 ** setting after the change.
47172 */
47173 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
47174   int b;
47175   if( p==0 ) return 0;
47176   sqlite3BtreeEnter(p);
47177   if( newFlag>=0 ){
47178     p->pBt->secureDelete = (newFlag!=0) ? 1 : 0;
47179   } 
47180   b = p->pBt->secureDelete;
47181   sqlite3BtreeLeave(p);
47182   return b;
47183 }
47184 #endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
47185
47186 /*
47187 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
47188 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
47189 ** is disabled. The default value for the auto-vacuum property is 
47190 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
47191 */
47192 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
47193 #ifdef SQLITE_OMIT_AUTOVACUUM
47194   return SQLITE_READONLY;
47195 #else
47196   BtShared *pBt = p->pBt;
47197   int rc = SQLITE_OK;
47198   u8 av = (u8)autoVacuum;
47199
47200   sqlite3BtreeEnter(p);
47201   if( pBt->pageSizeFixed && (av ?1:0)!=pBt->autoVacuum ){
47202     rc = SQLITE_READONLY;
47203   }else{
47204     pBt->autoVacuum = av ?1:0;
47205     pBt->incrVacuum = av==2 ?1:0;
47206   }
47207   sqlite3BtreeLeave(p);
47208   return rc;
47209 #endif
47210 }
47211
47212 /*
47213 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is 
47214 ** enabled 1 is returned. Otherwise 0.
47215 */
47216 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
47217 #ifdef SQLITE_OMIT_AUTOVACUUM
47218   return BTREE_AUTOVACUUM_NONE;
47219 #else
47220   int rc;
47221   sqlite3BtreeEnter(p);
47222   rc = (
47223     (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
47224     (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
47225     BTREE_AUTOVACUUM_INCR
47226   );
47227   sqlite3BtreeLeave(p);
47228   return rc;
47229 #endif
47230 }
47231
47232
47233 /*
47234 ** Get a reference to pPage1 of the database file.  This will
47235 ** also acquire a readlock on that file.
47236 **
47237 ** SQLITE_OK is returned on success.  If the file is not a
47238 ** well-formed database file, then SQLITE_CORRUPT is returned.
47239 ** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
47240 ** is returned if we run out of memory. 
47241 */
47242 static int lockBtree(BtShared *pBt){
47243   int rc;              /* Result code from subfunctions */
47244   MemPage *pPage1;     /* Page 1 of the database file */
47245   int nPage;           /* Number of pages in the database */
47246   int nPageFile = 0;   /* Number of pages in the database file */
47247   int nPageHeader;     /* Number of pages in the database according to hdr */
47248
47249   assert( sqlite3_mutex_held(pBt->mutex) );
47250   assert( pBt->pPage1==0 );
47251   rc = sqlite3PagerSharedLock(pBt->pPager);
47252   if( rc!=SQLITE_OK ) return rc;
47253   rc = btreeGetPage(pBt, 1, &pPage1, 0);
47254   if( rc!=SQLITE_OK ) return rc;
47255
47256   /* Do some checking to help insure the file we opened really is
47257   ** a valid database file. 
47258   */
47259   nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
47260   sqlite3PagerPagecount(pBt->pPager, &nPageFile);
47261   if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
47262     nPage = nPageFile;
47263   }
47264   if( nPage>0 ){
47265     u32 pageSize;
47266     u32 usableSize;
47267     u8 *page1 = pPage1->aData;
47268     rc = SQLITE_NOTADB;
47269     if( memcmp(page1, zMagicHeader, 16)!=0 ){
47270       goto page1_init_failed;
47271     }
47272
47273 #ifdef SQLITE_OMIT_WAL
47274     if( page1[18]>1 ){
47275       pBt->readOnly = 1;
47276     }
47277     if( page1[19]>1 ){
47278       goto page1_init_failed;
47279     }
47280 #else
47281     if( page1[18]>2 ){
47282       pBt->readOnly = 1;
47283     }
47284     if( page1[19]>2 ){
47285       goto page1_init_failed;
47286     }
47287
47288     /* If the write version is set to 2, this database should be accessed
47289     ** in WAL mode. If the log is not already open, open it now. Then 
47290     ** return SQLITE_OK and return without populating BtShared.pPage1.
47291     ** The caller detects this and calls this function again. This is
47292     ** required as the version of page 1 currently in the page1 buffer
47293     ** may not be the latest version - there may be a newer one in the log
47294     ** file.
47295     */
47296     if( page1[19]==2 && pBt->doNotUseWAL==0 ){
47297       int isOpen = 0;
47298       rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
47299       if( rc!=SQLITE_OK ){
47300         goto page1_init_failed;
47301       }else if( isOpen==0 ){
47302         releasePage(pPage1);
47303         return SQLITE_OK;
47304       }
47305       rc = SQLITE_NOTADB;
47306     }
47307 #endif
47308
47309     /* The maximum embedded fraction must be exactly 25%.  And the minimum
47310     ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
47311     ** The original design allowed these amounts to vary, but as of
47312     ** version 3.6.0, we require them to be fixed.
47313     */
47314     if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
47315       goto page1_init_failed;
47316     }
47317     pageSize = (page1[16]<<8) | (page1[17]<<16);
47318     if( ((pageSize-1)&pageSize)!=0
47319      || pageSize>SQLITE_MAX_PAGE_SIZE 
47320      || pageSize<=256 
47321     ){
47322       goto page1_init_failed;
47323     }
47324     assert( (pageSize & 7)==0 );
47325     usableSize = pageSize - page1[20];
47326     if( (u32)pageSize!=pBt->pageSize ){
47327       /* After reading the first page of the database assuming a page size
47328       ** of BtShared.pageSize, we have discovered that the page-size is
47329       ** actually pageSize. Unlock the database, leave pBt->pPage1 at
47330       ** zero and return SQLITE_OK. The caller will call this function
47331       ** again with the correct page-size.
47332       */
47333       releasePage(pPage1);
47334       pBt->usableSize = usableSize;
47335       pBt->pageSize = pageSize;
47336       freeTempSpace(pBt);
47337       rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
47338                                    pageSize-usableSize);
47339       return rc;
47340     }
47341     if( nPageHeader>nPageFile ){
47342       rc = SQLITE_CORRUPT_BKPT;
47343       goto page1_init_failed;
47344     }
47345     if( usableSize<480 ){
47346       goto page1_init_failed;
47347     }
47348     pBt->pageSize = pageSize;
47349     pBt->usableSize = usableSize;
47350 #ifndef SQLITE_OMIT_AUTOVACUUM
47351     pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
47352     pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
47353 #endif
47354   }
47355
47356   /* maxLocal is the maximum amount of payload to store locally for
47357   ** a cell.  Make sure it is small enough so that at least minFanout
47358   ** cells can will fit on one page.  We assume a 10-byte page header.
47359   ** Besides the payload, the cell must store:
47360   **     2-byte pointer to the cell
47361   **     4-byte child pointer
47362   **     9-byte nKey value
47363   **     4-byte nData value
47364   **     4-byte overflow page pointer
47365   ** So a cell consists of a 2-byte pointer, a header which is as much as
47366   ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
47367   ** page pointer.
47368   */
47369   pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
47370   pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
47371   pBt->maxLeaf = (u16)(pBt->usableSize - 35);
47372   pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
47373   assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
47374   pBt->pPage1 = pPage1;
47375   pBt->nPage = nPage;
47376   return SQLITE_OK;
47377
47378 page1_init_failed:
47379   releasePage(pPage1);
47380   pBt->pPage1 = 0;
47381   return rc;
47382 }
47383
47384 /*
47385 ** If there are no outstanding cursors and we are not in the middle
47386 ** of a transaction but there is a read lock on the database, then
47387 ** this routine unrefs the first page of the database file which 
47388 ** has the effect of releasing the read lock.
47389 **
47390 ** If there is a transaction in progress, this routine is a no-op.
47391 */
47392 static void unlockBtreeIfUnused(BtShared *pBt){
47393   assert( sqlite3_mutex_held(pBt->mutex) );
47394   assert( pBt->pCursor==0 || pBt->inTransaction>TRANS_NONE );
47395   if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
47396     assert( pBt->pPage1->aData );
47397     assert( sqlite3PagerRefcount(pBt->pPager)==1 );
47398     assert( pBt->pPage1->aData );
47399     releasePage(pBt->pPage1);
47400     pBt->pPage1 = 0;
47401   }
47402 }
47403
47404 /*
47405 ** If pBt points to an empty file then convert that empty file
47406 ** into a new empty database by initializing the first page of
47407 ** the database.
47408 */
47409 static int newDatabase(BtShared *pBt){
47410   MemPage *pP1;
47411   unsigned char *data;
47412   int rc;
47413
47414   assert( sqlite3_mutex_held(pBt->mutex) );
47415   if( pBt->nPage>0 ){
47416     return SQLITE_OK;
47417   }
47418   pP1 = pBt->pPage1;
47419   assert( pP1!=0 );
47420   data = pP1->aData;
47421   rc = sqlite3PagerWrite(pP1->pDbPage);
47422   if( rc ) return rc;
47423   memcpy(data, zMagicHeader, sizeof(zMagicHeader));
47424   assert( sizeof(zMagicHeader)==16 );
47425   data[16] = (u8)((pBt->pageSize>>8)&0xff);
47426   data[17] = (u8)((pBt->pageSize>>16)&0xff);
47427   data[18] = 1;
47428   data[19] = 1;
47429   assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
47430   data[20] = (u8)(pBt->pageSize - pBt->usableSize);
47431   data[21] = 64;
47432   data[22] = 32;
47433   data[23] = 32;
47434   memset(&data[24], 0, 100-24);
47435   zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
47436   pBt->pageSizeFixed = 1;
47437 #ifndef SQLITE_OMIT_AUTOVACUUM
47438   assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
47439   assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
47440   put4byte(&data[36 + 4*4], pBt->autoVacuum);
47441   put4byte(&data[36 + 7*4], pBt->incrVacuum);
47442 #endif
47443   pBt->nPage = 1;
47444   data[31] = 1;
47445   return SQLITE_OK;
47446 }
47447
47448 /*
47449 ** Attempt to start a new transaction. A write-transaction
47450 ** is started if the second argument is nonzero, otherwise a read-
47451 ** transaction.  If the second argument is 2 or more and exclusive
47452 ** transaction is started, meaning that no other process is allowed
47453 ** to access the database.  A preexisting transaction may not be
47454 ** upgraded to exclusive by calling this routine a second time - the
47455 ** exclusivity flag only works for a new transaction.
47456 **
47457 ** A write-transaction must be started before attempting any 
47458 ** changes to the database.  None of the following routines 
47459 ** will work unless a transaction is started first:
47460 **
47461 **      sqlite3BtreeCreateTable()
47462 **      sqlite3BtreeCreateIndex()
47463 **      sqlite3BtreeClearTable()
47464 **      sqlite3BtreeDropTable()
47465 **      sqlite3BtreeInsert()
47466 **      sqlite3BtreeDelete()
47467 **      sqlite3BtreeUpdateMeta()
47468 **
47469 ** If an initial attempt to acquire the lock fails because of lock contention
47470 ** and the database was previously unlocked, then invoke the busy handler
47471 ** if there is one.  But if there was previously a read-lock, do not
47472 ** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is 
47473 ** returned when there is already a read-lock in order to avoid a deadlock.
47474 **
47475 ** Suppose there are two processes A and B.  A has a read lock and B has
47476 ** a reserved lock.  B tries to promote to exclusive but is blocked because
47477 ** of A's read lock.  A tries to promote to reserved but is blocked by B.
47478 ** One or the other of the two processes must give way or there can be
47479 ** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
47480 ** when A already has a read lock, we encourage A to give up and let B
47481 ** proceed.
47482 */
47483 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
47484   sqlite3 *pBlock = 0;
47485   BtShared *pBt = p->pBt;
47486   int rc = SQLITE_OK;
47487
47488   sqlite3BtreeEnter(p);
47489   btreeIntegrity(p);
47490
47491   /* If the btree is already in a write-transaction, or it
47492   ** is already in a read-transaction and a read-transaction
47493   ** is requested, this is a no-op.
47494   */
47495   if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
47496     goto trans_begun;
47497   }
47498
47499   /* Write transactions are not possible on a read-only database */
47500   if( pBt->readOnly && wrflag ){
47501     rc = SQLITE_READONLY;
47502     goto trans_begun;
47503   }
47504
47505 #ifndef SQLITE_OMIT_SHARED_CACHE
47506   /* If another database handle has already opened a write transaction 
47507   ** on this shared-btree structure and a second write transaction is
47508   ** requested, return SQLITE_LOCKED.
47509   */
47510   if( (wrflag && pBt->inTransaction==TRANS_WRITE) || pBt->isPending ){
47511     pBlock = pBt->pWriter->db;
47512   }else if( wrflag>1 ){
47513     BtLock *pIter;
47514     for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
47515       if( pIter->pBtree!=p ){
47516         pBlock = pIter->pBtree->db;
47517         break;
47518       }
47519     }
47520   }
47521   if( pBlock ){
47522     sqlite3ConnectionBlocked(p->db, pBlock);
47523     rc = SQLITE_LOCKED_SHAREDCACHE;
47524     goto trans_begun;
47525   }
47526 #endif
47527
47528   /* Any read-only or read-write transaction implies a read-lock on 
47529   ** page 1. So if some other shared-cache client already has a write-lock 
47530   ** on page 1, the transaction cannot be opened. */
47531   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
47532   if( SQLITE_OK!=rc ) goto trans_begun;
47533
47534   pBt->initiallyEmpty = (u8)(pBt->nPage==0);
47535   do {
47536     /* Call lockBtree() until either pBt->pPage1 is populated or
47537     ** lockBtree() returns something other than SQLITE_OK. lockBtree()
47538     ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
47539     ** reading page 1 it discovers that the page-size of the database 
47540     ** file is not pBt->pageSize. In this case lockBtree() will update
47541     ** pBt->pageSize to the page-size of the file on disk.
47542     */
47543     while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
47544
47545     if( rc==SQLITE_OK && wrflag ){
47546       if( pBt->readOnly ){
47547         rc = SQLITE_READONLY;
47548       }else{
47549         rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
47550         if( rc==SQLITE_OK ){
47551           rc = newDatabase(pBt);
47552         }
47553       }
47554     }
47555   
47556     if( rc!=SQLITE_OK ){
47557       unlockBtreeIfUnused(pBt);
47558     }
47559   }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
47560           btreeInvokeBusyHandler(pBt) );
47561
47562   if( rc==SQLITE_OK ){
47563     if( p->inTrans==TRANS_NONE ){
47564       pBt->nTransaction++;
47565 #ifndef SQLITE_OMIT_SHARED_CACHE
47566       if( p->sharable ){
47567         assert( p->lock.pBtree==p && p->lock.iTable==1 );
47568         p->lock.eLock = READ_LOCK;
47569         p->lock.pNext = pBt->pLock;
47570         pBt->pLock = &p->lock;
47571       }
47572 #endif
47573     }
47574     p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
47575     if( p->inTrans>pBt->inTransaction ){
47576       pBt->inTransaction = p->inTrans;
47577     }
47578     if( wrflag ){
47579       MemPage *pPage1 = pBt->pPage1;
47580 #ifndef SQLITE_OMIT_SHARED_CACHE
47581       assert( !pBt->pWriter );
47582       pBt->pWriter = p;
47583       pBt->isExclusive = (u8)(wrflag>1);
47584 #endif
47585
47586       /* If the db-size header field is incorrect (as it may be if an old
47587       ** client has been writing the database file), update it now. Doing
47588       ** this sooner rather than later means the database size can safely 
47589       ** re-read the database size from page 1 if a savepoint or transaction
47590       ** rollback occurs within the transaction.
47591       */
47592       if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
47593         rc = sqlite3PagerWrite(pPage1->pDbPage);
47594         if( rc==SQLITE_OK ){
47595           put4byte(&pPage1->aData[28], pBt->nPage);
47596         }
47597       }
47598     }
47599   }
47600
47601
47602 trans_begun:
47603   if( rc==SQLITE_OK && wrflag ){
47604     /* This call makes sure that the pager has the correct number of
47605     ** open savepoints. If the second parameter is greater than 0 and
47606     ** the sub-journal is not already open, then it will be opened here.
47607     */
47608     rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
47609   }
47610
47611   btreeIntegrity(p);
47612   sqlite3BtreeLeave(p);
47613   return rc;
47614 }
47615
47616 #ifndef SQLITE_OMIT_AUTOVACUUM
47617
47618 /*
47619 ** Set the pointer-map entries for all children of page pPage. Also, if
47620 ** pPage contains cells that point to overflow pages, set the pointer
47621 ** map entries for the overflow pages as well.
47622 */
47623 static int setChildPtrmaps(MemPage *pPage){
47624   int i;                             /* Counter variable */
47625   int nCell;                         /* Number of cells in page pPage */
47626   int rc;                            /* Return code */
47627   BtShared *pBt = pPage->pBt;
47628   u8 isInitOrig = pPage->isInit;
47629   Pgno pgno = pPage->pgno;
47630
47631   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
47632   rc = btreeInitPage(pPage);
47633   if( rc!=SQLITE_OK ){
47634     goto set_child_ptrmaps_out;
47635   }
47636   nCell = pPage->nCell;
47637
47638   for(i=0; i<nCell; i++){
47639     u8 *pCell = findCell(pPage, i);
47640
47641     ptrmapPutOvflPtr(pPage, pCell, &rc);
47642
47643     if( !pPage->leaf ){
47644       Pgno childPgno = get4byte(pCell);
47645       ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
47646     }
47647   }
47648
47649   if( !pPage->leaf ){
47650     Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
47651     ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
47652   }
47653
47654 set_child_ptrmaps_out:
47655   pPage->isInit = isInitOrig;
47656   return rc;
47657 }
47658
47659 /*
47660 ** Somewhere on pPage is a pointer to page iFrom.  Modify this pointer so
47661 ** that it points to iTo. Parameter eType describes the type of pointer to
47662 ** be modified, as  follows:
47663 **
47664 ** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child 
47665 **                   page of pPage.
47666 **
47667 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
47668 **                   page pointed to by one of the cells on pPage.
47669 **
47670 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
47671 **                   overflow page in the list.
47672 */
47673 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
47674   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
47675   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
47676   if( eType==PTRMAP_OVERFLOW2 ){
47677     /* The pointer is always the first 4 bytes of the page in this case.  */
47678     if( get4byte(pPage->aData)!=iFrom ){
47679       return SQLITE_CORRUPT_BKPT;
47680     }
47681     put4byte(pPage->aData, iTo);
47682   }else{
47683     u8 isInitOrig = pPage->isInit;
47684     int i;
47685     int nCell;
47686
47687     btreeInitPage(pPage);
47688     nCell = pPage->nCell;
47689
47690     for(i=0; i<nCell; i++){
47691       u8 *pCell = findCell(pPage, i);
47692       if( eType==PTRMAP_OVERFLOW1 ){
47693         CellInfo info;
47694         btreeParseCellPtr(pPage, pCell, &info);
47695         if( info.iOverflow ){
47696           if( iFrom==get4byte(&pCell[info.iOverflow]) ){
47697             put4byte(&pCell[info.iOverflow], iTo);
47698             break;
47699           }
47700         }
47701       }else{
47702         if( get4byte(pCell)==iFrom ){
47703           put4byte(pCell, iTo);
47704           break;
47705         }
47706       }
47707     }
47708   
47709     if( i==nCell ){
47710       if( eType!=PTRMAP_BTREE || 
47711           get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
47712         return SQLITE_CORRUPT_BKPT;
47713       }
47714       put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
47715     }
47716
47717     pPage->isInit = isInitOrig;
47718   }
47719   return SQLITE_OK;
47720 }
47721
47722
47723 /*
47724 ** Move the open database page pDbPage to location iFreePage in the 
47725 ** database. The pDbPage reference remains valid.
47726 **
47727 ** The isCommit flag indicates that there is no need to remember that
47728 ** the journal needs to be sync()ed before database page pDbPage->pgno 
47729 ** can be written to. The caller has already promised not to write to that
47730 ** page.
47731 */
47732 static int relocatePage(
47733   BtShared *pBt,           /* Btree */
47734   MemPage *pDbPage,        /* Open page to move */
47735   u8 eType,                /* Pointer map 'type' entry for pDbPage */
47736   Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
47737   Pgno iFreePage,          /* The location to move pDbPage to */
47738   int isCommit             /* isCommit flag passed to sqlite3PagerMovepage */
47739 ){
47740   MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
47741   Pgno iDbPage = pDbPage->pgno;
47742   Pager *pPager = pBt->pPager;
47743   int rc;
47744
47745   assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 || 
47746       eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
47747   assert( sqlite3_mutex_held(pBt->mutex) );
47748   assert( pDbPage->pBt==pBt );
47749
47750   /* Move page iDbPage from its current location to page number iFreePage */
47751   TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n", 
47752       iDbPage, iFreePage, iPtrPage, eType));
47753   rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
47754   if( rc!=SQLITE_OK ){
47755     return rc;
47756   }
47757   pDbPage->pgno = iFreePage;
47758
47759   /* If pDbPage was a btree-page, then it may have child pages and/or cells
47760   ** that point to overflow pages. The pointer map entries for all these
47761   ** pages need to be changed.
47762   **
47763   ** If pDbPage is an overflow page, then the first 4 bytes may store a
47764   ** pointer to a subsequent overflow page. If this is the case, then
47765   ** the pointer map needs to be updated for the subsequent overflow page.
47766   */
47767   if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
47768     rc = setChildPtrmaps(pDbPage);
47769     if( rc!=SQLITE_OK ){
47770       return rc;
47771     }
47772   }else{
47773     Pgno nextOvfl = get4byte(pDbPage->aData);
47774     if( nextOvfl!=0 ){
47775       ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
47776       if( rc!=SQLITE_OK ){
47777         return rc;
47778       }
47779     }
47780   }
47781
47782   /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
47783   ** that it points at iFreePage. Also fix the pointer map entry for
47784   ** iPtrPage.
47785   */
47786   if( eType!=PTRMAP_ROOTPAGE ){
47787     rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
47788     if( rc!=SQLITE_OK ){
47789       return rc;
47790     }
47791     rc = sqlite3PagerWrite(pPtrPage->pDbPage);
47792     if( rc!=SQLITE_OK ){
47793       releasePage(pPtrPage);
47794       return rc;
47795     }
47796     rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
47797     releasePage(pPtrPage);
47798     if( rc==SQLITE_OK ){
47799       ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
47800     }
47801   }
47802   return rc;
47803 }
47804
47805 /* Forward declaration required by incrVacuumStep(). */
47806 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
47807
47808 /*
47809 ** Perform a single step of an incremental-vacuum. If successful,
47810 ** return SQLITE_OK. If there is no work to do (and therefore no
47811 ** point in calling this function again), return SQLITE_DONE.
47812 **
47813 ** More specificly, this function attempts to re-organize the 
47814 ** database so that the last page of the file currently in use
47815 ** is no longer in use.
47816 **
47817 ** If the nFin parameter is non-zero, this function assumes
47818 ** that the caller will keep calling incrVacuumStep() until
47819 ** it returns SQLITE_DONE or an error, and that nFin is the
47820 ** number of pages the database file will contain after this 
47821 ** process is complete.  If nFin is zero, it is assumed that
47822 ** incrVacuumStep() will be called a finite amount of times
47823 ** which may or may not empty the freelist.  A full autovacuum
47824 ** has nFin>0.  A "PRAGMA incremental_vacuum" has nFin==0.
47825 */
47826 static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg){
47827   Pgno nFreeList;           /* Number of pages still on the free-list */
47828   int rc;
47829
47830   assert( sqlite3_mutex_held(pBt->mutex) );
47831   assert( iLastPg>nFin );
47832
47833   if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
47834     u8 eType;
47835     Pgno iPtrPage;
47836
47837     nFreeList = get4byte(&pBt->pPage1->aData[36]);
47838     if( nFreeList==0 ){
47839       return SQLITE_DONE;
47840     }
47841
47842     rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
47843     if( rc!=SQLITE_OK ){
47844       return rc;
47845     }
47846     if( eType==PTRMAP_ROOTPAGE ){
47847       return SQLITE_CORRUPT_BKPT;
47848     }
47849
47850     if( eType==PTRMAP_FREEPAGE ){
47851       if( nFin==0 ){
47852         /* Remove the page from the files free-list. This is not required
47853         ** if nFin is non-zero. In that case, the free-list will be
47854         ** truncated to zero after this function returns, so it doesn't 
47855         ** matter if it still contains some garbage entries.
47856         */
47857         Pgno iFreePg;
47858         MemPage *pFreePg;
47859         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1);
47860         if( rc!=SQLITE_OK ){
47861           return rc;
47862         }
47863         assert( iFreePg==iLastPg );
47864         releasePage(pFreePg);
47865       }
47866     } else {
47867       Pgno iFreePg;             /* Index of free page to move pLastPg to */
47868       MemPage *pLastPg;
47869
47870       rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
47871       if( rc!=SQLITE_OK ){
47872         return rc;
47873       }
47874
47875       /* If nFin is zero, this loop runs exactly once and page pLastPg
47876       ** is swapped with the first free page pulled off the free list.
47877       **
47878       ** On the other hand, if nFin is greater than zero, then keep
47879       ** looping until a free-page located within the first nFin pages
47880       ** of the file is found.
47881       */
47882       do {
47883         MemPage *pFreePg;
47884         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0);
47885         if( rc!=SQLITE_OK ){
47886           releasePage(pLastPg);
47887           return rc;
47888         }
47889         releasePage(pFreePg);
47890       }while( nFin!=0 && iFreePg>nFin );
47891       assert( iFreePg<iLastPg );
47892       
47893       rc = sqlite3PagerWrite(pLastPg->pDbPage);
47894       if( rc==SQLITE_OK ){
47895         rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, nFin!=0);
47896       }
47897       releasePage(pLastPg);
47898       if( rc!=SQLITE_OK ){
47899         return rc;
47900       }
47901     }
47902   }
47903
47904   if( nFin==0 ){
47905     iLastPg--;
47906     while( iLastPg==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, iLastPg) ){
47907       if( PTRMAP_ISPAGE(pBt, iLastPg) ){
47908         MemPage *pPg;
47909         rc = btreeGetPage(pBt, iLastPg, &pPg, 0);
47910         if( rc!=SQLITE_OK ){
47911           return rc;
47912         }
47913         rc = sqlite3PagerWrite(pPg->pDbPage);
47914         releasePage(pPg);
47915         if( rc!=SQLITE_OK ){
47916           return rc;
47917         }
47918       }
47919       iLastPg--;
47920     }
47921     sqlite3PagerTruncateImage(pBt->pPager, iLastPg);
47922     pBt->nPage = iLastPg;
47923   }
47924   return SQLITE_OK;
47925 }
47926
47927 /*
47928 ** A write-transaction must be opened before calling this function.
47929 ** It performs a single unit of work towards an incremental vacuum.
47930 **
47931 ** If the incremental vacuum is finished after this function has run,
47932 ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
47933 ** SQLITE_OK is returned. Otherwise an SQLite error code. 
47934 */
47935 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
47936   int rc;
47937   BtShared *pBt = p->pBt;
47938
47939   sqlite3BtreeEnter(p);
47940   assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
47941   if( !pBt->autoVacuum ){
47942     rc = SQLITE_DONE;
47943   }else{
47944     invalidateAllOverflowCache(pBt);
47945     rc = incrVacuumStep(pBt, 0, btreePagecount(pBt));
47946     if( rc==SQLITE_OK ){
47947       rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
47948       put4byte(&pBt->pPage1->aData[28], pBt->nPage);
47949     }
47950   }
47951   sqlite3BtreeLeave(p);
47952   return rc;
47953 }
47954
47955 /*
47956 ** This routine is called prior to sqlite3PagerCommit when a transaction
47957 ** is commited for an auto-vacuum database.
47958 **
47959 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
47960 ** the database file should be truncated to during the commit process. 
47961 ** i.e. the database has been reorganized so that only the first *pnTrunc
47962 ** pages are in use.
47963 */
47964 static int autoVacuumCommit(BtShared *pBt){
47965   int rc = SQLITE_OK;
47966   Pager *pPager = pBt->pPager;
47967   VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
47968
47969   assert( sqlite3_mutex_held(pBt->mutex) );
47970   invalidateAllOverflowCache(pBt);
47971   assert(pBt->autoVacuum);
47972   if( !pBt->incrVacuum ){
47973     Pgno nFin;         /* Number of pages in database after autovacuuming */
47974     Pgno nFree;        /* Number of pages on the freelist initially */
47975     Pgno nPtrmap;      /* Number of PtrMap pages to be freed */
47976     Pgno iFree;        /* The next page to be freed */
47977     int nEntry;        /* Number of entries on one ptrmap page */
47978     Pgno nOrig;        /* Database size before freeing */
47979
47980     nOrig = btreePagecount(pBt);
47981     if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
47982       /* It is not possible to create a database for which the final page
47983       ** is either a pointer-map page or the pending-byte page. If one
47984       ** is encountered, this indicates corruption.
47985       */
47986       return SQLITE_CORRUPT_BKPT;
47987     }
47988
47989     nFree = get4byte(&pBt->pPage1->aData[36]);
47990     nEntry = pBt->usableSize/5;
47991     nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
47992     nFin = nOrig - nFree - nPtrmap;
47993     if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
47994       nFin--;
47995     }
47996     while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
47997       nFin--;
47998     }
47999     if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
48000
48001     for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
48002       rc = incrVacuumStep(pBt, nFin, iFree);
48003     }
48004     if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
48005       rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
48006       put4byte(&pBt->pPage1->aData[32], 0);
48007       put4byte(&pBt->pPage1->aData[36], 0);
48008       put4byte(&pBt->pPage1->aData[28], nFin);
48009       sqlite3PagerTruncateImage(pBt->pPager, nFin);
48010       pBt->nPage = nFin;
48011     }
48012     if( rc!=SQLITE_OK ){
48013       sqlite3PagerRollback(pPager);
48014     }
48015   }
48016
48017   assert( nRef==sqlite3PagerRefcount(pPager) );
48018   return rc;
48019 }
48020
48021 #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
48022 # define setChildPtrmaps(x) SQLITE_OK
48023 #endif
48024
48025 /*
48026 ** This routine does the first phase of a two-phase commit.  This routine
48027 ** causes a rollback journal to be created (if it does not already exist)
48028 ** and populated with enough information so that if a power loss occurs
48029 ** the database can be restored to its original state by playing back
48030 ** the journal.  Then the contents of the journal are flushed out to
48031 ** the disk.  After the journal is safely on oxide, the changes to the
48032 ** database are written into the database file and flushed to oxide.
48033 ** At the end of this call, the rollback journal still exists on the
48034 ** disk and we are still holding all locks, so the transaction has not
48035 ** committed.  See sqlite3BtreeCommitPhaseTwo() for the second phase of the
48036 ** commit process.
48037 **
48038 ** This call is a no-op if no write-transaction is currently active on pBt.
48039 **
48040 ** Otherwise, sync the database file for the btree pBt. zMaster points to
48041 ** the name of a master journal file that should be written into the
48042 ** individual journal file, or is NULL, indicating no master journal file 
48043 ** (single database transaction).
48044 **
48045 ** When this is called, the master journal should already have been
48046 ** created, populated with this journal pointer and synced to disk.
48047 **
48048 ** Once this is routine has returned, the only thing required to commit
48049 ** the write-transaction for this database file is to delete the journal.
48050 */
48051 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
48052   int rc = SQLITE_OK;
48053   if( p->inTrans==TRANS_WRITE ){
48054     BtShared *pBt = p->pBt;
48055     sqlite3BtreeEnter(p);
48056 #ifndef SQLITE_OMIT_AUTOVACUUM
48057     if( pBt->autoVacuum ){
48058       rc = autoVacuumCommit(pBt);
48059       if( rc!=SQLITE_OK ){
48060         sqlite3BtreeLeave(p);
48061         return rc;
48062       }
48063     }
48064 #endif
48065     rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
48066     sqlite3BtreeLeave(p);
48067   }
48068   return rc;
48069 }
48070
48071 /*
48072 ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
48073 ** at the conclusion of a transaction.
48074 */
48075 static void btreeEndTransaction(Btree *p){
48076   BtShared *pBt = p->pBt;
48077   assert( sqlite3BtreeHoldsMutex(p) );
48078
48079   btreeClearHasContent(pBt);
48080   if( p->inTrans>TRANS_NONE && p->db->activeVdbeCnt>1 ){
48081     /* If there are other active statements that belong to this database
48082     ** handle, downgrade to a read-only transaction. The other statements
48083     ** may still be reading from the database.  */
48084     downgradeAllSharedCacheTableLocks(p);
48085     p->inTrans = TRANS_READ;
48086   }else{
48087     /* If the handle had any kind of transaction open, decrement the 
48088     ** transaction count of the shared btree. If the transaction count 
48089     ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
48090     ** call below will unlock the pager.  */
48091     if( p->inTrans!=TRANS_NONE ){
48092       clearAllSharedCacheTableLocks(p);
48093       pBt->nTransaction--;
48094       if( 0==pBt->nTransaction ){
48095         pBt->inTransaction = TRANS_NONE;
48096       }
48097     }
48098
48099     /* Set the current transaction state to TRANS_NONE and unlock the 
48100     ** pager if this call closed the only read or write transaction.  */
48101     p->inTrans = TRANS_NONE;
48102     unlockBtreeIfUnused(pBt);
48103   }
48104
48105   btreeIntegrity(p);
48106 }
48107
48108 /*
48109 ** Commit the transaction currently in progress.
48110 **
48111 ** This routine implements the second phase of a 2-phase commit.  The
48112 ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
48113 ** be invoked prior to calling this routine.  The sqlite3BtreeCommitPhaseOne()
48114 ** routine did all the work of writing information out to disk and flushing the
48115 ** contents so that they are written onto the disk platter.  All this
48116 ** routine has to do is delete or truncate or zero the header in the
48117 ** the rollback journal (which causes the transaction to commit) and
48118 ** drop locks.
48119 **
48120 ** This will release the write lock on the database file.  If there
48121 ** are no active cursors, it also releases the read lock.
48122 */
48123 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p){
48124   BtShared *pBt = p->pBt;
48125
48126   sqlite3BtreeEnter(p);
48127   btreeIntegrity(p);
48128
48129   /* If the handle has a write-transaction open, commit the shared-btrees 
48130   ** transaction and set the shared state to TRANS_READ.
48131   */
48132   if( p->inTrans==TRANS_WRITE ){
48133     int rc;
48134     assert( pBt->inTransaction==TRANS_WRITE );
48135     assert( pBt->nTransaction>0 );
48136     rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
48137     if( rc!=SQLITE_OK ){
48138       sqlite3BtreeLeave(p);
48139       return rc;
48140     }
48141     pBt->inTransaction = TRANS_READ;
48142   }
48143
48144   btreeEndTransaction(p);
48145   sqlite3BtreeLeave(p);
48146   return SQLITE_OK;
48147 }
48148
48149 /*
48150 ** Do both phases of a commit.
48151 */
48152 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
48153   int rc;
48154   sqlite3BtreeEnter(p);
48155   rc = sqlite3BtreeCommitPhaseOne(p, 0);
48156   if( rc==SQLITE_OK ){
48157     rc = sqlite3BtreeCommitPhaseTwo(p);
48158   }
48159   sqlite3BtreeLeave(p);
48160   return rc;
48161 }
48162
48163 #ifndef NDEBUG
48164 /*
48165 ** Return the number of write-cursors open on this handle. This is for use
48166 ** in assert() expressions, so it is only compiled if NDEBUG is not
48167 ** defined.
48168 **
48169 ** For the purposes of this routine, a write-cursor is any cursor that
48170 ** is capable of writing to the databse.  That means the cursor was
48171 ** originally opened for writing and the cursor has not be disabled
48172 ** by having its state changed to CURSOR_FAULT.
48173 */
48174 static int countWriteCursors(BtShared *pBt){
48175   BtCursor *pCur;
48176   int r = 0;
48177   for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
48178     if( pCur->wrFlag && pCur->eState!=CURSOR_FAULT ) r++; 
48179   }
48180   return r;
48181 }
48182 #endif
48183
48184 /*
48185 ** This routine sets the state to CURSOR_FAULT and the error
48186 ** code to errCode for every cursor on BtShared that pBtree
48187 ** references.
48188 **
48189 ** Every cursor is tripped, including cursors that belong
48190 ** to other database connections that happen to be sharing
48191 ** the cache with pBtree.
48192 **
48193 ** This routine gets called when a rollback occurs.
48194 ** All cursors using the same cache must be tripped
48195 ** to prevent them from trying to use the btree after
48196 ** the rollback.  The rollback may have deleted tables
48197 ** or moved root pages, so it is not sufficient to
48198 ** save the state of the cursor.  The cursor must be
48199 ** invalidated.
48200 */
48201 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
48202   BtCursor *p;
48203   sqlite3BtreeEnter(pBtree);
48204   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
48205     int i;
48206     sqlite3BtreeClearCursor(p);
48207     p->eState = CURSOR_FAULT;
48208     p->skipNext = errCode;
48209     for(i=0; i<=p->iPage; i++){
48210       releasePage(p->apPage[i]);
48211       p->apPage[i] = 0;
48212     }
48213   }
48214   sqlite3BtreeLeave(pBtree);
48215 }
48216
48217 /*
48218 ** Rollback the transaction in progress.  All cursors will be
48219 ** invalided by this operation.  Any attempt to use a cursor
48220 ** that was open at the beginning of this operation will result
48221 ** in an error.
48222 **
48223 ** This will release the write lock on the database file.  If there
48224 ** are no active cursors, it also releases the read lock.
48225 */
48226 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p){
48227   int rc;
48228   BtShared *pBt = p->pBt;
48229   MemPage *pPage1;
48230
48231   sqlite3BtreeEnter(p);
48232   rc = saveAllCursors(pBt, 0, 0);
48233 #ifndef SQLITE_OMIT_SHARED_CACHE
48234   if( rc!=SQLITE_OK ){
48235     /* This is a horrible situation. An IO or malloc() error occurred whilst
48236     ** trying to save cursor positions. If this is an automatic rollback (as
48237     ** the result of a constraint, malloc() failure or IO error) then 
48238     ** the cache may be internally inconsistent (not contain valid trees) so
48239     ** we cannot simply return the error to the caller. Instead, abort 
48240     ** all queries that may be using any of the cursors that failed to save.
48241     */
48242     sqlite3BtreeTripAllCursors(p, rc);
48243   }
48244 #endif
48245   btreeIntegrity(p);
48246
48247   if( p->inTrans==TRANS_WRITE ){
48248     int rc2;
48249
48250     assert( TRANS_WRITE==pBt->inTransaction );
48251     rc2 = sqlite3PagerRollback(pBt->pPager);
48252     if( rc2!=SQLITE_OK ){
48253       rc = rc2;
48254     }
48255
48256     /* The rollback may have destroyed the pPage1->aData value.  So
48257     ** call btreeGetPage() on page 1 again to make
48258     ** sure pPage1->aData is set correctly. */
48259     if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
48260       int nPage = get4byte(28+(u8*)pPage1->aData);
48261       testcase( nPage==0 );
48262       if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
48263       testcase( pBt->nPage!=nPage );
48264       pBt->nPage = nPage;
48265       releasePage(pPage1);
48266     }
48267     assert( countWriteCursors(pBt)==0 );
48268     pBt->inTransaction = TRANS_READ;
48269   }
48270
48271   btreeEndTransaction(p);
48272   sqlite3BtreeLeave(p);
48273   return rc;
48274 }
48275
48276 /*
48277 ** Start a statement subtransaction. The subtransaction can can be rolled
48278 ** back independently of the main transaction. You must start a transaction 
48279 ** before starting a subtransaction. The subtransaction is ended automatically 
48280 ** if the main transaction commits or rolls back.
48281 **
48282 ** Statement subtransactions are used around individual SQL statements
48283 ** that are contained within a BEGIN...COMMIT block.  If a constraint
48284 ** error occurs within the statement, the effect of that one statement
48285 ** can be rolled back without having to rollback the entire transaction.
48286 **
48287 ** A statement sub-transaction is implemented as an anonymous savepoint. The
48288 ** value passed as the second parameter is the total number of savepoints,
48289 ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
48290 ** are no active savepoints and no other statement-transactions open,
48291 ** iStatement is 1. This anonymous savepoint can be released or rolled back
48292 ** using the sqlite3BtreeSavepoint() function.
48293 */
48294 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
48295   int rc;
48296   BtShared *pBt = p->pBt;
48297   sqlite3BtreeEnter(p);
48298   assert( p->inTrans==TRANS_WRITE );
48299   assert( pBt->readOnly==0 );
48300   assert( iStatement>0 );
48301   assert( iStatement>p->db->nSavepoint );
48302   assert( pBt->inTransaction==TRANS_WRITE );
48303   /* At the pager level, a statement transaction is a savepoint with
48304   ** an index greater than all savepoints created explicitly using
48305   ** SQL statements. It is illegal to open, release or rollback any
48306   ** such savepoints while the statement transaction savepoint is active.
48307   */
48308   rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
48309   sqlite3BtreeLeave(p);
48310   return rc;
48311 }
48312
48313 /*
48314 ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
48315 ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
48316 ** savepoint identified by parameter iSavepoint, depending on the value 
48317 ** of op.
48318 **
48319 ** Normally, iSavepoint is greater than or equal to zero. However, if op is
48320 ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the 
48321 ** contents of the entire transaction are rolled back. This is different
48322 ** from a normal transaction rollback, as no locks are released and the
48323 ** transaction remains open.
48324 */
48325 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
48326   int rc = SQLITE_OK;
48327   if( p && p->inTrans==TRANS_WRITE ){
48328     BtShared *pBt = p->pBt;
48329     assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
48330     assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
48331     sqlite3BtreeEnter(p);
48332     rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
48333     if( rc==SQLITE_OK ){
48334       if( iSavepoint<0 && pBt->initiallyEmpty ) pBt->nPage = 0;
48335       rc = newDatabase(pBt);
48336       pBt->nPage = get4byte(28 + pBt->pPage1->aData);
48337
48338       /* The database size was written into the offset 28 of the header
48339       ** when the transaction started, so we know that the value at offset
48340       ** 28 is nonzero. */
48341       assert( pBt->nPage>0 );
48342     }
48343     sqlite3BtreeLeave(p);
48344   }
48345   return rc;
48346 }
48347
48348 /*
48349 ** Create a new cursor for the BTree whose root is on the page
48350 ** iTable. If a read-only cursor is requested, it is assumed that
48351 ** the caller already has at least a read-only transaction open
48352 ** on the database already. If a write-cursor is requested, then
48353 ** the caller is assumed to have an open write transaction.
48354 **
48355 ** If wrFlag==0, then the cursor can only be used for reading.
48356 ** If wrFlag==1, then the cursor can be used for reading or for
48357 ** writing if other conditions for writing are also met.  These
48358 ** are the conditions that must be met in order for writing to
48359 ** be allowed:
48360 **
48361 ** 1:  The cursor must have been opened with wrFlag==1
48362 **
48363 ** 2:  Other database connections that share the same pager cache
48364 **     but which are not in the READ_UNCOMMITTED state may not have
48365 **     cursors open with wrFlag==0 on the same table.  Otherwise
48366 **     the changes made by this write cursor would be visible to
48367 **     the read cursors in the other database connection.
48368 **
48369 ** 3:  The database must be writable (not on read-only media)
48370 **
48371 ** 4:  There must be an active transaction.
48372 **
48373 ** No checking is done to make sure that page iTable really is the
48374 ** root page of a b-tree.  If it is not, then the cursor acquired
48375 ** will not work correctly.
48376 **
48377 ** It is assumed that the sqlite3BtreeCursorZero() has been called
48378 ** on pCur to initialize the memory space prior to invoking this routine.
48379 */
48380 static int btreeCursor(
48381   Btree *p,                              /* The btree */
48382   int iTable,                            /* Root page of table to open */
48383   int wrFlag,                            /* 1 to write. 0 read-only */
48384   struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
48385   BtCursor *pCur                         /* Space for new cursor */
48386 ){
48387   BtShared *pBt = p->pBt;                /* Shared b-tree handle */
48388
48389   assert( sqlite3BtreeHoldsMutex(p) );
48390   assert( wrFlag==0 || wrFlag==1 );
48391
48392   /* The following assert statements verify that if this is a sharable 
48393   ** b-tree database, the connection is holding the required table locks, 
48394   ** and that no other connection has any open cursor that conflicts with 
48395   ** this lock.  */
48396   assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
48397   assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
48398
48399   /* Assert that the caller has opened the required transaction. */
48400   assert( p->inTrans>TRANS_NONE );
48401   assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
48402   assert( pBt->pPage1 && pBt->pPage1->aData );
48403
48404   if( NEVER(wrFlag && pBt->readOnly) ){
48405     return SQLITE_READONLY;
48406   }
48407   if( iTable==1 && btreePagecount(pBt)==0 ){
48408     return SQLITE_EMPTY;
48409   }
48410
48411   /* Now that no other errors can occur, finish filling in the BtCursor
48412   ** variables and link the cursor into the BtShared list.  */
48413   pCur->pgnoRoot = (Pgno)iTable;
48414   pCur->iPage = -1;
48415   pCur->pKeyInfo = pKeyInfo;
48416   pCur->pBtree = p;
48417   pCur->pBt = pBt;
48418   pCur->wrFlag = (u8)wrFlag;
48419   pCur->pNext = pBt->pCursor;
48420   if( pCur->pNext ){
48421     pCur->pNext->pPrev = pCur;
48422   }
48423   pBt->pCursor = pCur;
48424   pCur->eState = CURSOR_INVALID;
48425   pCur->cachedRowid = 0;
48426   return SQLITE_OK;
48427 }
48428 SQLITE_PRIVATE int sqlite3BtreeCursor(
48429   Btree *p,                                   /* The btree */
48430   int iTable,                                 /* Root page of table to open */
48431   int wrFlag,                                 /* 1 to write. 0 read-only */
48432   struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
48433   BtCursor *pCur                              /* Write new cursor here */
48434 ){
48435   int rc;
48436   sqlite3BtreeEnter(p);
48437   rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
48438   sqlite3BtreeLeave(p);
48439   return rc;
48440 }
48441
48442 /*
48443 ** Return the size of a BtCursor object in bytes.
48444 **
48445 ** This interfaces is needed so that users of cursors can preallocate
48446 ** sufficient storage to hold a cursor.  The BtCursor object is opaque
48447 ** to users so they cannot do the sizeof() themselves - they must call
48448 ** this routine.
48449 */
48450 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
48451   return ROUND8(sizeof(BtCursor));
48452 }
48453
48454 /*
48455 ** Initialize memory that will be converted into a BtCursor object.
48456 **
48457 ** The simple approach here would be to memset() the entire object
48458 ** to zero.  But it turns out that the apPage[] and aiIdx[] arrays
48459 ** do not need to be zeroed and they are large, so we can save a lot
48460 ** of run-time by skipping the initialization of those elements.
48461 */
48462 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
48463   memset(p, 0, offsetof(BtCursor, iPage));
48464 }
48465
48466 /*
48467 ** Set the cached rowid value of every cursor in the same database file
48468 ** as pCur and having the same root page number as pCur.  The value is
48469 ** set to iRowid.
48470 **
48471 ** Only positive rowid values are considered valid for this cache.
48472 ** The cache is initialized to zero, indicating an invalid cache.
48473 ** A btree will work fine with zero or negative rowids.  We just cannot
48474 ** cache zero or negative rowids, which means tables that use zero or
48475 ** negative rowids might run a little slower.  But in practice, zero
48476 ** or negative rowids are very uncommon so this should not be a problem.
48477 */
48478 SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor *pCur, sqlite3_int64 iRowid){
48479   BtCursor *p;
48480   for(p=pCur->pBt->pCursor; p; p=p->pNext){
48481     if( p->pgnoRoot==pCur->pgnoRoot ) p->cachedRowid = iRowid;
48482   }
48483   assert( pCur->cachedRowid==iRowid );
48484 }
48485
48486 /*
48487 ** Return the cached rowid for the given cursor.  A negative or zero
48488 ** return value indicates that the rowid cache is invalid and should be
48489 ** ignored.  If the rowid cache has never before been set, then a
48490 ** zero is returned.
48491 */
48492 SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor *pCur){
48493   return pCur->cachedRowid;
48494 }
48495
48496 /*
48497 ** Close a cursor.  The read lock on the database file is released
48498 ** when the last cursor is closed.
48499 */
48500 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
48501   Btree *pBtree = pCur->pBtree;
48502   if( pBtree ){
48503     int i;
48504     BtShared *pBt = pCur->pBt;
48505     sqlite3BtreeEnter(pBtree);
48506     sqlite3BtreeClearCursor(pCur);
48507     if( pCur->pPrev ){
48508       pCur->pPrev->pNext = pCur->pNext;
48509     }else{
48510       pBt->pCursor = pCur->pNext;
48511     }
48512     if( pCur->pNext ){
48513       pCur->pNext->pPrev = pCur->pPrev;
48514     }
48515     for(i=0; i<=pCur->iPage; i++){
48516       releasePage(pCur->apPage[i]);
48517     }
48518     unlockBtreeIfUnused(pBt);
48519     invalidateOverflowCache(pCur);
48520     /* sqlite3_free(pCur); */
48521     sqlite3BtreeLeave(pBtree);
48522   }
48523   return SQLITE_OK;
48524 }
48525
48526 /*
48527 ** Make sure the BtCursor* given in the argument has a valid
48528 ** BtCursor.info structure.  If it is not already valid, call
48529 ** btreeParseCell() to fill it in.
48530 **
48531 ** BtCursor.info is a cache of the information in the current cell.
48532 ** Using this cache reduces the number of calls to btreeParseCell().
48533 **
48534 ** 2007-06-25:  There is a bug in some versions of MSVC that cause the
48535 ** compiler to crash when getCellInfo() is implemented as a macro.
48536 ** But there is a measureable speed advantage to using the macro on gcc
48537 ** (when less compiler optimizations like -Os or -O0 are used and the
48538 ** compiler is not doing agressive inlining.)  So we use a real function
48539 ** for MSVC and a macro for everything else.  Ticket #2457.
48540 */
48541 #ifndef NDEBUG
48542   static void assertCellInfo(BtCursor *pCur){
48543     CellInfo info;
48544     int iPage = pCur->iPage;
48545     memset(&info, 0, sizeof(info));
48546     btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
48547     assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
48548   }
48549 #else
48550   #define assertCellInfo(x)
48551 #endif
48552 #ifdef _MSC_VER
48553   /* Use a real function in MSVC to work around bugs in that compiler. */
48554   static void getCellInfo(BtCursor *pCur){
48555     if( pCur->info.nSize==0 ){
48556       int iPage = pCur->iPage;
48557       btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
48558       pCur->validNKey = 1;
48559     }else{
48560       assertCellInfo(pCur);
48561     }
48562   }
48563 #else /* if not _MSC_VER */
48564   /* Use a macro in all other compilers so that the function is inlined */
48565 #define getCellInfo(pCur)                                                      \
48566   if( pCur->info.nSize==0 ){                                                   \
48567     int iPage = pCur->iPage;                                                   \
48568     btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
48569     pCur->validNKey = 1;                                                       \
48570   }else{                                                                       \
48571     assertCellInfo(pCur);                                                      \
48572   }
48573 #endif /* _MSC_VER */
48574
48575 #ifndef NDEBUG  /* The next routine used only within assert() statements */
48576 /*
48577 ** Return true if the given BtCursor is valid.  A valid cursor is one
48578 ** that is currently pointing to a row in a (non-empty) table.
48579 ** This is a verification routine is used only within assert() statements.
48580 */
48581 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
48582   return pCur && pCur->eState==CURSOR_VALID;
48583 }
48584 #endif /* NDEBUG */
48585
48586 /*
48587 ** Set *pSize to the size of the buffer needed to hold the value of
48588 ** the key for the current entry.  If the cursor is not pointing
48589 ** to a valid entry, *pSize is set to 0. 
48590 **
48591 ** For a table with the INTKEY flag set, this routine returns the key
48592 ** itself, not the number of bytes in the key.
48593 **
48594 ** The caller must position the cursor prior to invoking this routine.
48595 ** 
48596 ** This routine cannot fail.  It always returns SQLITE_OK.  
48597 */
48598 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
48599   assert( cursorHoldsMutex(pCur) );
48600   assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
48601   if( pCur->eState!=CURSOR_VALID ){
48602     *pSize = 0;
48603   }else{
48604     getCellInfo(pCur);
48605     *pSize = pCur->info.nKey;
48606   }
48607   return SQLITE_OK;
48608 }
48609
48610 /*
48611 ** Set *pSize to the number of bytes of data in the entry the
48612 ** cursor currently points to.
48613 **
48614 ** The caller must guarantee that the cursor is pointing to a non-NULL
48615 ** valid entry.  In other words, the calling procedure must guarantee
48616 ** that the cursor has Cursor.eState==CURSOR_VALID.
48617 **
48618 ** Failure is not possible.  This function always returns SQLITE_OK.
48619 ** It might just as well be a procedure (returning void) but we continue
48620 ** to return an integer result code for historical reasons.
48621 */
48622 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
48623   assert( cursorHoldsMutex(pCur) );
48624   assert( pCur->eState==CURSOR_VALID );
48625   getCellInfo(pCur);
48626   *pSize = pCur->info.nData;
48627   return SQLITE_OK;
48628 }
48629
48630 /*
48631 ** Given the page number of an overflow page in the database (parameter
48632 ** ovfl), this function finds the page number of the next page in the 
48633 ** linked list of overflow pages. If possible, it uses the auto-vacuum
48634 ** pointer-map data instead of reading the content of page ovfl to do so. 
48635 **
48636 ** If an error occurs an SQLite error code is returned. Otherwise:
48637 **
48638 ** The page number of the next overflow page in the linked list is 
48639 ** written to *pPgnoNext. If page ovfl is the last page in its linked 
48640 ** list, *pPgnoNext is set to zero. 
48641 **
48642 ** If ppPage is not NULL, and a reference to the MemPage object corresponding
48643 ** to page number pOvfl was obtained, then *ppPage is set to point to that
48644 ** reference. It is the responsibility of the caller to call releasePage()
48645 ** on *ppPage to free the reference. In no reference was obtained (because
48646 ** the pointer-map was used to obtain the value for *pPgnoNext), then
48647 ** *ppPage is set to zero.
48648 */
48649 static int getOverflowPage(
48650   BtShared *pBt,               /* The database file */
48651   Pgno ovfl,                   /* Current overflow page number */
48652   MemPage **ppPage,            /* OUT: MemPage handle (may be NULL) */
48653   Pgno *pPgnoNext              /* OUT: Next overflow page number */
48654 ){
48655   Pgno next = 0;
48656   MemPage *pPage = 0;
48657   int rc = SQLITE_OK;
48658
48659   assert( sqlite3_mutex_held(pBt->mutex) );
48660   assert(pPgnoNext);
48661
48662 #ifndef SQLITE_OMIT_AUTOVACUUM
48663   /* Try to find the next page in the overflow list using the
48664   ** autovacuum pointer-map pages. Guess that the next page in 
48665   ** the overflow list is page number (ovfl+1). If that guess turns 
48666   ** out to be wrong, fall back to loading the data of page 
48667   ** number ovfl to determine the next page number.
48668   */
48669   if( pBt->autoVacuum ){
48670     Pgno pgno;
48671     Pgno iGuess = ovfl+1;
48672     u8 eType;
48673
48674     while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
48675       iGuess++;
48676     }
48677
48678     if( iGuess<=btreePagecount(pBt) ){
48679       rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
48680       if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
48681         next = iGuess;
48682         rc = SQLITE_DONE;
48683       }
48684     }
48685   }
48686 #endif
48687
48688   assert( next==0 || rc==SQLITE_DONE );
48689   if( rc==SQLITE_OK ){
48690     rc = btreeGetPage(pBt, ovfl, &pPage, 0);
48691     assert( rc==SQLITE_OK || pPage==0 );
48692     if( rc==SQLITE_OK ){
48693       next = get4byte(pPage->aData);
48694     }
48695   }
48696
48697   *pPgnoNext = next;
48698   if( ppPage ){
48699     *ppPage = pPage;
48700   }else{
48701     releasePage(pPage);
48702   }
48703   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
48704 }
48705
48706 /*
48707 ** Copy data from a buffer to a page, or from a page to a buffer.
48708 **
48709 ** pPayload is a pointer to data stored on database page pDbPage.
48710 ** If argument eOp is false, then nByte bytes of data are copied
48711 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
48712 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
48713 ** of data are copied from the buffer pBuf to pPayload.
48714 **
48715 ** SQLITE_OK is returned on success, otherwise an error code.
48716 */
48717 static int copyPayload(
48718   void *pPayload,           /* Pointer to page data */
48719   void *pBuf,               /* Pointer to buffer */
48720   int nByte,                /* Number of bytes to copy */
48721   int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
48722   DbPage *pDbPage           /* Page containing pPayload */
48723 ){
48724   if( eOp ){
48725     /* Copy data from buffer to page (a write operation) */
48726     int rc = sqlite3PagerWrite(pDbPage);
48727     if( rc!=SQLITE_OK ){
48728       return rc;
48729     }
48730     memcpy(pPayload, pBuf, nByte);
48731   }else{
48732     /* Copy data from page to buffer (a read operation) */
48733     memcpy(pBuf, pPayload, nByte);
48734   }
48735   return SQLITE_OK;
48736 }
48737
48738 /*
48739 ** This function is used to read or overwrite payload information
48740 ** for the entry that the pCur cursor is pointing to. If the eOp
48741 ** parameter is 0, this is a read operation (data copied into
48742 ** buffer pBuf). If it is non-zero, a write (data copied from
48743 ** buffer pBuf).
48744 **
48745 ** A total of "amt" bytes are read or written beginning at "offset".
48746 ** Data is read to or from the buffer pBuf.
48747 **
48748 ** The content being read or written might appear on the main page
48749 ** or be scattered out on multiple overflow pages.
48750 **
48751 ** If the BtCursor.isIncrblobHandle flag is set, and the current
48752 ** cursor entry uses one or more overflow pages, this function
48753 ** allocates space for and lazily popluates the overflow page-list 
48754 ** cache array (BtCursor.aOverflow). Subsequent calls use this
48755 ** cache to make seeking to the supplied offset more efficient.
48756 **
48757 ** Once an overflow page-list cache has been allocated, it may be
48758 ** invalidated if some other cursor writes to the same table, or if
48759 ** the cursor is moved to a different row. Additionally, in auto-vacuum
48760 ** mode, the following events may invalidate an overflow page-list cache.
48761 **
48762 **   * An incremental vacuum,
48763 **   * A commit in auto_vacuum="full" mode,
48764 **   * Creating a table (may require moving an overflow page).
48765 */
48766 static int accessPayload(
48767   BtCursor *pCur,      /* Cursor pointing to entry to read from */
48768   u32 offset,          /* Begin reading this far into payload */
48769   u32 amt,             /* Read this many bytes */
48770   unsigned char *pBuf, /* Write the bytes into this buffer */ 
48771   int eOp              /* zero to read. non-zero to write. */
48772 ){
48773   unsigned char *aPayload;
48774   int rc = SQLITE_OK;
48775   u32 nKey;
48776   int iIdx = 0;
48777   MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
48778   BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */
48779
48780   assert( pPage );
48781   assert( pCur->eState==CURSOR_VALID );
48782   assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
48783   assert( cursorHoldsMutex(pCur) );
48784
48785   getCellInfo(pCur);
48786   aPayload = pCur->info.pCell + pCur->info.nHeader;
48787   nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
48788
48789   if( NEVER(offset+amt > nKey+pCur->info.nData) 
48790    || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
48791   ){
48792     /* Trying to read or write past the end of the data is an error */
48793     return SQLITE_CORRUPT_BKPT;
48794   }
48795
48796   /* Check if data must be read/written to/from the btree page itself. */
48797   if( offset<pCur->info.nLocal ){
48798     int a = amt;
48799     if( a+offset>pCur->info.nLocal ){
48800       a = pCur->info.nLocal - offset;
48801     }
48802     rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
48803     offset = 0;
48804     pBuf += a;
48805     amt -= a;
48806   }else{
48807     offset -= pCur->info.nLocal;
48808   }
48809
48810   if( rc==SQLITE_OK && amt>0 ){
48811     const u32 ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
48812     Pgno nextPage;
48813
48814     nextPage = get4byte(&aPayload[pCur->info.nLocal]);
48815
48816 #ifndef SQLITE_OMIT_INCRBLOB
48817     /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
48818     ** has not been allocated, allocate it now. The array is sized at
48819     ** one entry for each overflow page in the overflow chain. The
48820     ** page number of the first overflow page is stored in aOverflow[0],
48821     ** etc. A value of 0 in the aOverflow[] array means "not yet known"
48822     ** (the cache is lazily populated).
48823     */
48824     if( pCur->isIncrblobHandle && !pCur->aOverflow ){
48825       int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
48826       pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
48827       /* nOvfl is always positive.  If it were zero, fetchPayload would have
48828       ** been used instead of this routine. */
48829       if( ALWAYS(nOvfl) && !pCur->aOverflow ){
48830         rc = SQLITE_NOMEM;
48831       }
48832     }
48833
48834     /* If the overflow page-list cache has been allocated and the
48835     ** entry for the first required overflow page is valid, skip
48836     ** directly to it.
48837     */
48838     if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
48839       iIdx = (offset/ovflSize);
48840       nextPage = pCur->aOverflow[iIdx];
48841       offset = (offset%ovflSize);
48842     }
48843 #endif
48844
48845     for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
48846
48847 #ifndef SQLITE_OMIT_INCRBLOB
48848       /* If required, populate the overflow page-list cache. */
48849       if( pCur->aOverflow ){
48850         assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
48851         pCur->aOverflow[iIdx] = nextPage;
48852       }
48853 #endif
48854
48855       if( offset>=ovflSize ){
48856         /* The only reason to read this page is to obtain the page
48857         ** number for the next page in the overflow chain. The page
48858         ** data is not required. So first try to lookup the overflow
48859         ** page-list cache, if any, then fall back to the getOverflowPage()
48860         ** function.
48861         */
48862 #ifndef SQLITE_OMIT_INCRBLOB
48863         if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
48864           nextPage = pCur->aOverflow[iIdx+1];
48865         } else 
48866 #endif
48867           rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
48868         offset -= ovflSize;
48869       }else{
48870         /* Need to read this page properly. It contains some of the
48871         ** range of data that is being read (eOp==0) or written (eOp!=0).
48872         */
48873         DbPage *pDbPage;
48874         int a = amt;
48875         rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage);
48876         if( rc==SQLITE_OK ){
48877           aPayload = sqlite3PagerGetData(pDbPage);
48878           nextPage = get4byte(aPayload);
48879           if( a + offset > ovflSize ){
48880             a = ovflSize - offset;
48881           }
48882           rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
48883           sqlite3PagerUnref(pDbPage);
48884           offset = 0;
48885           amt -= a;
48886           pBuf += a;
48887         }
48888       }
48889     }
48890   }
48891
48892   if( rc==SQLITE_OK && amt>0 ){
48893     return SQLITE_CORRUPT_BKPT;
48894   }
48895   return rc;
48896 }
48897
48898 /*
48899 ** Read part of the key associated with cursor pCur.  Exactly
48900 ** "amt" bytes will be transfered into pBuf[].  The transfer
48901 ** begins at "offset".
48902 **
48903 ** The caller must ensure that pCur is pointing to a valid row
48904 ** in the table.
48905 **
48906 ** Return SQLITE_OK on success or an error code if anything goes
48907 ** wrong.  An error is returned if "offset+amt" is larger than
48908 ** the available payload.
48909 */
48910 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
48911   assert( cursorHoldsMutex(pCur) );
48912   assert( pCur->eState==CURSOR_VALID );
48913   assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
48914   assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
48915   return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
48916 }
48917
48918 /*
48919 ** Read part of the data associated with cursor pCur.  Exactly
48920 ** "amt" bytes will be transfered into pBuf[].  The transfer
48921 ** begins at "offset".
48922 **
48923 ** Return SQLITE_OK on success or an error code if anything goes
48924 ** wrong.  An error is returned if "offset+amt" is larger than
48925 ** the available payload.
48926 */
48927 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
48928   int rc;
48929
48930 #ifndef SQLITE_OMIT_INCRBLOB
48931   if ( pCur->eState==CURSOR_INVALID ){
48932     return SQLITE_ABORT;
48933   }
48934 #endif
48935
48936   assert( cursorHoldsMutex(pCur) );
48937   rc = restoreCursorPosition(pCur);
48938   if( rc==SQLITE_OK ){
48939     assert( pCur->eState==CURSOR_VALID );
48940     assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
48941     assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
48942     rc = accessPayload(pCur, offset, amt, pBuf, 0);
48943   }
48944   return rc;
48945 }
48946
48947 /*
48948 ** Return a pointer to payload information from the entry that the 
48949 ** pCur cursor is pointing to.  The pointer is to the beginning of
48950 ** the key if skipKey==0 and it points to the beginning of data if
48951 ** skipKey==1.  The number of bytes of available key/data is written
48952 ** into *pAmt.  If *pAmt==0, then the value returned will not be
48953 ** a valid pointer.
48954 **
48955 ** This routine is an optimization.  It is common for the entire key
48956 ** and data to fit on the local page and for there to be no overflow
48957 ** pages.  When that is so, this routine can be used to access the
48958 ** key and data without making a copy.  If the key and/or data spills
48959 ** onto overflow pages, then accessPayload() must be used to reassemble
48960 ** the key/data and copy it into a preallocated buffer.
48961 **
48962 ** The pointer returned by this routine looks directly into the cached
48963 ** page of the database.  The data might change or move the next time
48964 ** any btree routine is called.
48965 */
48966 static const unsigned char *fetchPayload(
48967   BtCursor *pCur,      /* Cursor pointing to entry to read from */
48968   int *pAmt,           /* Write the number of available bytes here */
48969   int skipKey          /* read beginning at data if this is true */
48970 ){
48971   unsigned char *aPayload;
48972   MemPage *pPage;
48973   u32 nKey;
48974   u32 nLocal;
48975
48976   assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
48977   assert( pCur->eState==CURSOR_VALID );
48978   assert( cursorHoldsMutex(pCur) );
48979   pPage = pCur->apPage[pCur->iPage];
48980   assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
48981   if( NEVER(pCur->info.nSize==0) ){
48982     btreeParseCell(pCur->apPage[pCur->iPage], pCur->aiIdx[pCur->iPage],
48983                    &pCur->info);
48984   }
48985   aPayload = pCur->info.pCell;
48986   aPayload += pCur->info.nHeader;
48987   if( pPage->intKey ){
48988     nKey = 0;
48989   }else{
48990     nKey = (int)pCur->info.nKey;
48991   }
48992   if( skipKey ){
48993     aPayload += nKey;
48994     nLocal = pCur->info.nLocal - nKey;
48995   }else{
48996     nLocal = pCur->info.nLocal;
48997     assert( nLocal<=nKey );
48998   }
48999   *pAmt = nLocal;
49000   return aPayload;
49001 }
49002
49003
49004 /*
49005 ** For the entry that cursor pCur is point to, return as
49006 ** many bytes of the key or data as are available on the local
49007 ** b-tree page.  Write the number of available bytes into *pAmt.
49008 **
49009 ** The pointer returned is ephemeral.  The key/data may move
49010 ** or be destroyed on the next call to any Btree routine,
49011 ** including calls from other threads against the same cache.
49012 ** Hence, a mutex on the BtShared should be held prior to calling
49013 ** this routine.
49014 **
49015 ** These routines is used to get quick access to key and data
49016 ** in the common case where no overflow pages are used.
49017 */
49018 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
49019   const void *p = 0;
49020   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
49021   assert( cursorHoldsMutex(pCur) );
49022   if( ALWAYS(pCur->eState==CURSOR_VALID) ){
49023     p = (const void*)fetchPayload(pCur, pAmt, 0);
49024   }
49025   return p;
49026 }
49027 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
49028   const void *p = 0;
49029   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
49030   assert( cursorHoldsMutex(pCur) );
49031   if( ALWAYS(pCur->eState==CURSOR_VALID) ){
49032     p = (const void*)fetchPayload(pCur, pAmt, 1);
49033   }
49034   return p;
49035 }
49036
49037
49038 /*
49039 ** Move the cursor down to a new child page.  The newPgno argument is the
49040 ** page number of the child page to move to.
49041 **
49042 ** This function returns SQLITE_CORRUPT if the page-header flags field of
49043 ** the new child page does not match the flags field of the parent (i.e.
49044 ** if an intkey page appears to be the parent of a non-intkey page, or
49045 ** vice-versa).
49046 */
49047 static int moveToChild(BtCursor *pCur, u32 newPgno){
49048   int rc;
49049   int i = pCur->iPage;
49050   MemPage *pNewPage;
49051   BtShared *pBt = pCur->pBt;
49052
49053   assert( cursorHoldsMutex(pCur) );
49054   assert( pCur->eState==CURSOR_VALID );
49055   assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
49056   if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
49057     return SQLITE_CORRUPT_BKPT;
49058   }
49059   rc = getAndInitPage(pBt, newPgno, &pNewPage);
49060   if( rc ) return rc;
49061   pCur->apPage[i+1] = pNewPage;
49062   pCur->aiIdx[i+1] = 0;
49063   pCur->iPage++;
49064
49065   pCur->info.nSize = 0;
49066   pCur->validNKey = 0;
49067   if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
49068     return SQLITE_CORRUPT_BKPT;
49069   }
49070   return SQLITE_OK;
49071 }
49072
49073 #ifndef NDEBUG
49074 /*
49075 ** Page pParent is an internal (non-leaf) tree page. This function 
49076 ** asserts that page number iChild is the left-child if the iIdx'th
49077 ** cell in page pParent. Or, if iIdx is equal to the total number of
49078 ** cells in pParent, that page number iChild is the right-child of
49079 ** the page.
49080 */
49081 static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
49082   assert( iIdx<=pParent->nCell );
49083   if( iIdx==pParent->nCell ){
49084     assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
49085   }else{
49086     assert( get4byte(findCell(pParent, iIdx))==iChild );
49087   }
49088 }
49089 #else
49090 #  define assertParentIndex(x,y,z) 
49091 #endif
49092
49093 /*
49094 ** Move the cursor up to the parent page.
49095 **
49096 ** pCur->idx is set to the cell index that contains the pointer
49097 ** to the page we are coming from.  If we are coming from the
49098 ** right-most child page then pCur->idx is set to one more than
49099 ** the largest cell index.
49100 */
49101 static void moveToParent(BtCursor *pCur){
49102   assert( cursorHoldsMutex(pCur) );
49103   assert( pCur->eState==CURSOR_VALID );
49104   assert( pCur->iPage>0 );
49105   assert( pCur->apPage[pCur->iPage] );
49106   assertParentIndex(
49107     pCur->apPage[pCur->iPage-1], 
49108     pCur->aiIdx[pCur->iPage-1], 
49109     pCur->apPage[pCur->iPage]->pgno
49110   );
49111   releasePage(pCur->apPage[pCur->iPage]);
49112   pCur->iPage--;
49113   pCur->info.nSize = 0;
49114   pCur->validNKey = 0;
49115 }
49116
49117 /*
49118 ** Move the cursor to point to the root page of its b-tree structure.
49119 **
49120 ** If the table has a virtual root page, then the cursor is moved to point
49121 ** to the virtual root page instead of the actual root page. A table has a
49122 ** virtual root page when the actual root page contains no cells and a 
49123 ** single child page. This can only happen with the table rooted at page 1.
49124 **
49125 ** If the b-tree structure is empty, the cursor state is set to 
49126 ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
49127 ** cell located on the root (or virtual root) page and the cursor state
49128 ** is set to CURSOR_VALID.
49129 **
49130 ** If this function returns successfully, it may be assumed that the
49131 ** page-header flags indicate that the [virtual] root-page is the expected 
49132 ** kind of b-tree page (i.e. if when opening the cursor the caller did not
49133 ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
49134 ** indicating a table b-tree, or if the caller did specify a KeyInfo 
49135 ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
49136 ** b-tree).
49137 */
49138 static int moveToRoot(BtCursor *pCur){
49139   MemPage *pRoot;
49140   int rc = SQLITE_OK;
49141   Btree *p = pCur->pBtree;
49142   BtShared *pBt = p->pBt;
49143
49144   assert( cursorHoldsMutex(pCur) );
49145   assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
49146   assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
49147   assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
49148   if( pCur->eState>=CURSOR_REQUIRESEEK ){
49149     if( pCur->eState==CURSOR_FAULT ){
49150       assert( pCur->skipNext!=SQLITE_OK );
49151       return pCur->skipNext;
49152     }
49153     sqlite3BtreeClearCursor(pCur);
49154   }
49155
49156   if( pCur->iPage>=0 ){
49157     int i;
49158     for(i=1; i<=pCur->iPage; i++){
49159       releasePage(pCur->apPage[i]);
49160     }
49161     pCur->iPage = 0;
49162   }else{
49163     rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]);
49164     if( rc!=SQLITE_OK ){
49165       pCur->eState = CURSOR_INVALID;
49166       return rc;
49167     }
49168     pCur->iPage = 0;
49169
49170     /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
49171     ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
49172     ** NULL, the caller expects a table b-tree. If this is not the case,
49173     ** return an SQLITE_CORRUPT error.  */
49174     assert( pCur->apPage[0]->intKey==1 || pCur->apPage[0]->intKey==0 );
49175     if( (pCur->pKeyInfo==0)!=pCur->apPage[0]->intKey ){
49176       return SQLITE_CORRUPT_BKPT;
49177     }
49178   }
49179
49180   /* Assert that the root page is of the correct type. This must be the
49181   ** case as the call to this function that loaded the root-page (either
49182   ** this call or a previous invocation) would have detected corruption 
49183   ** if the assumption were not true, and it is not possible for the flags 
49184   ** byte to have been modified while this cursor is holding a reference
49185   ** to the page.  */
49186   pRoot = pCur->apPage[0];
49187   assert( pRoot->pgno==pCur->pgnoRoot );
49188   assert( pRoot->isInit && (pCur->pKeyInfo==0)==pRoot->intKey );
49189
49190   pCur->aiIdx[0] = 0;
49191   pCur->info.nSize = 0;
49192   pCur->atLast = 0;
49193   pCur->validNKey = 0;
49194
49195   if( pRoot->nCell==0 && !pRoot->leaf ){
49196     Pgno subpage;
49197     if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
49198     subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
49199     pCur->eState = CURSOR_VALID;
49200     rc = moveToChild(pCur, subpage);
49201   }else{
49202     pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
49203   }
49204   return rc;
49205 }
49206
49207 /*
49208 ** Move the cursor down to the left-most leaf entry beneath the
49209 ** entry to which it is currently pointing.
49210 **
49211 ** The left-most leaf is the one with the smallest key - the first
49212 ** in ascending order.
49213 */
49214 static int moveToLeftmost(BtCursor *pCur){
49215   Pgno pgno;
49216   int rc = SQLITE_OK;
49217   MemPage *pPage;
49218
49219   assert( cursorHoldsMutex(pCur) );
49220   assert( pCur->eState==CURSOR_VALID );
49221   while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
49222     assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
49223     pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
49224     rc = moveToChild(pCur, pgno);
49225   }
49226   return rc;
49227 }
49228
49229 /*
49230 ** Move the cursor down to the right-most leaf entry beneath the
49231 ** page to which it is currently pointing.  Notice the difference
49232 ** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
49233 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
49234 ** finds the right-most entry beneath the *page*.
49235 **
49236 ** The right-most entry is the one with the largest key - the last
49237 ** key in ascending order.
49238 */
49239 static int moveToRightmost(BtCursor *pCur){
49240   Pgno pgno;
49241   int rc = SQLITE_OK;
49242   MemPage *pPage = 0;
49243
49244   assert( cursorHoldsMutex(pCur) );
49245   assert( pCur->eState==CURSOR_VALID );
49246   while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
49247     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
49248     pCur->aiIdx[pCur->iPage] = pPage->nCell;
49249     rc = moveToChild(pCur, pgno);
49250   }
49251   if( rc==SQLITE_OK ){
49252     pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
49253     pCur->info.nSize = 0;
49254     pCur->validNKey = 0;
49255   }
49256   return rc;
49257 }
49258
49259 /* Move the cursor to the first entry in the table.  Return SQLITE_OK
49260 ** on success.  Set *pRes to 0 if the cursor actually points to something
49261 ** or set *pRes to 1 if the table is empty.
49262 */
49263 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
49264   int rc;
49265
49266   assert( cursorHoldsMutex(pCur) );
49267   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
49268   rc = moveToRoot(pCur);
49269   if( rc==SQLITE_OK ){
49270     if( pCur->eState==CURSOR_INVALID ){
49271       assert( pCur->apPage[pCur->iPage]->nCell==0 );
49272       *pRes = 1;
49273     }else{
49274       assert( pCur->apPage[pCur->iPage]->nCell>0 );
49275       *pRes = 0;
49276       rc = moveToLeftmost(pCur);
49277     }
49278   }
49279   return rc;
49280 }
49281
49282 /* Move the cursor to the last entry in the table.  Return SQLITE_OK
49283 ** on success.  Set *pRes to 0 if the cursor actually points to something
49284 ** or set *pRes to 1 if the table is empty.
49285 */
49286 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
49287   int rc;
49288  
49289   assert( cursorHoldsMutex(pCur) );
49290   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
49291
49292   /* If the cursor already points to the last entry, this is a no-op. */
49293   if( CURSOR_VALID==pCur->eState && pCur->atLast ){
49294 #ifdef SQLITE_DEBUG
49295     /* This block serves to assert() that the cursor really does point 
49296     ** to the last entry in the b-tree. */
49297     int ii;
49298     for(ii=0; ii<pCur->iPage; ii++){
49299       assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
49300     }
49301     assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
49302     assert( pCur->apPage[pCur->iPage]->leaf );
49303 #endif
49304     return SQLITE_OK;
49305   }
49306
49307   rc = moveToRoot(pCur);
49308   if( rc==SQLITE_OK ){
49309     if( CURSOR_INVALID==pCur->eState ){
49310       assert( pCur->apPage[pCur->iPage]->nCell==0 );
49311       *pRes = 1;
49312     }else{
49313       assert( pCur->eState==CURSOR_VALID );
49314       *pRes = 0;
49315       rc = moveToRightmost(pCur);
49316       pCur->atLast = rc==SQLITE_OK ?1:0;
49317     }
49318   }
49319   return rc;
49320 }
49321
49322 /* Move the cursor so that it points to an entry near the key 
49323 ** specified by pIdxKey or intKey.   Return a success code.
49324 **
49325 ** For INTKEY tables, the intKey parameter is used.  pIdxKey 
49326 ** must be NULL.  For index tables, pIdxKey is used and intKey
49327 ** is ignored.
49328 **
49329 ** If an exact match is not found, then the cursor is always
49330 ** left pointing at a leaf page which would hold the entry if it
49331 ** were present.  The cursor might point to an entry that comes
49332 ** before or after the key.
49333 **
49334 ** An integer is written into *pRes which is the result of
49335 ** comparing the key with the entry to which the cursor is 
49336 ** pointing.  The meaning of the integer written into
49337 ** *pRes is as follows:
49338 **
49339 **     *pRes<0      The cursor is left pointing at an entry that
49340 **                  is smaller than intKey/pIdxKey or if the table is empty
49341 **                  and the cursor is therefore left point to nothing.
49342 **
49343 **     *pRes==0     The cursor is left pointing at an entry that
49344 **                  exactly matches intKey/pIdxKey.
49345 **
49346 **     *pRes>0      The cursor is left pointing at an entry that
49347 **                  is larger than intKey/pIdxKey.
49348 **
49349 */
49350 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
49351   BtCursor *pCur,          /* The cursor to be moved */
49352   UnpackedRecord *pIdxKey, /* Unpacked index key */
49353   i64 intKey,              /* The table key */
49354   int biasRight,           /* If true, bias the search to the high end */
49355   int *pRes                /* Write search results here */
49356 ){
49357   int rc;
49358
49359   assert( cursorHoldsMutex(pCur) );
49360   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
49361   assert( pRes );
49362   assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
49363
49364   /* If the cursor is already positioned at the point we are trying
49365   ** to move to, then just return without doing any work */
49366   if( pCur->eState==CURSOR_VALID && pCur->validNKey 
49367    && pCur->apPage[0]->intKey 
49368   ){
49369     if( pCur->info.nKey==intKey ){
49370       *pRes = 0;
49371       return SQLITE_OK;
49372     }
49373     if( pCur->atLast && pCur->info.nKey<intKey ){
49374       *pRes = -1;
49375       return SQLITE_OK;
49376     }
49377   }
49378
49379   rc = moveToRoot(pCur);
49380   if( rc ){
49381     return rc;
49382   }
49383   assert( pCur->apPage[pCur->iPage] );
49384   assert( pCur->apPage[pCur->iPage]->isInit );
49385   assert( pCur->apPage[pCur->iPage]->nCell>0 || pCur->eState==CURSOR_INVALID );
49386   if( pCur->eState==CURSOR_INVALID ){
49387     *pRes = -1;
49388     assert( pCur->apPage[pCur->iPage]->nCell==0 );
49389     return SQLITE_OK;
49390   }
49391   assert( pCur->apPage[0]->intKey || pIdxKey );
49392   for(;;){
49393     int lwr, upr;
49394     Pgno chldPg;
49395     MemPage *pPage = pCur->apPage[pCur->iPage];
49396     int c;
49397
49398     /* pPage->nCell must be greater than zero. If this is the root-page
49399     ** the cursor would have been INVALID above and this for(;;) loop
49400     ** not run. If this is not the root-page, then the moveToChild() routine
49401     ** would have already detected db corruption. Similarly, pPage must
49402     ** be the right kind (index or table) of b-tree page. Otherwise
49403     ** a moveToChild() or moveToRoot() call would have detected corruption.  */
49404     assert( pPage->nCell>0 );
49405     assert( pPage->intKey==(pIdxKey==0) );
49406     lwr = 0;
49407     upr = pPage->nCell-1;
49408     if( biasRight ){
49409       pCur->aiIdx[pCur->iPage] = (u16)upr;
49410     }else{
49411       pCur->aiIdx[pCur->iPage] = (u16)((upr+lwr)/2);
49412     }
49413     for(;;){
49414       int idx = pCur->aiIdx[pCur->iPage]; /* Index of current cell in pPage */
49415       u8 *pCell;                          /* Pointer to current cell in pPage */
49416
49417       pCur->info.nSize = 0;
49418       pCell = findCell(pPage, idx) + pPage->childPtrSize;
49419       if( pPage->intKey ){
49420         i64 nCellKey;
49421         if( pPage->hasData ){
49422           u32 dummy;
49423           pCell += getVarint32(pCell, dummy);
49424         }
49425         getVarint(pCell, (u64*)&nCellKey);
49426         if( nCellKey==intKey ){
49427           c = 0;
49428         }else if( nCellKey<intKey ){
49429           c = -1;
49430         }else{
49431           assert( nCellKey>intKey );
49432           c = +1;
49433         }
49434         pCur->validNKey = 1;
49435         pCur->info.nKey = nCellKey;
49436       }else{
49437         /* The maximum supported page-size is 65536 bytes. This means that
49438         ** the maximum number of record bytes stored on an index B-Tree
49439         ** page is less than 16384 bytes and may be stored as a 2-byte
49440         ** varint. This information is used to attempt to avoid parsing 
49441         ** the entire cell by checking for the cases where the record is 
49442         ** stored entirely within the b-tree page by inspecting the first 
49443         ** 2 bytes of the cell.
49444         */
49445         int nCell = pCell[0];
49446         if( !(nCell & 0x80) && nCell<=pPage->maxLocal ){
49447           /* This branch runs if the record-size field of the cell is a
49448           ** single byte varint and the record fits entirely on the main
49449           ** b-tree page.  */
49450           c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
49451         }else if( !(pCell[1] & 0x80) 
49452           && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
49453         ){
49454           /* The record-size field is a 2 byte varint and the record 
49455           ** fits entirely on the main b-tree page.  */
49456           c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
49457         }else{
49458           /* The record flows over onto one or more overflow pages. In
49459           ** this case the whole cell needs to be parsed, a buffer allocated
49460           ** and accessPayload() used to retrieve the record into the
49461           ** buffer before VdbeRecordCompare() can be called. */
49462           void *pCellKey;
49463           u8 * const pCellBody = pCell - pPage->childPtrSize;
49464           btreeParseCellPtr(pPage, pCellBody, &pCur->info);
49465           nCell = (int)pCur->info.nKey;
49466           pCellKey = sqlite3Malloc( nCell );
49467           if( pCellKey==0 ){
49468             rc = SQLITE_NOMEM;
49469             goto moveto_finish;
49470           }
49471           rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
49472           if( rc ){
49473             sqlite3_free(pCellKey);
49474             goto moveto_finish;
49475           }
49476           c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
49477           sqlite3_free(pCellKey);
49478         }
49479       }
49480       if( c==0 ){
49481         if( pPage->intKey && !pPage->leaf ){
49482           lwr = idx;
49483           upr = lwr - 1;
49484           break;
49485         }else{
49486           *pRes = 0;
49487           rc = SQLITE_OK;
49488           goto moveto_finish;
49489         }
49490       }
49491       if( c<0 ){
49492         lwr = idx+1;
49493       }else{
49494         upr = idx-1;
49495       }
49496       if( lwr>upr ){
49497         break;
49498       }
49499       pCur->aiIdx[pCur->iPage] = (u16)((lwr+upr)/2);
49500     }
49501     assert( lwr==upr+1 );
49502     assert( pPage->isInit );
49503     if( pPage->leaf ){
49504       chldPg = 0;
49505     }else if( lwr>=pPage->nCell ){
49506       chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
49507     }else{
49508       chldPg = get4byte(findCell(pPage, lwr));
49509     }
49510     if( chldPg==0 ){
49511       assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
49512       *pRes = c;
49513       rc = SQLITE_OK;
49514       goto moveto_finish;
49515     }
49516     pCur->aiIdx[pCur->iPage] = (u16)lwr;
49517     pCur->info.nSize = 0;
49518     pCur->validNKey = 0;
49519     rc = moveToChild(pCur, chldPg);
49520     if( rc ) goto moveto_finish;
49521   }
49522 moveto_finish:
49523   return rc;
49524 }
49525
49526
49527 /*
49528 ** Return TRUE if the cursor is not pointing at an entry of the table.
49529 **
49530 ** TRUE will be returned after a call to sqlite3BtreeNext() moves
49531 ** past the last entry in the table or sqlite3BtreePrev() moves past
49532 ** the first entry.  TRUE is also returned if the table is empty.
49533 */
49534 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
49535   /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
49536   ** have been deleted? This API will need to change to return an error code
49537   ** as well as the boolean result value.
49538   */
49539   return (CURSOR_VALID!=pCur->eState);
49540 }
49541
49542 /*
49543 ** Advance the cursor to the next entry in the database.  If
49544 ** successful then set *pRes=0.  If the cursor
49545 ** was already pointing to the last entry in the database before
49546 ** this routine was called, then set *pRes=1.
49547 */
49548 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
49549   int rc;
49550   int idx;
49551   MemPage *pPage;
49552
49553   assert( cursorHoldsMutex(pCur) );
49554   rc = restoreCursorPosition(pCur);
49555   if( rc!=SQLITE_OK ){
49556     return rc;
49557   }
49558   assert( pRes!=0 );
49559   if( CURSOR_INVALID==pCur->eState ){
49560     *pRes = 1;
49561     return SQLITE_OK;
49562   }
49563   if( pCur->skipNext>0 ){
49564     pCur->skipNext = 0;
49565     *pRes = 0;
49566     return SQLITE_OK;
49567   }
49568   pCur->skipNext = 0;
49569
49570   pPage = pCur->apPage[pCur->iPage];
49571   idx = ++pCur->aiIdx[pCur->iPage];
49572   assert( pPage->isInit );
49573   assert( idx<=pPage->nCell );
49574
49575   pCur->info.nSize = 0;
49576   pCur->validNKey = 0;
49577   if( idx>=pPage->nCell ){
49578     if( !pPage->leaf ){
49579       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
49580       if( rc ) return rc;
49581       rc = moveToLeftmost(pCur);
49582       *pRes = 0;
49583       return rc;
49584     }
49585     do{
49586       if( pCur->iPage==0 ){
49587         *pRes = 1;
49588         pCur->eState = CURSOR_INVALID;
49589         return SQLITE_OK;
49590       }
49591       moveToParent(pCur);
49592       pPage = pCur->apPage[pCur->iPage];
49593     }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
49594     *pRes = 0;
49595     if( pPage->intKey ){
49596       rc = sqlite3BtreeNext(pCur, pRes);
49597     }else{
49598       rc = SQLITE_OK;
49599     }
49600     return rc;
49601   }
49602   *pRes = 0;
49603   if( pPage->leaf ){
49604     return SQLITE_OK;
49605   }
49606   rc = moveToLeftmost(pCur);
49607   return rc;
49608 }
49609
49610
49611 /*
49612 ** Step the cursor to the back to the previous entry in the database.  If
49613 ** successful then set *pRes=0.  If the cursor
49614 ** was already pointing to the first entry in the database before
49615 ** this routine was called, then set *pRes=1.
49616 */
49617 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
49618   int rc;
49619   MemPage *pPage;
49620
49621   assert( cursorHoldsMutex(pCur) );
49622   rc = restoreCursorPosition(pCur);
49623   if( rc!=SQLITE_OK ){
49624     return rc;
49625   }
49626   pCur->atLast = 0;
49627   if( CURSOR_INVALID==pCur->eState ){
49628     *pRes = 1;
49629     return SQLITE_OK;
49630   }
49631   if( pCur->skipNext<0 ){
49632     pCur->skipNext = 0;
49633     *pRes = 0;
49634     return SQLITE_OK;
49635   }
49636   pCur->skipNext = 0;
49637
49638   pPage = pCur->apPage[pCur->iPage];
49639   assert( pPage->isInit );
49640   if( !pPage->leaf ){
49641     int idx = pCur->aiIdx[pCur->iPage];
49642     rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
49643     if( rc ){
49644       return rc;
49645     }
49646     rc = moveToRightmost(pCur);
49647   }else{
49648     while( pCur->aiIdx[pCur->iPage]==0 ){
49649       if( pCur->iPage==0 ){
49650         pCur->eState = CURSOR_INVALID;
49651         *pRes = 1;
49652         return SQLITE_OK;
49653       }
49654       moveToParent(pCur);
49655     }
49656     pCur->info.nSize = 0;
49657     pCur->validNKey = 0;
49658
49659     pCur->aiIdx[pCur->iPage]--;
49660     pPage = pCur->apPage[pCur->iPage];
49661     if( pPage->intKey && !pPage->leaf ){
49662       rc = sqlite3BtreePrevious(pCur, pRes);
49663     }else{
49664       rc = SQLITE_OK;
49665     }
49666   }
49667   *pRes = 0;
49668   return rc;
49669 }
49670
49671 /*
49672 ** Allocate a new page from the database file.
49673 **
49674 ** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
49675 ** has already been called on the new page.)  The new page has also
49676 ** been referenced and the calling routine is responsible for calling
49677 ** sqlite3PagerUnref() on the new page when it is done.
49678 **
49679 ** SQLITE_OK is returned on success.  Any other return value indicates
49680 ** an error.  *ppPage and *pPgno are undefined in the event of an error.
49681 ** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
49682 **
49683 ** If the "nearby" parameter is not 0, then a (feeble) effort is made to 
49684 ** locate a page close to the page number "nearby".  This can be used in an
49685 ** attempt to keep related pages close to each other in the database file,
49686 ** which in turn can make database access faster.
49687 **
49688 ** If the "exact" parameter is not 0, and the page-number nearby exists 
49689 ** anywhere on the free-list, then it is guarenteed to be returned. This
49690 ** is only used by auto-vacuum databases when allocating a new table.
49691 */
49692 static int allocateBtreePage(
49693   BtShared *pBt, 
49694   MemPage **ppPage, 
49695   Pgno *pPgno, 
49696   Pgno nearby,
49697   u8 exact
49698 ){
49699   MemPage *pPage1;
49700   int rc;
49701   u32 n;     /* Number of pages on the freelist */
49702   u32 k;     /* Number of leaves on the trunk of the freelist */
49703   MemPage *pTrunk = 0;
49704   MemPage *pPrevTrunk = 0;
49705   Pgno mxPage;     /* Total size of the database file */
49706
49707   assert( sqlite3_mutex_held(pBt->mutex) );
49708   pPage1 = pBt->pPage1;
49709   mxPage = btreePagecount(pBt);
49710   n = get4byte(&pPage1->aData[36]);
49711   testcase( n==mxPage-1 );
49712   if( n>=mxPage ){
49713     return SQLITE_CORRUPT_BKPT;
49714   }
49715   if( n>0 ){
49716     /* There are pages on the freelist.  Reuse one of those pages. */
49717     Pgno iTrunk;
49718     u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
49719     
49720     /* If the 'exact' parameter was true and a query of the pointer-map
49721     ** shows that the page 'nearby' is somewhere on the free-list, then
49722     ** the entire-list will be searched for that page.
49723     */
49724 #ifndef SQLITE_OMIT_AUTOVACUUM
49725     if( exact && nearby<=mxPage ){
49726       u8 eType;
49727       assert( nearby>0 );
49728       assert( pBt->autoVacuum );
49729       rc = ptrmapGet(pBt, nearby, &eType, 0);
49730       if( rc ) return rc;
49731       if( eType==PTRMAP_FREEPAGE ){
49732         searchList = 1;
49733       }
49734       *pPgno = nearby;
49735     }
49736 #endif
49737
49738     /* Decrement the free-list count by 1. Set iTrunk to the index of the
49739     ** first free-list trunk page. iPrevTrunk is initially 1.
49740     */
49741     rc = sqlite3PagerWrite(pPage1->pDbPage);
49742     if( rc ) return rc;
49743     put4byte(&pPage1->aData[36], n-1);
49744
49745     /* The code within this loop is run only once if the 'searchList' variable
49746     ** is not true. Otherwise, it runs once for each trunk-page on the
49747     ** free-list until the page 'nearby' is located.
49748     */
49749     do {
49750       pPrevTrunk = pTrunk;
49751       if( pPrevTrunk ){
49752         iTrunk = get4byte(&pPrevTrunk->aData[0]);
49753       }else{
49754         iTrunk = get4byte(&pPage1->aData[32]);
49755       }
49756       testcase( iTrunk==mxPage );
49757       if( iTrunk>mxPage ){
49758         rc = SQLITE_CORRUPT_BKPT;
49759       }else{
49760         rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
49761       }
49762       if( rc ){
49763         pTrunk = 0;
49764         goto end_allocate_page;
49765       }
49766
49767       k = get4byte(&pTrunk->aData[4]);
49768       if( k==0 && !searchList ){
49769         /* The trunk has no leaves and the list is not being searched. 
49770         ** So extract the trunk page itself and use it as the newly 
49771         ** allocated page */
49772         assert( pPrevTrunk==0 );
49773         rc = sqlite3PagerWrite(pTrunk->pDbPage);
49774         if( rc ){
49775           goto end_allocate_page;
49776         }
49777         *pPgno = iTrunk;
49778         memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
49779         *ppPage = pTrunk;
49780         pTrunk = 0;
49781         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
49782       }else if( k>(u32)(pBt->usableSize/4 - 2) ){
49783         /* Value of k is out of range.  Database corruption */
49784         rc = SQLITE_CORRUPT_BKPT;
49785         goto end_allocate_page;
49786 #ifndef SQLITE_OMIT_AUTOVACUUM
49787       }else if( searchList && nearby==iTrunk ){
49788         /* The list is being searched and this trunk page is the page
49789         ** to allocate, regardless of whether it has leaves.
49790         */
49791         assert( *pPgno==iTrunk );
49792         *ppPage = pTrunk;
49793         searchList = 0;
49794         rc = sqlite3PagerWrite(pTrunk->pDbPage);
49795         if( rc ){
49796           goto end_allocate_page;
49797         }
49798         if( k==0 ){
49799           if( !pPrevTrunk ){
49800             memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
49801           }else{
49802             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
49803             if( rc!=SQLITE_OK ){
49804               goto end_allocate_page;
49805             }
49806             memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
49807           }
49808         }else{
49809           /* The trunk page is required by the caller but it contains 
49810           ** pointers to free-list leaves. The first leaf becomes a trunk
49811           ** page in this case.
49812           */
49813           MemPage *pNewTrunk;
49814           Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
49815           if( iNewTrunk>mxPage ){ 
49816             rc = SQLITE_CORRUPT_BKPT;
49817             goto end_allocate_page;
49818           }
49819           testcase( iNewTrunk==mxPage );
49820           rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
49821           if( rc!=SQLITE_OK ){
49822             goto end_allocate_page;
49823           }
49824           rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
49825           if( rc!=SQLITE_OK ){
49826             releasePage(pNewTrunk);
49827             goto end_allocate_page;
49828           }
49829           memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
49830           put4byte(&pNewTrunk->aData[4], k-1);
49831           memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
49832           releasePage(pNewTrunk);
49833           if( !pPrevTrunk ){
49834             assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
49835             put4byte(&pPage1->aData[32], iNewTrunk);
49836           }else{
49837             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
49838             if( rc ){
49839               goto end_allocate_page;
49840             }
49841             put4byte(&pPrevTrunk->aData[0], iNewTrunk);
49842           }
49843         }
49844         pTrunk = 0;
49845         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
49846 #endif
49847       }else if( k>0 ){
49848         /* Extract a leaf from the trunk */
49849         u32 closest;
49850         Pgno iPage;
49851         unsigned char *aData = pTrunk->aData;
49852         rc = sqlite3PagerWrite(pTrunk->pDbPage);
49853         if( rc ){
49854           goto end_allocate_page;
49855         }
49856         if( nearby>0 ){
49857           u32 i;
49858           int dist;
49859           closest = 0;
49860           dist = get4byte(&aData[8]) - nearby;
49861           if( dist<0 ) dist = -dist;
49862           for(i=1; i<k; i++){
49863             int d2 = get4byte(&aData[8+i*4]) - nearby;
49864             if( d2<0 ) d2 = -d2;
49865             if( d2<dist ){
49866               closest = i;
49867               dist = d2;
49868             }
49869           }
49870         }else{
49871           closest = 0;
49872         }
49873
49874         iPage = get4byte(&aData[8+closest*4]);
49875         testcase( iPage==mxPage );
49876         if( iPage>mxPage ){
49877           rc = SQLITE_CORRUPT_BKPT;
49878           goto end_allocate_page;
49879         }
49880         testcase( iPage==mxPage );
49881         if( !searchList || iPage==nearby ){
49882           int noContent;
49883           *pPgno = iPage;
49884           TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
49885                  ": %d more free pages\n",
49886                  *pPgno, closest+1, k, pTrunk->pgno, n-1));
49887           if( closest<k-1 ){
49888             memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
49889           }
49890           put4byte(&aData[4], k-1);
49891           assert( sqlite3PagerIswriteable(pTrunk->pDbPage) );
49892           noContent = !btreeGetHasContent(pBt, *pPgno);
49893           rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
49894           if( rc==SQLITE_OK ){
49895             rc = sqlite3PagerWrite((*ppPage)->pDbPage);
49896             if( rc!=SQLITE_OK ){
49897               releasePage(*ppPage);
49898             }
49899           }
49900           searchList = 0;
49901         }
49902       }
49903       releasePage(pPrevTrunk);
49904       pPrevTrunk = 0;
49905     }while( searchList );
49906   }else{
49907     /* There are no pages on the freelist, so create a new page at the
49908     ** end of the file */
49909     rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
49910     if( rc ) return rc;
49911     pBt->nPage++;
49912     if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
49913
49914 #ifndef SQLITE_OMIT_AUTOVACUUM
49915     if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
49916       /* If *pPgno refers to a pointer-map page, allocate two new pages
49917       ** at the end of the file instead of one. The first allocated page
49918       ** becomes a new pointer-map page, the second is used by the caller.
49919       */
49920       MemPage *pPg = 0;
49921       TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
49922       assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
49923       rc = btreeGetPage(pBt, pBt->nPage, &pPg, 1);
49924       if( rc==SQLITE_OK ){
49925         rc = sqlite3PagerWrite(pPg->pDbPage);
49926         releasePage(pPg);
49927       }
49928       if( rc ) return rc;
49929       pBt->nPage++;
49930       if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
49931     }
49932 #endif
49933     put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
49934     *pPgno = pBt->nPage;
49935
49936     assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
49937     rc = btreeGetPage(pBt, *pPgno, ppPage, 1);
49938     if( rc ) return rc;
49939     rc = sqlite3PagerWrite((*ppPage)->pDbPage);
49940     if( rc!=SQLITE_OK ){
49941       releasePage(*ppPage);
49942     }
49943     TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
49944   }
49945
49946   assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
49947
49948 end_allocate_page:
49949   releasePage(pTrunk);
49950   releasePage(pPrevTrunk);
49951   if( rc==SQLITE_OK ){
49952     if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
49953       releasePage(*ppPage);
49954       return SQLITE_CORRUPT_BKPT;
49955     }
49956     (*ppPage)->isInit = 0;
49957   }else{
49958     *ppPage = 0;
49959   }
49960   return rc;
49961 }
49962
49963 /*
49964 ** This function is used to add page iPage to the database file free-list. 
49965 ** It is assumed that the page is not already a part of the free-list.
49966 **
49967 ** The value passed as the second argument to this function is optional.
49968 ** If the caller happens to have a pointer to the MemPage object 
49969 ** corresponding to page iPage handy, it may pass it as the second value. 
49970 ** Otherwise, it may pass NULL.
49971 **
49972 ** If a pointer to a MemPage object is passed as the second argument,
49973 ** its reference count is not altered by this function.
49974 */
49975 static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
49976   MemPage *pTrunk = 0;                /* Free-list trunk page */
49977   Pgno iTrunk = 0;                    /* Page number of free-list trunk page */ 
49978   MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */
49979   MemPage *pPage;                     /* Page being freed. May be NULL. */
49980   int rc;                             /* Return Code */
49981   int nFree;                          /* Initial number of pages on free-list */
49982
49983   assert( sqlite3_mutex_held(pBt->mutex) );
49984   assert( iPage>1 );
49985   assert( !pMemPage || pMemPage->pgno==iPage );
49986
49987   if( pMemPage ){
49988     pPage = pMemPage;
49989     sqlite3PagerRef(pPage->pDbPage);
49990   }else{
49991     pPage = btreePageLookup(pBt, iPage);
49992   }
49993
49994   /* Increment the free page count on pPage1 */
49995   rc = sqlite3PagerWrite(pPage1->pDbPage);
49996   if( rc ) goto freepage_out;
49997   nFree = get4byte(&pPage1->aData[36]);
49998   put4byte(&pPage1->aData[36], nFree+1);
49999
50000   if( pBt->secureDelete ){
50001     /* If the secure_delete option is enabled, then
50002     ** always fully overwrite deleted information with zeros.
50003     */
50004     if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
50005      ||            ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
50006     ){
50007       goto freepage_out;
50008     }
50009     memset(pPage->aData, 0, pPage->pBt->pageSize);
50010   }
50011
50012   /* If the database supports auto-vacuum, write an entry in the pointer-map
50013   ** to indicate that the page is free.
50014   */
50015   if( ISAUTOVACUUM ){
50016     ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
50017     if( rc ) goto freepage_out;
50018   }
50019
50020   /* Now manipulate the actual database free-list structure. There are two
50021   ** possibilities. If the free-list is currently empty, or if the first
50022   ** trunk page in the free-list is full, then this page will become a
50023   ** new free-list trunk page. Otherwise, it will become a leaf of the
50024   ** first trunk page in the current free-list. This block tests if it
50025   ** is possible to add the page as a new free-list leaf.
50026   */
50027   if( nFree!=0 ){
50028     u32 nLeaf;                /* Initial number of leaf cells on trunk page */
50029
50030     iTrunk = get4byte(&pPage1->aData[32]);
50031     rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
50032     if( rc!=SQLITE_OK ){
50033       goto freepage_out;
50034     }
50035
50036     nLeaf = get4byte(&pTrunk->aData[4]);
50037     assert( pBt->usableSize>32 );
50038     if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
50039       rc = SQLITE_CORRUPT_BKPT;
50040       goto freepage_out;
50041     }
50042     if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
50043       /* In this case there is room on the trunk page to insert the page
50044       ** being freed as a new leaf.
50045       **
50046       ** Note that the trunk page is not really full until it contains
50047       ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
50048       ** coded.  But due to a coding error in versions of SQLite prior to
50049       ** 3.6.0, databases with freelist trunk pages holding more than
50050       ** usableSize/4 - 8 entries will be reported as corrupt.  In order
50051       ** to maintain backwards compatibility with older versions of SQLite,
50052       ** we will continue to restrict the number of entries to usableSize/4 - 8
50053       ** for now.  At some point in the future (once everyone has upgraded
50054       ** to 3.6.0 or later) we should consider fixing the conditional above
50055       ** to read "usableSize/4-2" instead of "usableSize/4-8".
50056       */
50057       rc = sqlite3PagerWrite(pTrunk->pDbPage);
50058       if( rc==SQLITE_OK ){
50059         put4byte(&pTrunk->aData[4], nLeaf+1);
50060         put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
50061         if( pPage && !pBt->secureDelete ){
50062           sqlite3PagerDontWrite(pPage->pDbPage);
50063         }
50064         rc = btreeSetHasContent(pBt, iPage);
50065       }
50066       TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
50067       goto freepage_out;
50068     }
50069   }
50070
50071   /* If control flows to this point, then it was not possible to add the
50072   ** the page being freed as a leaf page of the first trunk in the free-list.
50073   ** Possibly because the free-list is empty, or possibly because the 
50074   ** first trunk in the free-list is full. Either way, the page being freed
50075   ** will become the new first trunk page in the free-list.
50076   */
50077   if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
50078     goto freepage_out;
50079   }
50080   rc = sqlite3PagerWrite(pPage->pDbPage);
50081   if( rc!=SQLITE_OK ){
50082     goto freepage_out;
50083   }
50084   put4byte(pPage->aData, iTrunk);
50085   put4byte(&pPage->aData[4], 0);
50086   put4byte(&pPage1->aData[32], iPage);
50087   TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
50088
50089 freepage_out:
50090   if( pPage ){
50091     pPage->isInit = 0;
50092   }
50093   releasePage(pPage);
50094   releasePage(pTrunk);
50095   return rc;
50096 }
50097 static void freePage(MemPage *pPage, int *pRC){
50098   if( (*pRC)==SQLITE_OK ){
50099     *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
50100   }
50101 }
50102
50103 /*
50104 ** Free any overflow pages associated with the given Cell.
50105 */
50106 static int clearCell(MemPage *pPage, unsigned char *pCell){
50107   BtShared *pBt = pPage->pBt;
50108   CellInfo info;
50109   Pgno ovflPgno;
50110   int rc;
50111   int nOvfl;
50112   u32 ovflPageSize;
50113
50114   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50115   btreeParseCellPtr(pPage, pCell, &info);
50116   if( info.iOverflow==0 ){
50117     return SQLITE_OK;  /* No overflow pages. Return without doing anything */
50118   }
50119   ovflPgno = get4byte(&pCell[info.iOverflow]);
50120   assert( pBt->usableSize > 4 );
50121   ovflPageSize = pBt->usableSize - 4;
50122   nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
50123   assert( ovflPgno==0 || nOvfl>0 );
50124   while( nOvfl-- ){
50125     Pgno iNext = 0;
50126     MemPage *pOvfl = 0;
50127     if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
50128       /* 0 is not a legal page number and page 1 cannot be an 
50129       ** overflow page. Therefore if ovflPgno<2 or past the end of the 
50130       ** file the database must be corrupt. */
50131       return SQLITE_CORRUPT_BKPT;
50132     }
50133     if( nOvfl ){
50134       rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
50135       if( rc ) return rc;
50136     }
50137
50138     if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
50139      && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
50140     ){
50141       /* There is no reason any cursor should have an outstanding reference 
50142       ** to an overflow page belonging to a cell that is being deleted/updated.
50143       ** So if there exists more than one reference to this page, then it 
50144       ** must not really be an overflow page and the database must be corrupt. 
50145       ** It is helpful to detect this before calling freePage2(), as 
50146       ** freePage2() may zero the page contents if secure-delete mode is
50147       ** enabled. If this 'overflow' page happens to be a page that the
50148       ** caller is iterating through or using in some other way, this
50149       ** can be problematic.
50150       */
50151       rc = SQLITE_CORRUPT_BKPT;
50152     }else{
50153       rc = freePage2(pBt, pOvfl, ovflPgno);
50154     }
50155
50156     if( pOvfl ){
50157       sqlite3PagerUnref(pOvfl->pDbPage);
50158     }
50159     if( rc ) return rc;
50160     ovflPgno = iNext;
50161   }
50162   return SQLITE_OK;
50163 }
50164
50165 /*
50166 ** Create the byte sequence used to represent a cell on page pPage
50167 ** and write that byte sequence into pCell[].  Overflow pages are
50168 ** allocated and filled in as necessary.  The calling procedure
50169 ** is responsible for making sure sufficient space has been allocated
50170 ** for pCell[].
50171 **
50172 ** Note that pCell does not necessary need to point to the pPage->aData
50173 ** area.  pCell might point to some temporary storage.  The cell will
50174 ** be constructed in this temporary area then copied into pPage->aData
50175 ** later.
50176 */
50177 static int fillInCell(
50178   MemPage *pPage,                /* The page that contains the cell */
50179   unsigned char *pCell,          /* Complete text of the cell */
50180   const void *pKey, i64 nKey,    /* The key */
50181   const void *pData,int nData,   /* The data */
50182   int nZero,                     /* Extra zero bytes to append to pData */
50183   int *pnSize                    /* Write cell size here */
50184 ){
50185   int nPayload;
50186   const u8 *pSrc;
50187   int nSrc, n, rc;
50188   int spaceLeft;
50189   MemPage *pOvfl = 0;
50190   MemPage *pToRelease = 0;
50191   unsigned char *pPrior;
50192   unsigned char *pPayload;
50193   BtShared *pBt = pPage->pBt;
50194   Pgno pgnoOvfl = 0;
50195   int nHeader;
50196   CellInfo info;
50197
50198   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50199
50200   /* pPage is not necessarily writeable since pCell might be auxiliary
50201   ** buffer space that is separate from the pPage buffer area */
50202   assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
50203             || sqlite3PagerIswriteable(pPage->pDbPage) );
50204
50205   /* Fill in the header. */
50206   nHeader = 0;
50207   if( !pPage->leaf ){
50208     nHeader += 4;
50209   }
50210   if( pPage->hasData ){
50211     nHeader += putVarint(&pCell[nHeader], nData+nZero);
50212   }else{
50213     nData = nZero = 0;
50214   }
50215   nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
50216   btreeParseCellPtr(pPage, pCell, &info);
50217   assert( info.nHeader==nHeader );
50218   assert( info.nKey==nKey );
50219   assert( info.nData==(u32)(nData+nZero) );
50220   
50221   /* Fill in the payload */
50222   nPayload = nData + nZero;
50223   if( pPage->intKey ){
50224     pSrc = pData;
50225     nSrc = nData;
50226     nData = 0;
50227   }else{ 
50228     if( NEVER(nKey>0x7fffffff || pKey==0) ){
50229       return SQLITE_CORRUPT_BKPT;
50230     }
50231     nPayload += (int)nKey;
50232     pSrc = pKey;
50233     nSrc = (int)nKey;
50234   }
50235   *pnSize = info.nSize;
50236   spaceLeft = info.nLocal;
50237   pPayload = &pCell[nHeader];
50238   pPrior = &pCell[info.iOverflow];
50239
50240   while( nPayload>0 ){
50241     if( spaceLeft==0 ){
50242 #ifndef SQLITE_OMIT_AUTOVACUUM
50243       Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
50244       if( pBt->autoVacuum ){
50245         do{
50246           pgnoOvfl++;
50247         } while( 
50248           PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt) 
50249         );
50250       }
50251 #endif
50252       rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
50253 #ifndef SQLITE_OMIT_AUTOVACUUM
50254       /* If the database supports auto-vacuum, and the second or subsequent
50255       ** overflow page is being allocated, add an entry to the pointer-map
50256       ** for that page now. 
50257       **
50258       ** If this is the first overflow page, then write a partial entry 
50259       ** to the pointer-map. If we write nothing to this pointer-map slot,
50260       ** then the optimistic overflow chain processing in clearCell()
50261       ** may misinterpret the uninitialised values and delete the
50262       ** wrong pages from the database.
50263       */
50264       if( pBt->autoVacuum && rc==SQLITE_OK ){
50265         u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
50266         ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
50267         if( rc ){
50268           releasePage(pOvfl);
50269         }
50270       }
50271 #endif
50272       if( rc ){
50273         releasePage(pToRelease);
50274         return rc;
50275       }
50276
50277       /* If pToRelease is not zero than pPrior points into the data area
50278       ** of pToRelease.  Make sure pToRelease is still writeable. */
50279       assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
50280
50281       /* If pPrior is part of the data area of pPage, then make sure pPage
50282       ** is still writeable */
50283       assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
50284             || sqlite3PagerIswriteable(pPage->pDbPage) );
50285
50286       put4byte(pPrior, pgnoOvfl);
50287       releasePage(pToRelease);
50288       pToRelease = pOvfl;
50289       pPrior = pOvfl->aData;
50290       put4byte(pPrior, 0);
50291       pPayload = &pOvfl->aData[4];
50292       spaceLeft = pBt->usableSize - 4;
50293     }
50294     n = nPayload;
50295     if( n>spaceLeft ) n = spaceLeft;
50296
50297     /* If pToRelease is not zero than pPayload points into the data area
50298     ** of pToRelease.  Make sure pToRelease is still writeable. */
50299     assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
50300
50301     /* If pPayload is part of the data area of pPage, then make sure pPage
50302     ** is still writeable */
50303     assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
50304             || sqlite3PagerIswriteable(pPage->pDbPage) );
50305
50306     if( nSrc>0 ){
50307       if( n>nSrc ) n = nSrc;
50308       assert( pSrc );
50309       memcpy(pPayload, pSrc, n);
50310     }else{
50311       memset(pPayload, 0, n);
50312     }
50313     nPayload -= n;
50314     pPayload += n;
50315     pSrc += n;
50316     nSrc -= n;
50317     spaceLeft -= n;
50318     if( nSrc==0 ){
50319       nSrc = nData;
50320       pSrc = pData;
50321     }
50322   }
50323   releasePage(pToRelease);
50324   return SQLITE_OK;
50325 }
50326
50327 /*
50328 ** Remove the i-th cell from pPage.  This routine effects pPage only.
50329 ** The cell content is not freed or deallocated.  It is assumed that
50330 ** the cell content has been copied someplace else.  This routine just
50331 ** removes the reference to the cell from pPage.
50332 **
50333 ** "sz" must be the number of bytes in the cell.
50334 */
50335 static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
50336   int i;          /* Loop counter */
50337   u32 pc;         /* Offset to cell content of cell being deleted */
50338   u8 *data;       /* pPage->aData */
50339   u8 *ptr;        /* Used to move bytes around within data[] */
50340   int rc;         /* The return code */
50341   int hdr;        /* Beginning of the header.  0 most pages.  100 page 1 */
50342
50343   if( *pRC ) return;
50344
50345   assert( idx>=0 && idx<pPage->nCell );
50346   assert( sz==cellSize(pPage, idx) );
50347   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
50348   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50349   data = pPage->aData;
50350   ptr = &data[pPage->cellOffset + 2*idx];
50351   pc = get2byte(ptr);
50352   hdr = pPage->hdrOffset;
50353   testcase( pc==get2byte(&data[hdr+5]) );
50354   testcase( pc+sz==pPage->pBt->usableSize );
50355   if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
50356     *pRC = SQLITE_CORRUPT_BKPT;
50357     return;
50358   }
50359   rc = freeSpace(pPage, pc, sz);
50360   if( rc ){
50361     *pRC = rc;
50362     return;
50363   }
50364   for(i=idx+1; i<pPage->nCell; i++, ptr+=2){
50365     ptr[0] = ptr[2];
50366     ptr[1] = ptr[3];
50367   }
50368   pPage->nCell--;
50369   put2byte(&data[hdr+3], pPage->nCell);
50370   pPage->nFree += 2;
50371 }
50372
50373 /*
50374 ** Insert a new cell on pPage at cell index "i".  pCell points to the
50375 ** content of the cell.
50376 **
50377 ** If the cell content will fit on the page, then put it there.  If it
50378 ** will not fit, then make a copy of the cell content into pTemp if
50379 ** pTemp is not null.  Regardless of pTemp, allocate a new entry
50380 ** in pPage->aOvfl[] and make it point to the cell content (either
50381 ** in pTemp or the original pCell) and also record its index. 
50382 ** Allocating a new entry in pPage->aCell[] implies that 
50383 ** pPage->nOverflow is incremented.
50384 **
50385 ** If nSkip is non-zero, then do not copy the first nSkip bytes of the
50386 ** cell. The caller will overwrite them after this function returns. If
50387 ** nSkip is non-zero, then pCell may not point to an invalid memory location 
50388 ** (but pCell+nSkip is always valid).
50389 */
50390 static void insertCell(
50391   MemPage *pPage,   /* Page into which we are copying */
50392   int i,            /* New cell becomes the i-th cell of the page */
50393   u8 *pCell,        /* Content of the new cell */
50394   int sz,           /* Bytes of content in pCell */
50395   u8 *pTemp,        /* Temp storage space for pCell, if needed */
50396   Pgno iChild,      /* If non-zero, replace first 4 bytes with this value */
50397   int *pRC          /* Read and write return code from here */
50398 ){
50399   int idx = 0;      /* Where to write new cell content in data[] */
50400   int j;            /* Loop counter */
50401   int end;          /* First byte past the last cell pointer in data[] */
50402   int ins;          /* Index in data[] where new cell pointer is inserted */
50403   int cellOffset;   /* Address of first cell pointer in data[] */
50404   u8 *data;         /* The content of the whole page */
50405   u8 *ptr;          /* Used for moving information around in data[] */
50406
50407   int nSkip = (iChild ? 4 : 0);
50408
50409   if( *pRC ) return;
50410
50411   assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
50412   assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=10921 );
50413   assert( pPage->nOverflow<=ArraySize(pPage->aOvfl) );
50414   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50415   /* The cell should normally be sized correctly.  However, when moving a
50416   ** malformed cell from a leaf page to an interior page, if the cell size
50417   ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
50418   ** might be less than 8 (leaf-size + pointer) on the interior node.  Hence
50419   ** the term after the || in the following assert(). */
50420   assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
50421   if( pPage->nOverflow || sz+2>pPage->nFree ){
50422     if( pTemp ){
50423       memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
50424       pCell = pTemp;
50425     }
50426     if( iChild ){
50427       put4byte(pCell, iChild);
50428     }
50429     j = pPage->nOverflow++;
50430     assert( j<(int)(sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0])) );
50431     pPage->aOvfl[j].pCell = pCell;
50432     pPage->aOvfl[j].idx = (u16)i;
50433   }else{
50434     int rc = sqlite3PagerWrite(pPage->pDbPage);
50435     if( rc!=SQLITE_OK ){
50436       *pRC = rc;
50437       return;
50438     }
50439     assert( sqlite3PagerIswriteable(pPage->pDbPage) );
50440     data = pPage->aData;
50441     cellOffset = pPage->cellOffset;
50442     end = cellOffset + 2*pPage->nCell;
50443     ins = cellOffset + 2*i;
50444     rc = allocateSpace(pPage, sz, &idx);
50445     if( rc ){ *pRC = rc; return; }
50446     /* The allocateSpace() routine guarantees the following two properties
50447     ** if it returns success */
50448     assert( idx >= end+2 );
50449     assert( idx+sz <= pPage->pBt->usableSize );
50450     pPage->nCell++;
50451     pPage->nFree -= (u16)(2 + sz);
50452     memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
50453     if( iChild ){
50454       put4byte(&data[idx], iChild);
50455     }
50456     for(j=end, ptr=&data[j]; j>ins; j-=2, ptr-=2){
50457       ptr[0] = ptr[-2];
50458       ptr[1] = ptr[-1];
50459     }
50460     put2byte(&data[ins], idx);
50461     put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
50462 #ifndef SQLITE_OMIT_AUTOVACUUM
50463     if( pPage->pBt->autoVacuum ){
50464       /* The cell may contain a pointer to an overflow page. If so, write
50465       ** the entry for the overflow page into the pointer map.
50466       */
50467       ptrmapPutOvflPtr(pPage, pCell, pRC);
50468     }
50469 #endif
50470   }
50471 }
50472
50473 /*
50474 ** Add a list of cells to a page.  The page should be initially empty.
50475 ** The cells are guaranteed to fit on the page.
50476 */
50477 static void assemblePage(
50478   MemPage *pPage,   /* The page to be assemblied */
50479   int nCell,        /* The number of cells to add to this page */
50480   u8 **apCell,      /* Pointers to cell bodies */
50481   u16 *aSize        /* Sizes of the cells */
50482 ){
50483   int i;            /* Loop counter */
50484   u8 *pCellptr;     /* Address of next cell pointer */
50485   int cellbody;     /* Address of next cell body */
50486   u8 * const data = pPage->aData;             /* Pointer to data for pPage */
50487   const int hdr = pPage->hdrOffset;           /* Offset of header on pPage */
50488   const int nUsable = pPage->pBt->usableSize; /* Usable size of page */
50489
50490   assert( pPage->nOverflow==0 );
50491   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50492   assert( nCell>=0 && nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=10921);
50493   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
50494
50495   /* Check that the page has just been zeroed by zeroPage() */
50496   assert( pPage->nCell==0 );
50497   assert( get2byteNotZero(&data[hdr+5])==nUsable );
50498
50499   pCellptr = &data[pPage->cellOffset + nCell*2];
50500   cellbody = nUsable;
50501   for(i=nCell-1; i>=0; i--){
50502     pCellptr -= 2;
50503     cellbody -= aSize[i];
50504     put2byte(pCellptr, cellbody);
50505     memcpy(&data[cellbody], apCell[i], aSize[i]);
50506   }
50507   put2byte(&data[hdr+3], nCell);
50508   put2byte(&data[hdr+5], cellbody);
50509   pPage->nFree -= (nCell*2 + nUsable - cellbody);
50510   pPage->nCell = (u16)nCell;
50511 }
50512
50513 /*
50514 ** The following parameters determine how many adjacent pages get involved
50515 ** in a balancing operation.  NN is the number of neighbors on either side
50516 ** of the page that participate in the balancing operation.  NB is the
50517 ** total number of pages that participate, including the target page and
50518 ** NN neighbors on either side.
50519 **
50520 ** The minimum value of NN is 1 (of course).  Increasing NN above 1
50521 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
50522 ** in exchange for a larger degradation in INSERT and UPDATE performance.
50523 ** The value of NN appears to give the best results overall.
50524 */
50525 #define NN 1             /* Number of neighbors on either side of pPage */
50526 #define NB (NN*2+1)      /* Total pages involved in the balance */
50527
50528
50529 #ifndef SQLITE_OMIT_QUICKBALANCE
50530 /*
50531 ** This version of balance() handles the common special case where
50532 ** a new entry is being inserted on the extreme right-end of the
50533 ** tree, in other words, when the new entry will become the largest
50534 ** entry in the tree.
50535 **
50536 ** Instead of trying to balance the 3 right-most leaf pages, just add
50537 ** a new page to the right-hand side and put the one new entry in
50538 ** that page.  This leaves the right side of the tree somewhat
50539 ** unbalanced.  But odds are that we will be inserting new entries
50540 ** at the end soon afterwards so the nearly empty page will quickly
50541 ** fill up.  On average.
50542 **
50543 ** pPage is the leaf page which is the right-most page in the tree.
50544 ** pParent is its parent.  pPage must have a single overflow entry
50545 ** which is also the right-most entry on the page.
50546 **
50547 ** The pSpace buffer is used to store a temporary copy of the divider
50548 ** cell that will be inserted into pParent. Such a cell consists of a 4
50549 ** byte page number followed by a variable length integer. In other
50550 ** words, at most 13 bytes. Hence the pSpace buffer must be at
50551 ** least 13 bytes in size.
50552 */
50553 static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
50554   BtShared *const pBt = pPage->pBt;    /* B-Tree Database */
50555   MemPage *pNew;                       /* Newly allocated page */
50556   int rc;                              /* Return Code */
50557   Pgno pgnoNew;                        /* Page number of pNew */
50558
50559   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50560   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
50561   assert( pPage->nOverflow==1 );
50562
50563   /* This error condition is now caught prior to reaching this function */
50564   if( pPage->nCell<=0 ) return SQLITE_CORRUPT_BKPT;
50565
50566   /* Allocate a new page. This page will become the right-sibling of 
50567   ** pPage. Make the parent page writable, so that the new divider cell
50568   ** may be inserted. If both these operations are successful, proceed.
50569   */
50570   rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
50571
50572   if( rc==SQLITE_OK ){
50573
50574     u8 *pOut = &pSpace[4];
50575     u8 *pCell = pPage->aOvfl[0].pCell;
50576     u16 szCell = cellSizePtr(pPage, pCell);
50577     u8 *pStop;
50578
50579     assert( sqlite3PagerIswriteable(pNew->pDbPage) );
50580     assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
50581     zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
50582     assemblePage(pNew, 1, &pCell, &szCell);
50583
50584     /* If this is an auto-vacuum database, update the pointer map
50585     ** with entries for the new page, and any pointer from the 
50586     ** cell on the page to an overflow page. If either of these
50587     ** operations fails, the return code is set, but the contents
50588     ** of the parent page are still manipulated by thh code below.
50589     ** That is Ok, at this point the parent page is guaranteed to
50590     ** be marked as dirty. Returning an error code will cause a
50591     ** rollback, undoing any changes made to the parent page.
50592     */
50593     if( ISAUTOVACUUM ){
50594       ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
50595       if( szCell>pNew->minLocal ){
50596         ptrmapPutOvflPtr(pNew, pCell, &rc);
50597       }
50598     }
50599   
50600     /* Create a divider cell to insert into pParent. The divider cell
50601     ** consists of a 4-byte page number (the page number of pPage) and
50602     ** a variable length key value (which must be the same value as the
50603     ** largest key on pPage).
50604     **
50605     ** To find the largest key value on pPage, first find the right-most 
50606     ** cell on pPage. The first two fields of this cell are the 
50607     ** record-length (a variable length integer at most 32-bits in size)
50608     ** and the key value (a variable length integer, may have any value).
50609     ** The first of the while(...) loops below skips over the record-length
50610     ** field. The second while(...) loop copies the key value from the
50611     ** cell on pPage into the pSpace buffer.
50612     */
50613     pCell = findCell(pPage, pPage->nCell-1);
50614     pStop = &pCell[9];
50615     while( (*(pCell++)&0x80) && pCell<pStop );
50616     pStop = &pCell[9];
50617     while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
50618
50619     /* Insert the new divider cell into pParent. */
50620     insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
50621                0, pPage->pgno, &rc);
50622
50623     /* Set the right-child pointer of pParent to point to the new page. */
50624     put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
50625   
50626     /* Release the reference to the new page. */
50627     releasePage(pNew);
50628   }
50629
50630   return rc;
50631 }
50632 #endif /* SQLITE_OMIT_QUICKBALANCE */
50633
50634 #if 0
50635 /*
50636 ** This function does not contribute anything to the operation of SQLite.
50637 ** it is sometimes activated temporarily while debugging code responsible 
50638 ** for setting pointer-map entries.
50639 */
50640 static int ptrmapCheckPages(MemPage **apPage, int nPage){
50641   int i, j;
50642   for(i=0; i<nPage; i++){
50643     Pgno n;
50644     u8 e;
50645     MemPage *pPage = apPage[i];
50646     BtShared *pBt = pPage->pBt;
50647     assert( pPage->isInit );
50648
50649     for(j=0; j<pPage->nCell; j++){
50650       CellInfo info;
50651       u8 *z;
50652      
50653       z = findCell(pPage, j);
50654       btreeParseCellPtr(pPage, z, &info);
50655       if( info.iOverflow ){
50656         Pgno ovfl = get4byte(&z[info.iOverflow]);
50657         ptrmapGet(pBt, ovfl, &e, &n);
50658         assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
50659       }
50660       if( !pPage->leaf ){
50661         Pgno child = get4byte(z);
50662         ptrmapGet(pBt, child, &e, &n);
50663         assert( n==pPage->pgno && e==PTRMAP_BTREE );
50664       }
50665     }
50666     if( !pPage->leaf ){
50667       Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
50668       ptrmapGet(pBt, child, &e, &n);
50669       assert( n==pPage->pgno && e==PTRMAP_BTREE );
50670     }
50671   }
50672   return 1;
50673 }
50674 #endif
50675
50676 /*
50677 ** This function is used to copy the contents of the b-tree node stored 
50678 ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
50679 ** the pointer-map entries for each child page are updated so that the
50680 ** parent page stored in the pointer map is page pTo. If pFrom contained
50681 ** any cells with overflow page pointers, then the corresponding pointer
50682 ** map entries are also updated so that the parent page is page pTo.
50683 **
50684 ** If pFrom is currently carrying any overflow cells (entries in the
50685 ** MemPage.aOvfl[] array), they are not copied to pTo. 
50686 **
50687 ** Before returning, page pTo is reinitialized using btreeInitPage().
50688 **
50689 ** The performance of this function is not critical. It is only used by 
50690 ** the balance_shallower() and balance_deeper() procedures, neither of
50691 ** which are called often under normal circumstances.
50692 */
50693 static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
50694   if( (*pRC)==SQLITE_OK ){
50695     BtShared * const pBt = pFrom->pBt;
50696     u8 * const aFrom = pFrom->aData;
50697     u8 * const aTo = pTo->aData;
50698     int const iFromHdr = pFrom->hdrOffset;
50699     int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
50700     int rc;
50701     int iData;
50702   
50703   
50704     assert( pFrom->isInit );
50705     assert( pFrom->nFree>=iToHdr );
50706     assert( get2byte(&aFrom[iFromHdr+5])<=pBt->usableSize );
50707   
50708     /* Copy the b-tree node content from page pFrom to page pTo. */
50709     iData = get2byte(&aFrom[iFromHdr+5]);
50710     memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
50711     memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
50712   
50713     /* Reinitialize page pTo so that the contents of the MemPage structure
50714     ** match the new data. The initialization of pTo can actually fail under
50715     ** fairly obscure circumstances, even though it is a copy of initialized 
50716     ** page pFrom.
50717     */
50718     pTo->isInit = 0;
50719     rc = btreeInitPage(pTo);
50720     if( rc!=SQLITE_OK ){
50721       *pRC = rc;
50722       return;
50723     }
50724   
50725     /* If this is an auto-vacuum database, update the pointer-map entries
50726     ** for any b-tree or overflow pages that pTo now contains the pointers to.
50727     */
50728     if( ISAUTOVACUUM ){
50729       *pRC = setChildPtrmaps(pTo);
50730     }
50731   }
50732 }
50733
50734 /*
50735 ** This routine redistributes cells on the iParentIdx'th child of pParent
50736 ** (hereafter "the page") and up to 2 siblings so that all pages have about the
50737 ** same amount of free space. Usually a single sibling on either side of the
50738 ** page are used in the balancing, though both siblings might come from one
50739 ** side if the page is the first or last child of its parent. If the page 
50740 ** has fewer than 2 siblings (something which can only happen if the page
50741 ** is a root page or a child of a root page) then all available siblings
50742 ** participate in the balancing.
50743 **
50744 ** The number of siblings of the page might be increased or decreased by 
50745 ** one or two in an effort to keep pages nearly full but not over full. 
50746 **
50747 ** Note that when this routine is called, some of the cells on the page
50748 ** might not actually be stored in MemPage.aData[]. This can happen
50749 ** if the page is overfull. This routine ensures that all cells allocated
50750 ** to the page and its siblings fit into MemPage.aData[] before returning.
50751 **
50752 ** In the course of balancing the page and its siblings, cells may be
50753 ** inserted into or removed from the parent page (pParent). Doing so
50754 ** may cause the parent page to become overfull or underfull. If this
50755 ** happens, it is the responsibility of the caller to invoke the correct
50756 ** balancing routine to fix this problem (see the balance() routine). 
50757 **
50758 ** If this routine fails for any reason, it might leave the database
50759 ** in a corrupted state. So if this routine fails, the database should
50760 ** be rolled back.
50761 **
50762 ** The third argument to this function, aOvflSpace, is a pointer to a
50763 ** buffer big enough to hold one page. If while inserting cells into the parent
50764 ** page (pParent) the parent page becomes overfull, this buffer is
50765 ** used to store the parent's overflow cells. Because this function inserts
50766 ** a maximum of four divider cells into the parent page, and the maximum
50767 ** size of a cell stored within an internal node is always less than 1/4
50768 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
50769 ** enough for all overflow cells.
50770 **
50771 ** If aOvflSpace is set to a null pointer, this function returns 
50772 ** SQLITE_NOMEM.
50773 */
50774 static int balance_nonroot(
50775   MemPage *pParent,               /* Parent page of siblings being balanced */
50776   int iParentIdx,                 /* Index of "the page" in pParent */
50777   u8 *aOvflSpace,                 /* page-size bytes of space for parent ovfl */
50778   int isRoot                      /* True if pParent is a root-page */
50779 ){
50780   BtShared *pBt;               /* The whole database */
50781   int nCell = 0;               /* Number of cells in apCell[] */
50782   int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
50783   int nNew = 0;                /* Number of pages in apNew[] */
50784   int nOld;                    /* Number of pages in apOld[] */
50785   int i, j, k;                 /* Loop counters */
50786   int nxDiv;                   /* Next divider slot in pParent->aCell[] */
50787   int rc = SQLITE_OK;          /* The return code */
50788   u16 leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
50789   int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
50790   int usableSpace;             /* Bytes in pPage beyond the header */
50791   int pageFlags;               /* Value of pPage->aData[0] */
50792   int subtotal;                /* Subtotal of bytes in cells on one page */
50793   int iSpace1 = 0;             /* First unused byte of aSpace1[] */
50794   int iOvflSpace = 0;          /* First unused byte of aOvflSpace[] */
50795   int szScratch;               /* Size of scratch memory requested */
50796   MemPage *apOld[NB];          /* pPage and up to two siblings */
50797   MemPage *apCopy[NB];         /* Private copies of apOld[] pages */
50798   MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
50799   u8 *pRight;                  /* Location in parent of right-sibling pointer */
50800   u8 *apDiv[NB-1];             /* Divider cells in pParent */
50801   int cntNew[NB+2];            /* Index in aCell[] of cell after i-th page */
50802   int szNew[NB+2];             /* Combined size of cells place on i-th page */
50803   u8 **apCell = 0;             /* All cells begin balanced */
50804   u16 *szCell;                 /* Local size of all cells in apCell[] */
50805   u8 *aSpace1;                 /* Space for copies of dividers cells */
50806   Pgno pgno;                   /* Temp var to store a page number in */
50807
50808   pBt = pParent->pBt;
50809   assert( sqlite3_mutex_held(pBt->mutex) );
50810   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
50811
50812 #if 0
50813   TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
50814 #endif
50815
50816   /* At this point pParent may have at most one overflow cell. And if
50817   ** this overflow cell is present, it must be the cell with 
50818   ** index iParentIdx. This scenario comes about when this function
50819   ** is called (indirectly) from sqlite3BtreeDelete().
50820   */
50821   assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
50822   assert( pParent->nOverflow==0 || pParent->aOvfl[0].idx==iParentIdx );
50823
50824   if( !aOvflSpace ){
50825     return SQLITE_NOMEM;
50826   }
50827
50828   /* Find the sibling pages to balance. Also locate the cells in pParent 
50829   ** that divide the siblings. An attempt is made to find NN siblings on 
50830   ** either side of pPage. More siblings are taken from one side, however, 
50831   ** if there are fewer than NN siblings on the other side. If pParent
50832   ** has NB or fewer children then all children of pParent are taken.  
50833   **
50834   ** This loop also drops the divider cells from the parent page. This
50835   ** way, the remainder of the function does not have to deal with any
50836   ** overflow cells in the parent page, since if any existed they will
50837   ** have already been removed.
50838   */
50839   i = pParent->nOverflow + pParent->nCell;
50840   if( i<2 ){
50841     nxDiv = 0;
50842     nOld = i+1;
50843   }else{
50844     nOld = 3;
50845     if( iParentIdx==0 ){                 
50846       nxDiv = 0;
50847     }else if( iParentIdx==i ){
50848       nxDiv = i-2;
50849     }else{
50850       nxDiv = iParentIdx-1;
50851     }
50852     i = 2;
50853   }
50854   if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
50855     pRight = &pParent->aData[pParent->hdrOffset+8];
50856   }else{
50857     pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
50858   }
50859   pgno = get4byte(pRight);
50860   while( 1 ){
50861     rc = getAndInitPage(pBt, pgno, &apOld[i]);
50862     if( rc ){
50863       memset(apOld, 0, (i+1)*sizeof(MemPage*));
50864       goto balance_cleanup;
50865     }
50866     nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
50867     if( (i--)==0 ) break;
50868
50869     if( i+nxDiv==pParent->aOvfl[0].idx && pParent->nOverflow ){
50870       apDiv[i] = pParent->aOvfl[0].pCell;
50871       pgno = get4byte(apDiv[i]);
50872       szNew[i] = cellSizePtr(pParent, apDiv[i]);
50873       pParent->nOverflow = 0;
50874     }else{
50875       apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
50876       pgno = get4byte(apDiv[i]);
50877       szNew[i] = cellSizePtr(pParent, apDiv[i]);
50878
50879       /* Drop the cell from the parent page. apDiv[i] still points to
50880       ** the cell within the parent, even though it has been dropped.
50881       ** This is safe because dropping a cell only overwrites the first
50882       ** four bytes of it, and this function does not need the first
50883       ** four bytes of the divider cell. So the pointer is safe to use
50884       ** later on.  
50885       **
50886       ** Unless SQLite is compiled in secure-delete mode. In this case,
50887       ** the dropCell() routine will overwrite the entire cell with zeroes.
50888       ** In this case, temporarily copy the cell into the aOvflSpace[]
50889       ** buffer. It will be copied out again as soon as the aSpace[] buffer
50890       ** is allocated.  */
50891       if( pBt->secureDelete ){
50892         int iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
50893         if( (iOff+szNew[i])>(int)pBt->usableSize ){
50894           rc = SQLITE_CORRUPT_BKPT;
50895           memset(apOld, 0, (i+1)*sizeof(MemPage*));
50896           goto balance_cleanup;
50897         }else{
50898           memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
50899           apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
50900         }
50901       }
50902       dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
50903     }
50904   }
50905
50906   /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
50907   ** alignment */
50908   nMaxCells = (nMaxCells + 3)&~3;
50909
50910   /*
50911   ** Allocate space for memory structures
50912   */
50913   k = pBt->pageSize + ROUND8(sizeof(MemPage));
50914   szScratch =
50915        nMaxCells*sizeof(u8*)                       /* apCell */
50916      + nMaxCells*sizeof(u16)                       /* szCell */
50917      + pBt->pageSize                               /* aSpace1 */
50918      + k*nOld;                                     /* Page copies (apCopy) */
50919   apCell = sqlite3ScratchMalloc( szScratch ); 
50920   if( apCell==0 ){
50921     rc = SQLITE_NOMEM;
50922     goto balance_cleanup;
50923   }
50924   szCell = (u16*)&apCell[nMaxCells];
50925   aSpace1 = (u8*)&szCell[nMaxCells];
50926   assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
50927
50928   /*
50929   ** Load pointers to all cells on sibling pages and the divider cells
50930   ** into the local apCell[] array.  Make copies of the divider cells
50931   ** into space obtained from aSpace1[] and remove the the divider Cells
50932   ** from pParent.
50933   **
50934   ** If the siblings are on leaf pages, then the child pointers of the
50935   ** divider cells are stripped from the cells before they are copied
50936   ** into aSpace1[].  In this way, all cells in apCell[] are without
50937   ** child pointers.  If siblings are not leaves, then all cell in
50938   ** apCell[] include child pointers.  Either way, all cells in apCell[]
50939   ** are alike.
50940   **
50941   ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
50942   **       leafData:  1 if pPage holds key+data and pParent holds only keys.
50943   */
50944   leafCorrection = apOld[0]->leaf*4;
50945   leafData = apOld[0]->hasData;
50946   for(i=0; i<nOld; i++){
50947     int limit;
50948     
50949     /* Before doing anything else, take a copy of the i'th original sibling
50950     ** The rest of this function will use data from the copies rather
50951     ** that the original pages since the original pages will be in the
50952     ** process of being overwritten.  */
50953     MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i];
50954     memcpy(pOld, apOld[i], sizeof(MemPage));
50955     pOld->aData = (void*)&pOld[1];
50956     memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize);
50957
50958     limit = pOld->nCell+pOld->nOverflow;
50959     for(j=0; j<limit; j++){
50960       assert( nCell<nMaxCells );
50961       apCell[nCell] = findOverflowCell(pOld, j);
50962       szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
50963       nCell++;
50964     }
50965     if( i<nOld-1 && !leafData){
50966       u16 sz = (u16)szNew[i];
50967       u8 *pTemp;
50968       assert( nCell<nMaxCells );
50969       szCell[nCell] = sz;
50970       pTemp = &aSpace1[iSpace1];
50971       iSpace1 += sz;
50972       assert( sz<=pBt->maxLocal+23 );
50973       assert( iSpace1<=pBt->pageSize );
50974       memcpy(pTemp, apDiv[i], sz);
50975       apCell[nCell] = pTemp+leafCorrection;
50976       assert( leafCorrection==0 || leafCorrection==4 );
50977       szCell[nCell] = szCell[nCell] - leafCorrection;
50978       if( !pOld->leaf ){
50979         assert( leafCorrection==0 );
50980         assert( pOld->hdrOffset==0 );
50981         /* The right pointer of the child page pOld becomes the left
50982         ** pointer of the divider cell */
50983         memcpy(apCell[nCell], &pOld->aData[8], 4);
50984       }else{
50985         assert( leafCorrection==4 );
50986         if( szCell[nCell]<4 ){
50987           /* Do not allow any cells smaller than 4 bytes. */
50988           szCell[nCell] = 4;
50989         }
50990       }
50991       nCell++;
50992     }
50993   }
50994
50995   /*
50996   ** Figure out the number of pages needed to hold all nCell cells.
50997   ** Store this number in "k".  Also compute szNew[] which is the total
50998   ** size of all cells on the i-th page and cntNew[] which is the index
50999   ** in apCell[] of the cell that divides page i from page i+1.  
51000   ** cntNew[k] should equal nCell.
51001   **
51002   ** Values computed by this block:
51003   **
51004   **           k: The total number of sibling pages
51005   **    szNew[i]: Spaced used on the i-th sibling page.
51006   **   cntNew[i]: Index in apCell[] and szCell[] for the first cell to
51007   **              the right of the i-th sibling page.
51008   ** usableSpace: Number of bytes of space available on each sibling.
51009   ** 
51010   */
51011   usableSpace = pBt->usableSize - 12 + leafCorrection;
51012   for(subtotal=k=i=0; i<nCell; i++){
51013     assert( i<nMaxCells );
51014     subtotal += szCell[i] + 2;
51015     if( subtotal > usableSpace ){
51016       szNew[k] = subtotal - szCell[i];
51017       cntNew[k] = i;
51018       if( leafData ){ i--; }
51019       subtotal = 0;
51020       k++;
51021       if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
51022     }
51023   }
51024   szNew[k] = subtotal;
51025   cntNew[k] = nCell;
51026   k++;
51027
51028   /*
51029   ** The packing computed by the previous block is biased toward the siblings
51030   ** on the left side.  The left siblings are always nearly full, while the
51031   ** right-most sibling might be nearly empty.  This block of code attempts
51032   ** to adjust the packing of siblings to get a better balance.
51033   **
51034   ** This adjustment is more than an optimization.  The packing above might
51035   ** be so out of balance as to be illegal.  For example, the right-most
51036   ** sibling might be completely empty.  This adjustment is not optional.
51037   */
51038   for(i=k-1; i>0; i--){
51039     int szRight = szNew[i];  /* Size of sibling on the right */
51040     int szLeft = szNew[i-1]; /* Size of sibling on the left */
51041     int r;              /* Index of right-most cell in left sibling */
51042     int d;              /* Index of first cell to the left of right sibling */
51043
51044     r = cntNew[i-1] - 1;
51045     d = r + 1 - leafData;
51046     assert( d<nMaxCells );
51047     assert( r<nMaxCells );
51048     while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
51049       szRight += szCell[d] + 2;
51050       szLeft -= szCell[r] + 2;
51051       cntNew[i-1]--;
51052       r = cntNew[i-1] - 1;
51053       d = r + 1 - leafData;
51054     }
51055     szNew[i] = szRight;
51056     szNew[i-1] = szLeft;
51057   }
51058
51059   /* Either we found one or more cells (cntnew[0])>0) or pPage is
51060   ** a virtual root page.  A virtual root page is when the real root
51061   ** page is page 1 and we are the only child of that page.
51062   */
51063   assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
51064
51065   TRACE(("BALANCE: old: %d %d %d  ",
51066     apOld[0]->pgno, 
51067     nOld>=2 ? apOld[1]->pgno : 0,
51068     nOld>=3 ? apOld[2]->pgno : 0
51069   ));
51070
51071   /*
51072   ** Allocate k new pages.  Reuse old pages where possible.
51073   */
51074   if( apOld[0]->pgno<=1 ){
51075     rc = SQLITE_CORRUPT_BKPT;
51076     goto balance_cleanup;
51077   }
51078   pageFlags = apOld[0]->aData[0];
51079   for(i=0; i<k; i++){
51080     MemPage *pNew;
51081     if( i<nOld ){
51082       pNew = apNew[i] = apOld[i];
51083       apOld[i] = 0;
51084       rc = sqlite3PagerWrite(pNew->pDbPage);
51085       nNew++;
51086       if( rc ) goto balance_cleanup;
51087     }else{
51088       assert( i>0 );
51089       rc = allocateBtreePage(pBt, &pNew, &pgno, pgno, 0);
51090       if( rc ) goto balance_cleanup;
51091       apNew[i] = pNew;
51092       nNew++;
51093
51094       /* Set the pointer-map entry for the new sibling page. */
51095       if( ISAUTOVACUUM ){
51096         ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
51097         if( rc!=SQLITE_OK ){
51098           goto balance_cleanup;
51099         }
51100       }
51101     }
51102   }
51103
51104   /* Free any old pages that were not reused as new pages.
51105   */
51106   while( i<nOld ){
51107     freePage(apOld[i], &rc);
51108     if( rc ) goto balance_cleanup;
51109     releasePage(apOld[i]);
51110     apOld[i] = 0;
51111     i++;
51112   }
51113
51114   /*
51115   ** Put the new pages in accending order.  This helps to
51116   ** keep entries in the disk file in order so that a scan
51117   ** of the table is a linear scan through the file.  That
51118   ** in turn helps the operating system to deliver pages
51119   ** from the disk more rapidly.
51120   **
51121   ** An O(n^2) insertion sort algorithm is used, but since
51122   ** n is never more than NB (a small constant), that should
51123   ** not be a problem.
51124   **
51125   ** When NB==3, this one optimization makes the database
51126   ** about 25% faster for large insertions and deletions.
51127   */
51128   for(i=0; i<k-1; i++){
51129     int minV = apNew[i]->pgno;
51130     int minI = i;
51131     for(j=i+1; j<k; j++){
51132       if( apNew[j]->pgno<(unsigned)minV ){
51133         minI = j;
51134         minV = apNew[j]->pgno;
51135       }
51136     }
51137     if( minI>i ){
51138       int t;
51139       MemPage *pT;
51140       t = apNew[i]->pgno;
51141       pT = apNew[i];
51142       apNew[i] = apNew[minI];
51143       apNew[minI] = pT;
51144     }
51145   }
51146   TRACE(("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
51147     apNew[0]->pgno, szNew[0],
51148     nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
51149     nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
51150     nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
51151     nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0));
51152
51153   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
51154   put4byte(pRight, apNew[nNew-1]->pgno);
51155
51156   /*
51157   ** Evenly distribute the data in apCell[] across the new pages.
51158   ** Insert divider cells into pParent as necessary.
51159   */
51160   j = 0;
51161   for(i=0; i<nNew; i++){
51162     /* Assemble the new sibling page. */
51163     MemPage *pNew = apNew[i];
51164     assert( j<nMaxCells );
51165     zeroPage(pNew, pageFlags);
51166     assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
51167     assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
51168     assert( pNew->nOverflow==0 );
51169
51170     j = cntNew[i];
51171
51172     /* If the sibling page assembled above was not the right-most sibling,
51173     ** insert a divider cell into the parent page.
51174     */
51175     assert( i<nNew-1 || j==nCell );
51176     if( j<nCell ){
51177       u8 *pCell;
51178       u8 *pTemp;
51179       int sz;
51180
51181       assert( j<nMaxCells );
51182       pCell = apCell[j];
51183       sz = szCell[j] + leafCorrection;
51184       pTemp = &aOvflSpace[iOvflSpace];
51185       if( !pNew->leaf ){
51186         memcpy(&pNew->aData[8], pCell, 4);
51187       }else if( leafData ){
51188         /* If the tree is a leaf-data tree, and the siblings are leaves, 
51189         ** then there is no divider cell in apCell[]. Instead, the divider 
51190         ** cell consists of the integer key for the right-most cell of 
51191         ** the sibling-page assembled above only.
51192         */
51193         CellInfo info;
51194         j--;
51195         btreeParseCellPtr(pNew, apCell[j], &info);
51196         pCell = pTemp;
51197         sz = 4 + putVarint(&pCell[4], info.nKey);
51198         pTemp = 0;
51199       }else{
51200         pCell -= 4;
51201         /* Obscure case for non-leaf-data trees: If the cell at pCell was
51202         ** previously stored on a leaf node, and its reported size was 4
51203         ** bytes, then it may actually be smaller than this 
51204         ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
51205         ** any cell). But it is important to pass the correct size to 
51206         ** insertCell(), so reparse the cell now.
51207         **
51208         ** Note that this can never happen in an SQLite data file, as all
51209         ** cells are at least 4 bytes. It only happens in b-trees used
51210         ** to evaluate "IN (SELECT ...)" and similar clauses.
51211         */
51212         if( szCell[j]==4 ){
51213           assert(leafCorrection==4);
51214           sz = cellSizePtr(pParent, pCell);
51215         }
51216       }
51217       iOvflSpace += sz;
51218       assert( sz<=pBt->maxLocal+23 );
51219       assert( iOvflSpace<=pBt->pageSize );
51220       insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc);
51221       if( rc!=SQLITE_OK ) goto balance_cleanup;
51222       assert( sqlite3PagerIswriteable(pParent->pDbPage) );
51223
51224       j++;
51225       nxDiv++;
51226     }
51227   }
51228   assert( j==nCell );
51229   assert( nOld>0 );
51230   assert( nNew>0 );
51231   if( (pageFlags & PTF_LEAF)==0 ){
51232     u8 *zChild = &apCopy[nOld-1]->aData[8];
51233     memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
51234   }
51235
51236   if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
51237     /* The root page of the b-tree now contains no cells. The only sibling
51238     ** page is the right-child of the parent. Copy the contents of the
51239     ** child page into the parent, decreasing the overall height of the
51240     ** b-tree structure by one. This is described as the "balance-shallower"
51241     ** sub-algorithm in some documentation.
51242     **
51243     ** If this is an auto-vacuum database, the call to copyNodeContent() 
51244     ** sets all pointer-map entries corresponding to database image pages 
51245     ** for which the pointer is stored within the content being copied.
51246     **
51247     ** The second assert below verifies that the child page is defragmented
51248     ** (it must be, as it was just reconstructed using assemblePage()). This
51249     ** is important if the parent page happens to be page 1 of the database
51250     ** image.  */
51251     assert( nNew==1 );
51252     assert( apNew[0]->nFree == 
51253         (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2) 
51254     );
51255     copyNodeContent(apNew[0], pParent, &rc);
51256     freePage(apNew[0], &rc);
51257   }else if( ISAUTOVACUUM ){
51258     /* Fix the pointer-map entries for all the cells that were shifted around. 
51259     ** There are several different types of pointer-map entries that need to
51260     ** be dealt with by this routine. Some of these have been set already, but
51261     ** many have not. The following is a summary:
51262     **
51263     **   1) The entries associated with new sibling pages that were not
51264     **      siblings when this function was called. These have already
51265     **      been set. We don't need to worry about old siblings that were
51266     **      moved to the free-list - the freePage() code has taken care
51267     **      of those.
51268     **
51269     **   2) The pointer-map entries associated with the first overflow
51270     **      page in any overflow chains used by new divider cells. These 
51271     **      have also already been taken care of by the insertCell() code.
51272     **
51273     **   3) If the sibling pages are not leaves, then the child pages of
51274     **      cells stored on the sibling pages may need to be updated.
51275     **
51276     **   4) If the sibling pages are not internal intkey nodes, then any
51277     **      overflow pages used by these cells may need to be updated
51278     **      (internal intkey nodes never contain pointers to overflow pages).
51279     **
51280     **   5) If the sibling pages are not leaves, then the pointer-map
51281     **      entries for the right-child pages of each sibling may need
51282     **      to be updated.
51283     **
51284     ** Cases 1 and 2 are dealt with above by other code. The next
51285     ** block deals with cases 3 and 4 and the one after that, case 5. Since
51286     ** setting a pointer map entry is a relatively expensive operation, this
51287     ** code only sets pointer map entries for child or overflow pages that have
51288     ** actually moved between pages.  */
51289     MemPage *pNew = apNew[0];
51290     MemPage *pOld = apCopy[0];
51291     int nOverflow = pOld->nOverflow;
51292     int iNextOld = pOld->nCell + nOverflow;
51293     int iOverflow = (nOverflow ? pOld->aOvfl[0].idx : -1);
51294     j = 0;                             /* Current 'old' sibling page */
51295     k = 0;                             /* Current 'new' sibling page */
51296     for(i=0; i<nCell; i++){
51297       int isDivider = 0;
51298       while( i==iNextOld ){
51299         /* Cell i is the cell immediately following the last cell on old
51300         ** sibling page j. If the siblings are not leaf pages of an
51301         ** intkey b-tree, then cell i was a divider cell. */
51302         pOld = apCopy[++j];
51303         iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow;
51304         if( pOld->nOverflow ){
51305           nOverflow = pOld->nOverflow;
51306           iOverflow = i + !leafData + pOld->aOvfl[0].idx;
51307         }
51308         isDivider = !leafData;  
51309       }
51310
51311       assert(nOverflow>0 || iOverflow<i );
51312       assert(nOverflow<2 || pOld->aOvfl[0].idx==pOld->aOvfl[1].idx-1);
51313       assert(nOverflow<3 || pOld->aOvfl[1].idx==pOld->aOvfl[2].idx-1);
51314       if( i==iOverflow ){
51315         isDivider = 1;
51316         if( (--nOverflow)>0 ){
51317           iOverflow++;
51318         }
51319       }
51320
51321       if( i==cntNew[k] ){
51322         /* Cell i is the cell immediately following the last cell on new
51323         ** sibling page k. If the siblings are not leaf pages of an
51324         ** intkey b-tree, then cell i is a divider cell.  */
51325         pNew = apNew[++k];
51326         if( !leafData ) continue;
51327       }
51328       assert( j<nOld );
51329       assert( k<nNew );
51330
51331       /* If the cell was originally divider cell (and is not now) or
51332       ** an overflow cell, or if the cell was located on a different sibling
51333       ** page before the balancing, then the pointer map entries associated
51334       ** with any child or overflow pages need to be updated.  */
51335       if( isDivider || pOld->pgno!=pNew->pgno ){
51336         if( !leafCorrection ){
51337           ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno, &rc);
51338         }
51339         if( szCell[i]>pNew->minLocal ){
51340           ptrmapPutOvflPtr(pNew, apCell[i], &rc);
51341         }
51342       }
51343     }
51344
51345     if( !leafCorrection ){
51346       for(i=0; i<nNew; i++){
51347         u32 key = get4byte(&apNew[i]->aData[8]);
51348         ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
51349       }
51350     }
51351
51352 #if 0
51353     /* The ptrmapCheckPages() contains assert() statements that verify that
51354     ** all pointer map pages are set correctly. This is helpful while 
51355     ** debugging. This is usually disabled because a corrupt database may
51356     ** cause an assert() statement to fail.  */
51357     ptrmapCheckPages(apNew, nNew);
51358     ptrmapCheckPages(&pParent, 1);
51359 #endif
51360   }
51361
51362   assert( pParent->isInit );
51363   TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
51364           nOld, nNew, nCell));
51365
51366   /*
51367   ** Cleanup before returning.
51368   */
51369 balance_cleanup:
51370   sqlite3ScratchFree(apCell);
51371   for(i=0; i<nOld; i++){
51372     releasePage(apOld[i]);
51373   }
51374   for(i=0; i<nNew; i++){
51375     releasePage(apNew[i]);
51376   }
51377
51378   return rc;
51379 }
51380
51381
51382 /*
51383 ** This function is called when the root page of a b-tree structure is
51384 ** overfull (has one or more overflow pages).
51385 **
51386 ** A new child page is allocated and the contents of the current root
51387 ** page, including overflow cells, are copied into the child. The root
51388 ** page is then overwritten to make it an empty page with the right-child 
51389 ** pointer pointing to the new page.
51390 **
51391 ** Before returning, all pointer-map entries corresponding to pages 
51392 ** that the new child-page now contains pointers to are updated. The
51393 ** entry corresponding to the new right-child pointer of the root
51394 ** page is also updated.
51395 **
51396 ** If successful, *ppChild is set to contain a reference to the child 
51397 ** page and SQLITE_OK is returned. In this case the caller is required
51398 ** to call releasePage() on *ppChild exactly once. If an error occurs,
51399 ** an error code is returned and *ppChild is set to 0.
51400 */
51401 static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
51402   int rc;                        /* Return value from subprocedures */
51403   MemPage *pChild = 0;           /* Pointer to a new child page */
51404   Pgno pgnoChild = 0;            /* Page number of the new child page */
51405   BtShared *pBt = pRoot->pBt;    /* The BTree */
51406
51407   assert( pRoot->nOverflow>0 );
51408   assert( sqlite3_mutex_held(pBt->mutex) );
51409
51410   /* Make pRoot, the root page of the b-tree, writable. Allocate a new 
51411   ** page that will become the new right-child of pPage. Copy the contents
51412   ** of the node stored on pRoot into the new child page.
51413   */
51414   rc = sqlite3PagerWrite(pRoot->pDbPage);
51415   if( rc==SQLITE_OK ){
51416     rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
51417     copyNodeContent(pRoot, pChild, &rc);
51418     if( ISAUTOVACUUM ){
51419       ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
51420     }
51421   }
51422   if( rc ){
51423     *ppChild = 0;
51424     releasePage(pChild);
51425     return rc;
51426   }
51427   assert( sqlite3PagerIswriteable(pChild->pDbPage) );
51428   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
51429   assert( pChild->nCell==pRoot->nCell );
51430
51431   TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
51432
51433   /* Copy the overflow cells from pRoot to pChild */
51434   memcpy(pChild->aOvfl, pRoot->aOvfl, pRoot->nOverflow*sizeof(pRoot->aOvfl[0]));
51435   pChild->nOverflow = pRoot->nOverflow;
51436
51437   /* Zero the contents of pRoot. Then install pChild as the right-child. */
51438   zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
51439   put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
51440
51441   *ppChild = pChild;
51442   return SQLITE_OK;
51443 }
51444
51445 /*
51446 ** The page that pCur currently points to has just been modified in
51447 ** some way. This function figures out if this modification means the
51448 ** tree needs to be balanced, and if so calls the appropriate balancing 
51449 ** routine. Balancing routines are:
51450 **
51451 **   balance_quick()
51452 **   balance_deeper()
51453 **   balance_nonroot()
51454 */
51455 static int balance(BtCursor *pCur){
51456   int rc = SQLITE_OK;
51457   const int nMin = pCur->pBt->usableSize * 2 / 3;
51458   u8 aBalanceQuickSpace[13];
51459   u8 *pFree = 0;
51460
51461   TESTONLY( int balance_quick_called = 0 );
51462   TESTONLY( int balance_deeper_called = 0 );
51463
51464   do {
51465     int iPage = pCur->iPage;
51466     MemPage *pPage = pCur->apPage[iPage];
51467
51468     if( iPage==0 ){
51469       if( pPage->nOverflow ){
51470         /* The root page of the b-tree is overfull. In this case call the
51471         ** balance_deeper() function to create a new child for the root-page
51472         ** and copy the current contents of the root-page to it. The
51473         ** next iteration of the do-loop will balance the child page.
51474         */ 
51475         assert( (balance_deeper_called++)==0 );
51476         rc = balance_deeper(pPage, &pCur->apPage[1]);
51477         if( rc==SQLITE_OK ){
51478           pCur->iPage = 1;
51479           pCur->aiIdx[0] = 0;
51480           pCur->aiIdx[1] = 0;
51481           assert( pCur->apPage[1]->nOverflow );
51482         }
51483       }else{
51484         break;
51485       }
51486     }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
51487       break;
51488     }else{
51489       MemPage * const pParent = pCur->apPage[iPage-1];
51490       int const iIdx = pCur->aiIdx[iPage-1];
51491
51492       rc = sqlite3PagerWrite(pParent->pDbPage);
51493       if( rc==SQLITE_OK ){
51494 #ifndef SQLITE_OMIT_QUICKBALANCE
51495         if( pPage->hasData
51496          && pPage->nOverflow==1
51497          && pPage->aOvfl[0].idx==pPage->nCell
51498          && pParent->pgno!=1
51499          && pParent->nCell==iIdx
51500         ){
51501           /* Call balance_quick() to create a new sibling of pPage on which
51502           ** to store the overflow cell. balance_quick() inserts a new cell
51503           ** into pParent, which may cause pParent overflow. If this
51504           ** happens, the next interation of the do-loop will balance pParent 
51505           ** use either balance_nonroot() or balance_deeper(). Until this
51506           ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
51507           ** buffer. 
51508           **
51509           ** The purpose of the following assert() is to check that only a
51510           ** single call to balance_quick() is made for each call to this
51511           ** function. If this were not verified, a subtle bug involving reuse
51512           ** of the aBalanceQuickSpace[] might sneak in.
51513           */
51514           assert( (balance_quick_called++)==0 );
51515           rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
51516         }else
51517 #endif
51518         {
51519           /* In this case, call balance_nonroot() to redistribute cells
51520           ** between pPage and up to 2 of its sibling pages. This involves
51521           ** modifying the contents of pParent, which may cause pParent to
51522           ** become overfull or underfull. The next iteration of the do-loop
51523           ** will balance the parent page to correct this.
51524           ** 
51525           ** If the parent page becomes overfull, the overflow cell or cells
51526           ** are stored in the pSpace buffer allocated immediately below. 
51527           ** A subsequent iteration of the do-loop will deal with this by
51528           ** calling balance_nonroot() (balance_deeper() may be called first,
51529           ** but it doesn't deal with overflow cells - just moves them to a
51530           ** different page). Once this subsequent call to balance_nonroot() 
51531           ** has completed, it is safe to release the pSpace buffer used by
51532           ** the previous call, as the overflow cell data will have been 
51533           ** copied either into the body of a database page or into the new
51534           ** pSpace buffer passed to the latter call to balance_nonroot().
51535           */
51536           u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
51537           rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1);
51538           if( pFree ){
51539             /* If pFree is not NULL, it points to the pSpace buffer used 
51540             ** by a previous call to balance_nonroot(). Its contents are
51541             ** now stored either on real database pages or within the 
51542             ** new pSpace buffer, so it may be safely freed here. */
51543             sqlite3PageFree(pFree);
51544           }
51545
51546           /* The pSpace buffer will be freed after the next call to
51547           ** balance_nonroot(), or just before this function returns, whichever
51548           ** comes first. */
51549           pFree = pSpace;
51550         }
51551       }
51552
51553       pPage->nOverflow = 0;
51554
51555       /* The next iteration of the do-loop balances the parent page. */
51556       releasePage(pPage);
51557       pCur->iPage--;
51558     }
51559   }while( rc==SQLITE_OK );
51560
51561   if( pFree ){
51562     sqlite3PageFree(pFree);
51563   }
51564   return rc;
51565 }
51566
51567
51568 /*
51569 ** Insert a new record into the BTree.  The key is given by (pKey,nKey)
51570 ** and the data is given by (pData,nData).  The cursor is used only to
51571 ** define what table the record should be inserted into.  The cursor
51572 ** is left pointing at a random location.
51573 **
51574 ** For an INTKEY table, only the nKey value of the key is used.  pKey is
51575 ** ignored.  For a ZERODATA table, the pData and nData are both ignored.
51576 **
51577 ** If the seekResult parameter is non-zero, then a successful call to
51578 ** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
51579 ** been performed. seekResult is the search result returned (a negative
51580 ** number if pCur points at an entry that is smaller than (pKey, nKey), or
51581 ** a positive value if pCur points at an etry that is larger than 
51582 ** (pKey, nKey)). 
51583 **
51584 ** If the seekResult parameter is non-zero, then the caller guarantees that
51585 ** cursor pCur is pointing at the existing copy of a row that is to be
51586 ** overwritten.  If the seekResult parameter is 0, then cursor pCur may
51587 ** point to any entry or to no entry at all and so this function has to seek
51588 ** the cursor before the new key can be inserted.
51589 */
51590 SQLITE_PRIVATE int sqlite3BtreeInsert(
51591   BtCursor *pCur,                /* Insert data into the table of this cursor */
51592   const void *pKey, i64 nKey,    /* The key of the new record */
51593   const void *pData, int nData,  /* The data of the new record */
51594   int nZero,                     /* Number of extra 0 bytes to append to data */
51595   int appendBias,                /* True if this is likely an append */
51596   int seekResult                 /* Result of prior MovetoUnpacked() call */
51597 ){
51598   int rc;
51599   int loc = seekResult;          /* -1: before desired location  +1: after */
51600   int szNew = 0;
51601   int idx;
51602   MemPage *pPage;
51603   Btree *p = pCur->pBtree;
51604   BtShared *pBt = p->pBt;
51605   unsigned char *oldCell;
51606   unsigned char *newCell = 0;
51607
51608   if( pCur->eState==CURSOR_FAULT ){
51609     assert( pCur->skipNext!=SQLITE_OK );
51610     return pCur->skipNext;
51611   }
51612
51613   assert( cursorHoldsMutex(pCur) );
51614   assert( pCur->wrFlag && pBt->inTransaction==TRANS_WRITE && !pBt->readOnly );
51615   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
51616
51617   /* Assert that the caller has been consistent. If this cursor was opened
51618   ** expecting an index b-tree, then the caller should be inserting blob
51619   ** keys with no associated data. If the cursor was opened expecting an
51620   ** intkey table, the caller should be inserting integer keys with a
51621   ** blob of associated data.  */
51622   assert( (pKey==0)==(pCur->pKeyInfo==0) );
51623
51624   /* If this is an insert into a table b-tree, invalidate any incrblob 
51625   ** cursors open on the row being replaced (assuming this is a replace
51626   ** operation - if it is not, the following is a no-op).  */
51627   if( pCur->pKeyInfo==0 ){
51628     invalidateIncrblobCursors(p, nKey, 0);
51629   }
51630
51631   /* Save the positions of any other cursors open on this table.
51632   **
51633   ** In some cases, the call to btreeMoveto() below is a no-op. For
51634   ** example, when inserting data into a table with auto-generated integer
51635   ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the 
51636   ** integer key to use. It then calls this function to actually insert the 
51637   ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
51638   ** that the cursor is already where it needs to be and returns without
51639   ** doing any work. To avoid thwarting these optimizations, it is important
51640   ** not to clear the cursor here.
51641   */
51642   rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
51643   if( rc ) return rc;
51644   if( !loc ){
51645     rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
51646     if( rc ) return rc;
51647   }
51648   assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
51649
51650   pPage = pCur->apPage[pCur->iPage];
51651   assert( pPage->intKey || nKey>=0 );
51652   assert( pPage->leaf || !pPage->intKey );
51653
51654   TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
51655           pCur->pgnoRoot, nKey, nData, pPage->pgno,
51656           loc==0 ? "overwrite" : "new entry"));
51657   assert( pPage->isInit );
51658   allocateTempSpace(pBt);
51659   newCell = pBt->pTmpSpace;
51660   if( newCell==0 ) return SQLITE_NOMEM;
51661   rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
51662   if( rc ) goto end_insert;
51663   assert( szNew==cellSizePtr(pPage, newCell) );
51664   assert( szNew<=MX_CELL_SIZE(pBt) );
51665   idx = pCur->aiIdx[pCur->iPage];
51666   if( loc==0 ){
51667     u16 szOld;
51668     assert( idx<pPage->nCell );
51669     rc = sqlite3PagerWrite(pPage->pDbPage);
51670     if( rc ){
51671       goto end_insert;
51672     }
51673     oldCell = findCell(pPage, idx);
51674     if( !pPage->leaf ){
51675       memcpy(newCell, oldCell, 4);
51676     }
51677     szOld = cellSizePtr(pPage, oldCell);
51678     rc = clearCell(pPage, oldCell);
51679     dropCell(pPage, idx, szOld, &rc);
51680     if( rc ) goto end_insert;
51681   }else if( loc<0 && pPage->nCell>0 ){
51682     assert( pPage->leaf );
51683     idx = ++pCur->aiIdx[pCur->iPage];
51684   }else{
51685     assert( pPage->leaf );
51686   }
51687   insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
51688   assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
51689
51690   /* If no error has occured and pPage has an overflow cell, call balance() 
51691   ** to redistribute the cells within the tree. Since balance() may move
51692   ** the cursor, zero the BtCursor.info.nSize and BtCursor.validNKey
51693   ** variables.
51694   **
51695   ** Previous versions of SQLite called moveToRoot() to move the cursor
51696   ** back to the root page as balance() used to invalidate the contents
51697   ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
51698   ** set the cursor state to "invalid". This makes common insert operations
51699   ** slightly faster.
51700   **
51701   ** There is a subtle but important optimization here too. When inserting
51702   ** multiple records into an intkey b-tree using a single cursor (as can
51703   ** happen while processing an "INSERT INTO ... SELECT" statement), it
51704   ** is advantageous to leave the cursor pointing to the last entry in
51705   ** the b-tree if possible. If the cursor is left pointing to the last
51706   ** entry in the table, and the next row inserted has an integer key
51707   ** larger than the largest existing key, it is possible to insert the
51708   ** row without seeking the cursor. This can be a big performance boost.
51709   */
51710   pCur->info.nSize = 0;
51711   pCur->validNKey = 0;
51712   if( rc==SQLITE_OK && pPage->nOverflow ){
51713     rc = balance(pCur);
51714
51715     /* Must make sure nOverflow is reset to zero even if the balance()
51716     ** fails. Internal data structure corruption will result otherwise. 
51717     ** Also, set the cursor state to invalid. This stops saveCursorPosition()
51718     ** from trying to save the current position of the cursor.  */
51719     pCur->apPage[pCur->iPage]->nOverflow = 0;
51720     pCur->eState = CURSOR_INVALID;
51721   }
51722   assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
51723
51724 end_insert:
51725   return rc;
51726 }
51727
51728 /*
51729 ** Delete the entry that the cursor is pointing to.  The cursor
51730 ** is left pointing at a arbitrary location.
51731 */
51732 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
51733   Btree *p = pCur->pBtree;
51734   BtShared *pBt = p->pBt;              
51735   int rc;                              /* Return code */
51736   MemPage *pPage;                      /* Page to delete cell from */
51737   unsigned char *pCell;                /* Pointer to cell to delete */
51738   int iCellIdx;                        /* Index of cell to delete */
51739   int iCellDepth;                      /* Depth of node containing pCell */ 
51740
51741   assert( cursorHoldsMutex(pCur) );
51742   assert( pBt->inTransaction==TRANS_WRITE );
51743   assert( !pBt->readOnly );
51744   assert( pCur->wrFlag );
51745   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
51746   assert( !hasReadConflicts(p, pCur->pgnoRoot) );
51747
51748   if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell) 
51749    || NEVER(pCur->eState!=CURSOR_VALID)
51750   ){
51751     return SQLITE_ERROR;  /* Something has gone awry. */
51752   }
51753
51754   /* If this is a delete operation to remove a row from a table b-tree,
51755   ** invalidate any incrblob cursors open on the row being deleted.  */
51756   if( pCur->pKeyInfo==0 ){
51757     invalidateIncrblobCursors(p, pCur->info.nKey, 0);
51758   }
51759
51760   iCellDepth = pCur->iPage;
51761   iCellIdx = pCur->aiIdx[iCellDepth];
51762   pPage = pCur->apPage[iCellDepth];
51763   pCell = findCell(pPage, iCellIdx);
51764
51765   /* If the page containing the entry to delete is not a leaf page, move
51766   ** the cursor to the largest entry in the tree that is smaller than
51767   ** the entry being deleted. This cell will replace the cell being deleted
51768   ** from the internal node. The 'previous' entry is used for this instead
51769   ** of the 'next' entry, as the previous entry is always a part of the
51770   ** sub-tree headed by the child page of the cell being deleted. This makes
51771   ** balancing the tree following the delete operation easier.  */
51772   if( !pPage->leaf ){
51773     int notUsed;
51774     rc = sqlite3BtreePrevious(pCur, &notUsed);
51775     if( rc ) return rc;
51776   }
51777
51778   /* Save the positions of any other cursors open on this table before
51779   ** making any modifications. Make the page containing the entry to be 
51780   ** deleted writable. Then free any overflow pages associated with the 
51781   ** entry and finally remove the cell itself from within the page.  
51782   */
51783   rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
51784   if( rc ) return rc;
51785   rc = sqlite3PagerWrite(pPage->pDbPage);
51786   if( rc ) return rc;
51787   rc = clearCell(pPage, pCell);
51788   dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell), &rc);
51789   if( rc ) return rc;
51790
51791   /* If the cell deleted was not located on a leaf page, then the cursor
51792   ** is currently pointing to the largest entry in the sub-tree headed
51793   ** by the child-page of the cell that was just deleted from an internal
51794   ** node. The cell from the leaf node needs to be moved to the internal
51795   ** node to replace the deleted cell.  */
51796   if( !pPage->leaf ){
51797     MemPage *pLeaf = pCur->apPage[pCur->iPage];
51798     int nCell;
51799     Pgno n = pCur->apPage[iCellDepth+1]->pgno;
51800     unsigned char *pTmp;
51801
51802     pCell = findCell(pLeaf, pLeaf->nCell-1);
51803     nCell = cellSizePtr(pLeaf, pCell);
51804     assert( MX_CELL_SIZE(pBt)>=nCell );
51805
51806     allocateTempSpace(pBt);
51807     pTmp = pBt->pTmpSpace;
51808
51809     rc = sqlite3PagerWrite(pLeaf->pDbPage);
51810     insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
51811     dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
51812     if( rc ) return rc;
51813   }
51814
51815   /* Balance the tree. If the entry deleted was located on a leaf page,
51816   ** then the cursor still points to that page. In this case the first
51817   ** call to balance() repairs the tree, and the if(...) condition is
51818   ** never true.
51819   **
51820   ** Otherwise, if the entry deleted was on an internal node page, then
51821   ** pCur is pointing to the leaf page from which a cell was removed to
51822   ** replace the cell deleted from the internal node. This is slightly
51823   ** tricky as the leaf node may be underfull, and the internal node may
51824   ** be either under or overfull. In this case run the balancing algorithm
51825   ** on the leaf node first. If the balance proceeds far enough up the
51826   ** tree that we can be sure that any problem in the internal node has
51827   ** been corrected, so be it. Otherwise, after balancing the leaf node,
51828   ** walk the cursor up the tree to the internal node and balance it as 
51829   ** well.  */
51830   rc = balance(pCur);
51831   if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
51832     while( pCur->iPage>iCellDepth ){
51833       releasePage(pCur->apPage[pCur->iPage--]);
51834     }
51835     rc = balance(pCur);
51836   }
51837
51838   if( rc==SQLITE_OK ){
51839     moveToRoot(pCur);
51840   }
51841   return rc;
51842 }
51843
51844 /*
51845 ** Create a new BTree table.  Write into *piTable the page
51846 ** number for the root page of the new table.
51847 **
51848 ** The type of type is determined by the flags parameter.  Only the
51849 ** following values of flags are currently in use.  Other values for
51850 ** flags might not work:
51851 **
51852 **     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
51853 **     BTREE_ZERODATA                  Used for SQL indices
51854 */
51855 static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
51856   BtShared *pBt = p->pBt;
51857   MemPage *pRoot;
51858   Pgno pgnoRoot;
51859   int rc;
51860   int ptfFlags;          /* Page-type flage for the root page of new table */
51861
51862   assert( sqlite3BtreeHoldsMutex(p) );
51863   assert( pBt->inTransaction==TRANS_WRITE );
51864   assert( !pBt->readOnly );
51865
51866 #ifdef SQLITE_OMIT_AUTOVACUUM
51867   rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
51868   if( rc ){
51869     return rc;
51870   }
51871 #else
51872   if( pBt->autoVacuum ){
51873     Pgno pgnoMove;      /* Move a page here to make room for the root-page */
51874     MemPage *pPageMove; /* The page to move to. */
51875
51876     /* Creating a new table may probably require moving an existing database
51877     ** to make room for the new tables root page. In case this page turns
51878     ** out to be an overflow page, delete all overflow page-map caches
51879     ** held by open cursors.
51880     */
51881     invalidateAllOverflowCache(pBt);
51882
51883     /* Read the value of meta[3] from the database to determine where the
51884     ** root page of the new table should go. meta[3] is the largest root-page
51885     ** created so far, so the new root-page is (meta[3]+1).
51886     */
51887     sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
51888     pgnoRoot++;
51889
51890     /* The new root-page may not be allocated on a pointer-map page, or the
51891     ** PENDING_BYTE page.
51892     */
51893     while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
51894         pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
51895       pgnoRoot++;
51896     }
51897     assert( pgnoRoot>=3 );
51898
51899     /* Allocate a page. The page that currently resides at pgnoRoot will
51900     ** be moved to the allocated page (unless the allocated page happens
51901     ** to reside at pgnoRoot).
51902     */
51903     rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
51904     if( rc!=SQLITE_OK ){
51905       return rc;
51906     }
51907
51908     if( pgnoMove!=pgnoRoot ){
51909       /* pgnoRoot is the page that will be used for the root-page of
51910       ** the new table (assuming an error did not occur). But we were
51911       ** allocated pgnoMove. If required (i.e. if it was not allocated
51912       ** by extending the file), the current page at position pgnoMove
51913       ** is already journaled.
51914       */
51915       u8 eType = 0;
51916       Pgno iPtrPage = 0;
51917
51918       releasePage(pPageMove);
51919
51920       /* Move the page currently at pgnoRoot to pgnoMove. */
51921       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
51922       if( rc!=SQLITE_OK ){
51923         return rc;
51924       }
51925       rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
51926       if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
51927         rc = SQLITE_CORRUPT_BKPT;
51928       }
51929       if( rc!=SQLITE_OK ){
51930         releasePage(pRoot);
51931         return rc;
51932       }
51933       assert( eType!=PTRMAP_ROOTPAGE );
51934       assert( eType!=PTRMAP_FREEPAGE );
51935       rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
51936       releasePage(pRoot);
51937
51938       /* Obtain the page at pgnoRoot */
51939       if( rc!=SQLITE_OK ){
51940         return rc;
51941       }
51942       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
51943       if( rc!=SQLITE_OK ){
51944         return rc;
51945       }
51946       rc = sqlite3PagerWrite(pRoot->pDbPage);
51947       if( rc!=SQLITE_OK ){
51948         releasePage(pRoot);
51949         return rc;
51950       }
51951     }else{
51952       pRoot = pPageMove;
51953     } 
51954
51955     /* Update the pointer-map and meta-data with the new root-page number. */
51956     ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
51957     if( rc ){
51958       releasePage(pRoot);
51959       return rc;
51960     }
51961
51962     /* When the new root page was allocated, page 1 was made writable in
51963     ** order either to increase the database filesize, or to decrement the
51964     ** freelist count.  Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
51965     */
51966     assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
51967     rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
51968     if( NEVER(rc) ){
51969       releasePage(pRoot);
51970       return rc;
51971     }
51972
51973   }else{
51974     rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
51975     if( rc ) return rc;
51976   }
51977 #endif
51978   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
51979   if( createTabFlags & BTREE_INTKEY ){
51980     ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
51981   }else{
51982     ptfFlags = PTF_ZERODATA | PTF_LEAF;
51983   }
51984   zeroPage(pRoot, ptfFlags);
51985   sqlite3PagerUnref(pRoot->pDbPage);
51986   assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
51987   *piTable = (int)pgnoRoot;
51988   return SQLITE_OK;
51989 }
51990 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
51991   int rc;
51992   sqlite3BtreeEnter(p);
51993   rc = btreeCreateTable(p, piTable, flags);
51994   sqlite3BtreeLeave(p);
51995   return rc;
51996 }
51997
51998 /*
51999 ** Erase the given database page and all its children.  Return
52000 ** the page to the freelist.
52001 */
52002 static int clearDatabasePage(
52003   BtShared *pBt,           /* The BTree that contains the table */
52004   Pgno pgno,               /* Page number to clear */
52005   int freePageFlag,        /* Deallocate page if true */
52006   int *pnChange            /* Add number of Cells freed to this counter */
52007 ){
52008   MemPage *pPage;
52009   int rc;
52010   unsigned char *pCell;
52011   int i;
52012
52013   assert( sqlite3_mutex_held(pBt->mutex) );
52014   if( pgno>btreePagecount(pBt) ){
52015     return SQLITE_CORRUPT_BKPT;
52016   }
52017
52018   rc = getAndInitPage(pBt, pgno, &pPage);
52019   if( rc ) return rc;
52020   for(i=0; i<pPage->nCell; i++){
52021     pCell = findCell(pPage, i);
52022     if( !pPage->leaf ){
52023       rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
52024       if( rc ) goto cleardatabasepage_out;
52025     }
52026     rc = clearCell(pPage, pCell);
52027     if( rc ) goto cleardatabasepage_out;
52028   }
52029   if( !pPage->leaf ){
52030     rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange);
52031     if( rc ) goto cleardatabasepage_out;
52032   }else if( pnChange ){
52033     assert( pPage->intKey );
52034     *pnChange += pPage->nCell;
52035   }
52036   if( freePageFlag ){
52037     freePage(pPage, &rc);
52038   }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
52039     zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
52040   }
52041
52042 cleardatabasepage_out:
52043   releasePage(pPage);
52044   return rc;
52045 }
52046
52047 /*
52048 ** Delete all information from a single table in the database.  iTable is
52049 ** the page number of the root of the table.  After this routine returns,
52050 ** the root page is empty, but still exists.
52051 **
52052 ** This routine will fail with SQLITE_LOCKED if there are any open
52053 ** read cursors on the table.  Open write cursors are moved to the
52054 ** root of the table.
52055 **
52056 ** If pnChange is not NULL, then table iTable must be an intkey table. The
52057 ** integer value pointed to by pnChange is incremented by the number of
52058 ** entries in the table.
52059 */
52060 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
52061   int rc;
52062   BtShared *pBt = p->pBt;
52063   sqlite3BtreeEnter(p);
52064   assert( p->inTrans==TRANS_WRITE );
52065
52066   /* Invalidate all incrblob cursors open on table iTable (assuming iTable
52067   ** is the root of a table b-tree - if it is not, the following call is
52068   ** a no-op).  */
52069   invalidateIncrblobCursors(p, 0, 1);
52070
52071   rc = saveAllCursors(pBt, (Pgno)iTable, 0);
52072   if( SQLITE_OK==rc ){
52073     rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
52074   }
52075   sqlite3BtreeLeave(p);
52076   return rc;
52077 }
52078
52079 /*
52080 ** Erase all information in a table and add the root of the table to
52081 ** the freelist.  Except, the root of the principle table (the one on
52082 ** page 1) is never added to the freelist.
52083 **
52084 ** This routine will fail with SQLITE_LOCKED if there are any open
52085 ** cursors on the table.
52086 **
52087 ** If AUTOVACUUM is enabled and the page at iTable is not the last
52088 ** root page in the database file, then the last root page 
52089 ** in the database file is moved into the slot formerly occupied by
52090 ** iTable and that last slot formerly occupied by the last root page
52091 ** is added to the freelist instead of iTable.  In this say, all
52092 ** root pages are kept at the beginning of the database file, which
52093 ** is necessary for AUTOVACUUM to work right.  *piMoved is set to the 
52094 ** page number that used to be the last root page in the file before
52095 ** the move.  If no page gets moved, *piMoved is set to 0.
52096 ** The last root page is recorded in meta[3] and the value of
52097 ** meta[3] is updated by this procedure.
52098 */
52099 static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
52100   int rc;
52101   MemPage *pPage = 0;
52102   BtShared *pBt = p->pBt;
52103
52104   assert( sqlite3BtreeHoldsMutex(p) );
52105   assert( p->inTrans==TRANS_WRITE );
52106
52107   /* It is illegal to drop a table if any cursors are open on the
52108   ** database. This is because in auto-vacuum mode the backend may
52109   ** need to move another root-page to fill a gap left by the deleted
52110   ** root page. If an open cursor was using this page a problem would 
52111   ** occur.
52112   **
52113   ** This error is caught long before control reaches this point.
52114   */
52115   if( NEVER(pBt->pCursor) ){
52116     sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
52117     return SQLITE_LOCKED_SHAREDCACHE;
52118   }
52119
52120   rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
52121   if( rc ) return rc;
52122   rc = sqlite3BtreeClearTable(p, iTable, 0);
52123   if( rc ){
52124     releasePage(pPage);
52125     return rc;
52126   }
52127
52128   *piMoved = 0;
52129
52130   if( iTable>1 ){
52131 #ifdef SQLITE_OMIT_AUTOVACUUM
52132     freePage(pPage, &rc);
52133     releasePage(pPage);
52134 #else
52135     if( pBt->autoVacuum ){
52136       Pgno maxRootPgno;
52137       sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
52138
52139       if( iTable==maxRootPgno ){
52140         /* If the table being dropped is the table with the largest root-page
52141         ** number in the database, put the root page on the free list. 
52142         */
52143         freePage(pPage, &rc);
52144         releasePage(pPage);
52145         if( rc!=SQLITE_OK ){
52146           return rc;
52147         }
52148       }else{
52149         /* The table being dropped does not have the largest root-page
52150         ** number in the database. So move the page that does into the 
52151         ** gap left by the deleted root-page.
52152         */
52153         MemPage *pMove;
52154         releasePage(pPage);
52155         rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
52156         if( rc!=SQLITE_OK ){
52157           return rc;
52158         }
52159         rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
52160         releasePage(pMove);
52161         if( rc!=SQLITE_OK ){
52162           return rc;
52163         }
52164         pMove = 0;
52165         rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
52166         freePage(pMove, &rc);
52167         releasePage(pMove);
52168         if( rc!=SQLITE_OK ){
52169           return rc;
52170         }
52171         *piMoved = maxRootPgno;
52172       }
52173
52174       /* Set the new 'max-root-page' value in the database header. This
52175       ** is the old value less one, less one more if that happens to
52176       ** be a root-page number, less one again if that is the
52177       ** PENDING_BYTE_PAGE.
52178       */
52179       maxRootPgno--;
52180       while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
52181              || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
52182         maxRootPgno--;
52183       }
52184       assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
52185
52186       rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
52187     }else{
52188       freePage(pPage, &rc);
52189       releasePage(pPage);
52190     }
52191 #endif
52192   }else{
52193     /* If sqlite3BtreeDropTable was called on page 1.
52194     ** This really never should happen except in a corrupt
52195     ** database. 
52196     */
52197     zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
52198     releasePage(pPage);
52199   }
52200   return rc;  
52201 }
52202 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
52203   int rc;
52204   sqlite3BtreeEnter(p);
52205   rc = btreeDropTable(p, iTable, piMoved);
52206   sqlite3BtreeLeave(p);
52207   return rc;
52208 }
52209
52210
52211 /*
52212 ** This function may only be called if the b-tree connection already
52213 ** has a read or write transaction open on the database.
52214 **
52215 ** Read the meta-information out of a database file.  Meta[0]
52216 ** is the number of free pages currently in the database.  Meta[1]
52217 ** through meta[15] are available for use by higher layers.  Meta[0]
52218 ** is read-only, the others are read/write.
52219 ** 
52220 ** The schema layer numbers meta values differently.  At the schema
52221 ** layer (and the SetCookie and ReadCookie opcodes) the number of
52222 ** free pages is not visible.  So Cookie[0] is the same as Meta[1].
52223 */
52224 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
52225   BtShared *pBt = p->pBt;
52226
52227   sqlite3BtreeEnter(p);
52228   assert( p->inTrans>TRANS_NONE );
52229   assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
52230   assert( pBt->pPage1 );
52231   assert( idx>=0 && idx<=15 );
52232
52233   *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
52234
52235   /* If auto-vacuum is disabled in this build and this is an auto-vacuum
52236   ** database, mark the database as read-only.  */
52237 #ifdef SQLITE_OMIT_AUTOVACUUM
52238   if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ) pBt->readOnly = 1;
52239 #endif
52240
52241   sqlite3BtreeLeave(p);
52242 }
52243
52244 /*
52245 ** Write meta-information back into the database.  Meta[0] is
52246 ** read-only and may not be written.
52247 */
52248 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
52249   BtShared *pBt = p->pBt;
52250   unsigned char *pP1;
52251   int rc;
52252   assert( idx>=1 && idx<=15 );
52253   sqlite3BtreeEnter(p);
52254   assert( p->inTrans==TRANS_WRITE );
52255   assert( pBt->pPage1!=0 );
52256   pP1 = pBt->pPage1->aData;
52257   rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
52258   if( rc==SQLITE_OK ){
52259     put4byte(&pP1[36 + idx*4], iMeta);
52260 #ifndef SQLITE_OMIT_AUTOVACUUM
52261     if( idx==BTREE_INCR_VACUUM ){
52262       assert( pBt->autoVacuum || iMeta==0 );
52263       assert( iMeta==0 || iMeta==1 );
52264       pBt->incrVacuum = (u8)iMeta;
52265     }
52266 #endif
52267   }
52268   sqlite3BtreeLeave(p);
52269   return rc;
52270 }
52271
52272 #ifndef SQLITE_OMIT_BTREECOUNT
52273 /*
52274 ** The first argument, pCur, is a cursor opened on some b-tree. Count the
52275 ** number of entries in the b-tree and write the result to *pnEntry.
52276 **
52277 ** SQLITE_OK is returned if the operation is successfully executed. 
52278 ** Otherwise, if an error is encountered (i.e. an IO error or database
52279 ** corruption) an SQLite error code is returned.
52280 */
52281 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
52282   i64 nEntry = 0;                      /* Value to return in *pnEntry */
52283   int rc;                              /* Return code */
52284   rc = moveToRoot(pCur);
52285
52286   /* Unless an error occurs, the following loop runs one iteration for each
52287   ** page in the B-Tree structure (not including overflow pages). 
52288   */
52289   while( rc==SQLITE_OK ){
52290     int iIdx;                          /* Index of child node in parent */
52291     MemPage *pPage;                    /* Current page of the b-tree */
52292
52293     /* If this is a leaf page or the tree is not an int-key tree, then 
52294     ** this page contains countable entries. Increment the entry counter
52295     ** accordingly.
52296     */
52297     pPage = pCur->apPage[pCur->iPage];
52298     if( pPage->leaf || !pPage->intKey ){
52299       nEntry += pPage->nCell;
52300     }
52301
52302     /* pPage is a leaf node. This loop navigates the cursor so that it 
52303     ** points to the first interior cell that it points to the parent of
52304     ** the next page in the tree that has not yet been visited. The
52305     ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
52306     ** of the page, or to the number of cells in the page if the next page
52307     ** to visit is the right-child of its parent.
52308     **
52309     ** If all pages in the tree have been visited, return SQLITE_OK to the
52310     ** caller.
52311     */
52312     if( pPage->leaf ){
52313       do {
52314         if( pCur->iPage==0 ){
52315           /* All pages of the b-tree have been visited. Return successfully. */
52316           *pnEntry = nEntry;
52317           return SQLITE_OK;
52318         }
52319         moveToParent(pCur);
52320       }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
52321
52322       pCur->aiIdx[pCur->iPage]++;
52323       pPage = pCur->apPage[pCur->iPage];
52324     }
52325
52326     /* Descend to the child node of the cell that the cursor currently 
52327     ** points at. This is the right-child if (iIdx==pPage->nCell).
52328     */
52329     iIdx = pCur->aiIdx[pCur->iPage];
52330     if( iIdx==pPage->nCell ){
52331       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
52332     }else{
52333       rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
52334     }
52335   }
52336
52337   /* An error has occurred. Return an error code. */
52338   return rc;
52339 }
52340 #endif
52341
52342 /*
52343 ** Return the pager associated with a BTree.  This routine is used for
52344 ** testing and debugging only.
52345 */
52346 SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
52347   return p->pBt->pPager;
52348 }
52349
52350 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
52351 /*
52352 ** Append a message to the error message string.
52353 */
52354 static void checkAppendMsg(
52355   IntegrityCk *pCheck,
52356   char *zMsg1,
52357   const char *zFormat,
52358   ...
52359 ){
52360   va_list ap;
52361   if( !pCheck->mxErr ) return;
52362   pCheck->mxErr--;
52363   pCheck->nErr++;
52364   va_start(ap, zFormat);
52365   if( pCheck->errMsg.nChar ){
52366     sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
52367   }
52368   if( zMsg1 ){
52369     sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
52370   }
52371   sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
52372   va_end(ap);
52373   if( pCheck->errMsg.mallocFailed ){
52374     pCheck->mallocFailed = 1;
52375   }
52376 }
52377 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
52378
52379 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
52380 /*
52381 ** Add 1 to the reference count for page iPage.  If this is the second
52382 ** reference to the page, add an error message to pCheck->zErrMsg.
52383 ** Return 1 if there are 2 ore more references to the page and 0 if
52384 ** if this is the first reference to the page.
52385 **
52386 ** Also check that the page number is in bounds.
52387 */
52388 static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
52389   if( iPage==0 ) return 1;
52390   if( iPage>pCheck->nPage ){
52391     checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
52392     return 1;
52393   }
52394   if( pCheck->anRef[iPage]==1 ){
52395     checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
52396     return 1;
52397   }
52398   return  (pCheck->anRef[iPage]++)>1;
52399 }
52400
52401 #ifndef SQLITE_OMIT_AUTOVACUUM
52402 /*
52403 ** Check that the entry in the pointer-map for page iChild maps to 
52404 ** page iParent, pointer type ptrType. If not, append an error message
52405 ** to pCheck.
52406 */
52407 static void checkPtrmap(
52408   IntegrityCk *pCheck,   /* Integrity check context */
52409   Pgno iChild,           /* Child page number */
52410   u8 eType,              /* Expected pointer map type */
52411   Pgno iParent,          /* Expected pointer map parent page number */
52412   char *zContext         /* Context description (used for error msg) */
52413 ){
52414   int rc;
52415   u8 ePtrmapType;
52416   Pgno iPtrmapParent;
52417
52418   rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
52419   if( rc!=SQLITE_OK ){
52420     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
52421     checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
52422     return;
52423   }
52424
52425   if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
52426     checkAppendMsg(pCheck, zContext, 
52427       "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)", 
52428       iChild, eType, iParent, ePtrmapType, iPtrmapParent);
52429   }
52430 }
52431 #endif
52432
52433 /*
52434 ** Check the integrity of the freelist or of an overflow page list.
52435 ** Verify that the number of pages on the list is N.
52436 */
52437 static void checkList(
52438   IntegrityCk *pCheck,  /* Integrity checking context */
52439   int isFreeList,       /* True for a freelist.  False for overflow page list */
52440   int iPage,            /* Page number for first page in the list */
52441   int N,                /* Expected number of pages in the list */
52442   char *zContext        /* Context for error messages */
52443 ){
52444   int i;
52445   int expected = N;
52446   int iFirst = iPage;
52447   while( N-- > 0 && pCheck->mxErr ){
52448     DbPage *pOvflPage;
52449     unsigned char *pOvflData;
52450     if( iPage<1 ){
52451       checkAppendMsg(pCheck, zContext,
52452          "%d of %d pages missing from overflow list starting at %d",
52453           N+1, expected, iFirst);
52454       break;
52455     }
52456     if( checkRef(pCheck, iPage, zContext) ) break;
52457     if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
52458       checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
52459       break;
52460     }
52461     pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
52462     if( isFreeList ){
52463       int n = get4byte(&pOvflData[4]);
52464 #ifndef SQLITE_OMIT_AUTOVACUUM
52465       if( pCheck->pBt->autoVacuum ){
52466         checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
52467       }
52468 #endif
52469       if( n>(int)pCheck->pBt->usableSize/4-2 ){
52470         checkAppendMsg(pCheck, zContext,
52471            "freelist leaf count too big on page %d", iPage);
52472         N--;
52473       }else{
52474         for(i=0; i<n; i++){
52475           Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
52476 #ifndef SQLITE_OMIT_AUTOVACUUM
52477           if( pCheck->pBt->autoVacuum ){
52478             checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
52479           }
52480 #endif
52481           checkRef(pCheck, iFreePage, zContext);
52482         }
52483         N -= n;
52484       }
52485     }
52486 #ifndef SQLITE_OMIT_AUTOVACUUM
52487     else{
52488       /* If this database supports auto-vacuum and iPage is not the last
52489       ** page in this overflow list, check that the pointer-map entry for
52490       ** the following page matches iPage.
52491       */
52492       if( pCheck->pBt->autoVacuum && N>0 ){
52493         i = get4byte(pOvflData);
52494         checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
52495       }
52496     }
52497 #endif
52498     iPage = get4byte(pOvflData);
52499     sqlite3PagerUnref(pOvflPage);
52500   }
52501 }
52502 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
52503
52504 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
52505 /*
52506 ** Do various sanity checks on a single page of a tree.  Return
52507 ** the tree depth.  Root pages return 0.  Parents of root pages
52508 ** return 1, and so forth.
52509 ** 
52510 ** These checks are done:
52511 **
52512 **      1.  Make sure that cells and freeblocks do not overlap
52513 **          but combine to completely cover the page.
52514 **  NO  2.  Make sure cell keys are in order.
52515 **  NO  3.  Make sure no key is less than or equal to zLowerBound.
52516 **  NO  4.  Make sure no key is greater than or equal to zUpperBound.
52517 **      5.  Check the integrity of overflow pages.
52518 **      6.  Recursively call checkTreePage on all children.
52519 **      7.  Verify that the depth of all children is the same.
52520 **      8.  Make sure this page is at least 33% full or else it is
52521 **          the root of the tree.
52522 */
52523 static int checkTreePage(
52524   IntegrityCk *pCheck,  /* Context for the sanity check */
52525   int iPage,            /* Page number of the page to check */
52526   char *zParentContext, /* Parent context */
52527   i64 *pnParentMinKey, 
52528   i64 *pnParentMaxKey
52529 ){
52530   MemPage *pPage;
52531   int i, rc, depth, d2, pgno, cnt;
52532   int hdr, cellStart;
52533   int nCell;
52534   u8 *data;
52535   BtShared *pBt;
52536   int usableSize;
52537   char zContext[100];
52538   char *hit = 0;
52539   i64 nMinKey = 0;
52540   i64 nMaxKey = 0;
52541
52542   sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
52543
52544   /* Check that the page exists
52545   */
52546   pBt = pCheck->pBt;
52547   usableSize = pBt->usableSize;
52548   if( iPage==0 ) return 0;
52549   if( checkRef(pCheck, iPage, zParentContext) ) return 0;
52550   if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
52551     checkAppendMsg(pCheck, zContext,
52552        "unable to get the page. error code=%d", rc);
52553     return 0;
52554   }
52555
52556   /* Clear MemPage.isInit to make sure the corruption detection code in
52557   ** btreeInitPage() is executed.  */
52558   pPage->isInit = 0;
52559   if( (rc = btreeInitPage(pPage))!=0 ){
52560     assert( rc==SQLITE_CORRUPT );  /* The only possible error from InitPage */
52561     checkAppendMsg(pCheck, zContext, 
52562                    "btreeInitPage() returns error code %d", rc);
52563     releasePage(pPage);
52564     return 0;
52565   }
52566
52567   /* Check out all the cells.
52568   */
52569   depth = 0;
52570   for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
52571     u8 *pCell;
52572     u32 sz;
52573     CellInfo info;
52574
52575     /* Check payload overflow pages
52576     */
52577     sqlite3_snprintf(sizeof(zContext), zContext,
52578              "On tree page %d cell %d: ", iPage, i);
52579     pCell = findCell(pPage,i);
52580     btreeParseCellPtr(pPage, pCell, &info);
52581     sz = info.nData;
52582     if( !pPage->intKey ) sz += (int)info.nKey;
52583     /* For intKey pages, check that the keys are in order.
52584     */
52585     else if( i==0 ) nMinKey = nMaxKey = info.nKey;
52586     else{
52587       if( info.nKey <= nMaxKey ){
52588         checkAppendMsg(pCheck, zContext, 
52589             "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
52590       }
52591       nMaxKey = info.nKey;
52592     }
52593     assert( sz==info.nPayload );
52594     if( (sz>info.nLocal) 
52595      && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
52596     ){
52597       int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
52598       Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
52599 #ifndef SQLITE_OMIT_AUTOVACUUM
52600       if( pBt->autoVacuum ){
52601         checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
52602       }
52603 #endif
52604       checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
52605     }
52606
52607     /* Check sanity of left child page.
52608     */
52609     if( !pPage->leaf ){
52610       pgno = get4byte(pCell);
52611 #ifndef SQLITE_OMIT_AUTOVACUUM
52612       if( pBt->autoVacuum ){
52613         checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
52614       }
52615 #endif
52616       d2 = checkTreePage(pCheck, pgno, zContext, &nMinKey, i==0 ? NULL : &nMaxKey);
52617       if( i>0 && d2!=depth ){
52618         checkAppendMsg(pCheck, zContext, "Child page depth differs");
52619       }
52620       depth = d2;
52621     }
52622   }
52623
52624   if( !pPage->leaf ){
52625     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
52626     sqlite3_snprintf(sizeof(zContext), zContext, 
52627                      "On page %d at right child: ", iPage);
52628 #ifndef SQLITE_OMIT_AUTOVACUUM
52629     if( pBt->autoVacuum ){
52630       checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
52631     }
52632 #endif
52633     checkTreePage(pCheck, pgno, zContext, NULL, !pPage->nCell ? NULL : &nMaxKey);
52634   }
52635  
52636   /* For intKey leaf pages, check that the min/max keys are in order
52637   ** with any left/parent/right pages.
52638   */
52639   if( pPage->leaf && pPage->intKey ){
52640     /* if we are a left child page */
52641     if( pnParentMinKey ){
52642       /* if we are the left most child page */
52643       if( !pnParentMaxKey ){
52644         if( nMaxKey > *pnParentMinKey ){
52645           checkAppendMsg(pCheck, zContext, 
52646               "Rowid %lld out of order (max larger than parent min of %lld)",
52647               nMaxKey, *pnParentMinKey);
52648         }
52649       }else{
52650         if( nMinKey <= *pnParentMinKey ){
52651           checkAppendMsg(pCheck, zContext, 
52652               "Rowid %lld out of order (min less than parent min of %lld)",
52653               nMinKey, *pnParentMinKey);
52654         }
52655         if( nMaxKey > *pnParentMaxKey ){
52656           checkAppendMsg(pCheck, zContext, 
52657               "Rowid %lld out of order (max larger than parent max of %lld)",
52658               nMaxKey, *pnParentMaxKey);
52659         }
52660         *pnParentMinKey = nMaxKey;
52661       }
52662     /* else if we're a right child page */
52663     } else if( pnParentMaxKey ){
52664       if( nMinKey <= *pnParentMaxKey ){
52665         checkAppendMsg(pCheck, zContext, 
52666             "Rowid %lld out of order (min less than parent max of %lld)",
52667             nMinKey, *pnParentMaxKey);
52668       }
52669     }
52670   }
52671
52672   /* Check for complete coverage of the page
52673   */
52674   data = pPage->aData;
52675   hdr = pPage->hdrOffset;
52676   hit = sqlite3PageMalloc( pBt->pageSize );
52677   if( hit==0 ){
52678     pCheck->mallocFailed = 1;
52679   }else{
52680     int contentOffset = get2byteNotZero(&data[hdr+5]);
52681     assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
52682     memset(hit+contentOffset, 0, usableSize-contentOffset);
52683     memset(hit, 1, contentOffset);
52684     nCell = get2byte(&data[hdr+3]);
52685     cellStart = hdr + 12 - 4*pPage->leaf;
52686     for(i=0; i<nCell; i++){
52687       int pc = get2byte(&data[cellStart+i*2]);
52688       u32 size = 65536;
52689       int j;
52690       if( pc<=usableSize-4 ){
52691         size = cellSizePtr(pPage, &data[pc]);
52692       }
52693       if( (int)(pc+size-1)>=usableSize ){
52694         checkAppendMsg(pCheck, 0, 
52695             "Corruption detected in cell %d on page %d",i,iPage);
52696       }else{
52697         for(j=pc+size-1; j>=pc; j--) hit[j]++;
52698       }
52699     }
52700     i = get2byte(&data[hdr+1]);
52701     while( i>0 ){
52702       int size, j;
52703       assert( i<=usableSize-4 );     /* Enforced by btreeInitPage() */
52704       size = get2byte(&data[i+2]);
52705       assert( i+size<=usableSize );  /* Enforced by btreeInitPage() */
52706       for(j=i+size-1; j>=i; j--) hit[j]++;
52707       j = get2byte(&data[i]);
52708       assert( j==0 || j>i+size );  /* Enforced by btreeInitPage() */
52709       assert( j<=usableSize-4 );   /* Enforced by btreeInitPage() */
52710       i = j;
52711     }
52712     for(i=cnt=0; i<usableSize; i++){
52713       if( hit[i]==0 ){
52714         cnt++;
52715       }else if( hit[i]>1 ){
52716         checkAppendMsg(pCheck, 0,
52717           "Multiple uses for byte %d of page %d", i, iPage);
52718         break;
52719       }
52720     }
52721     if( cnt!=data[hdr+7] ){
52722       checkAppendMsg(pCheck, 0, 
52723           "Fragmentation of %d bytes reported as %d on page %d",
52724           cnt, data[hdr+7], iPage);
52725     }
52726   }
52727   sqlite3PageFree(hit);
52728   releasePage(pPage);
52729   return depth+1;
52730 }
52731 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
52732
52733 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
52734 /*
52735 ** This routine does a complete check of the given BTree file.  aRoot[] is
52736 ** an array of pages numbers were each page number is the root page of
52737 ** a table.  nRoot is the number of entries in aRoot.
52738 **
52739 ** A read-only or read-write transaction must be opened before calling
52740 ** this function.
52741 **
52742 ** Write the number of error seen in *pnErr.  Except for some memory
52743 ** allocation errors,  an error message held in memory obtained from
52744 ** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
52745 ** returned.  If a memory allocation error occurs, NULL is returned.
52746 */
52747 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
52748   Btree *p,     /* The btree to be checked */
52749   int *aRoot,   /* An array of root pages numbers for individual trees */
52750   int nRoot,    /* Number of entries in aRoot[] */
52751   int mxErr,    /* Stop reporting errors after this many */
52752   int *pnErr    /* Write number of errors seen to this variable */
52753 ){
52754   Pgno i;
52755   int nRef;
52756   IntegrityCk sCheck;
52757   BtShared *pBt = p->pBt;
52758   char zErr[100];
52759
52760   sqlite3BtreeEnter(p);
52761   assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
52762   nRef = sqlite3PagerRefcount(pBt->pPager);
52763   sCheck.pBt = pBt;
52764   sCheck.pPager = pBt->pPager;
52765   sCheck.nPage = btreePagecount(sCheck.pBt);
52766   sCheck.mxErr = mxErr;
52767   sCheck.nErr = 0;
52768   sCheck.mallocFailed = 0;
52769   *pnErr = 0;
52770   if( sCheck.nPage==0 ){
52771     sqlite3BtreeLeave(p);
52772     return 0;
52773   }
52774   sCheck.anRef = sqlite3Malloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
52775   if( !sCheck.anRef ){
52776     *pnErr = 1;
52777     sqlite3BtreeLeave(p);
52778     return 0;
52779   }
52780   for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
52781   i = PENDING_BYTE_PAGE(pBt);
52782   if( i<=sCheck.nPage ){
52783     sCheck.anRef[i] = 1;
52784   }
52785   sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), 20000);
52786   sCheck.errMsg.useMalloc = 2;
52787
52788   /* Check the integrity of the freelist
52789   */
52790   checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
52791             get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
52792
52793   /* Check all the tables.
52794   */
52795   for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
52796     if( aRoot[i]==0 ) continue;
52797 #ifndef SQLITE_OMIT_AUTOVACUUM
52798     if( pBt->autoVacuum && aRoot[i]>1 ){
52799       checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
52800     }
52801 #endif
52802     checkTreePage(&sCheck, aRoot[i], "List of tree roots: ", NULL, NULL);
52803   }
52804
52805   /* Make sure every page in the file is referenced
52806   */
52807   for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
52808 #ifdef SQLITE_OMIT_AUTOVACUUM
52809     if( sCheck.anRef[i]==0 ){
52810       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
52811     }
52812 #else
52813     /* If the database supports auto-vacuum, make sure no tables contain
52814     ** references to pointer-map pages.
52815     */
52816     if( sCheck.anRef[i]==0 && 
52817        (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
52818       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
52819     }
52820     if( sCheck.anRef[i]!=0 && 
52821        (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
52822       checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
52823     }
52824 #endif
52825   }
52826
52827   /* Make sure this analysis did not leave any unref() pages.
52828   ** This is an internal consistency check; an integrity check
52829   ** of the integrity check.
52830   */
52831   if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
52832     checkAppendMsg(&sCheck, 0, 
52833       "Outstanding page count goes from %d to %d during this analysis",
52834       nRef, sqlite3PagerRefcount(pBt->pPager)
52835     );
52836   }
52837
52838   /* Clean  up and report errors.
52839   */
52840   sqlite3BtreeLeave(p);
52841   sqlite3_free(sCheck.anRef);
52842   if( sCheck.mallocFailed ){
52843     sqlite3StrAccumReset(&sCheck.errMsg);
52844     *pnErr = sCheck.nErr+1;
52845     return 0;
52846   }
52847   *pnErr = sCheck.nErr;
52848   if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
52849   return sqlite3StrAccumFinish(&sCheck.errMsg);
52850 }
52851 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
52852
52853 /*
52854 ** Return the full pathname of the underlying database file.
52855 **
52856 ** The pager filename is invariant as long as the pager is
52857 ** open so it is safe to access without the BtShared mutex.
52858 */
52859 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
52860   assert( p->pBt->pPager!=0 );
52861   return sqlite3PagerFilename(p->pBt->pPager);
52862 }
52863
52864 /*
52865 ** Return the pathname of the journal file for this database. The return
52866 ** value of this routine is the same regardless of whether the journal file
52867 ** has been created or not.
52868 **
52869 ** The pager journal filename is invariant as long as the pager is
52870 ** open so it is safe to access without the BtShared mutex.
52871 */
52872 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
52873   assert( p->pBt->pPager!=0 );
52874   return sqlite3PagerJournalname(p->pBt->pPager);
52875 }
52876
52877 /*
52878 ** Return non-zero if a transaction is active.
52879 */
52880 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
52881   assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
52882   return (p && (p->inTrans==TRANS_WRITE));
52883 }
52884
52885 #ifndef SQLITE_OMIT_WAL
52886 /*
52887 ** Run a checkpoint on the Btree passed as the first argument.
52888 **
52889 ** Return SQLITE_LOCKED if this or any other connection has an open 
52890 ** transaction on the shared-cache the argument Btree is connected to.
52891 */
52892 SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p){
52893   int rc = SQLITE_OK;
52894   if( p ){
52895     BtShared *pBt = p->pBt;
52896     sqlite3BtreeEnter(p);
52897     if( pBt->inTransaction!=TRANS_NONE ){
52898       rc = SQLITE_LOCKED;
52899     }else{
52900       rc = sqlite3PagerCheckpoint(pBt->pPager);
52901     }
52902     sqlite3BtreeLeave(p);
52903   }
52904   return rc;
52905 }
52906 #endif
52907
52908 /*
52909 ** Return non-zero if a read (or write) transaction is active.
52910 */
52911 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
52912   assert( p );
52913   assert( sqlite3_mutex_held(p->db->mutex) );
52914   return p->inTrans!=TRANS_NONE;
52915 }
52916
52917 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
52918   assert( p );
52919   assert( sqlite3_mutex_held(p->db->mutex) );
52920   return p->nBackup!=0;
52921 }
52922
52923 /*
52924 ** This function returns a pointer to a blob of memory associated with
52925 ** a single shared-btree. The memory is used by client code for its own
52926 ** purposes (for example, to store a high-level schema associated with 
52927 ** the shared-btree). The btree layer manages reference counting issues.
52928 **
52929 ** The first time this is called on a shared-btree, nBytes bytes of memory
52930 ** are allocated, zeroed, and returned to the caller. For each subsequent 
52931 ** call the nBytes parameter is ignored and a pointer to the same blob
52932 ** of memory returned. 
52933 **
52934 ** If the nBytes parameter is 0 and the blob of memory has not yet been
52935 ** allocated, a null pointer is returned. If the blob has already been
52936 ** allocated, it is returned as normal.
52937 **
52938 ** Just before the shared-btree is closed, the function passed as the 
52939 ** xFree argument when the memory allocation was made is invoked on the 
52940 ** blob of allocated memory. This function should not call sqlite3_free()
52941 ** on the memory, the btree layer does that.
52942 */
52943 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
52944   BtShared *pBt = p->pBt;
52945   sqlite3BtreeEnter(p);
52946   if( !pBt->pSchema && nBytes ){
52947     pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
52948     pBt->xFreeSchema = xFree;
52949   }
52950   sqlite3BtreeLeave(p);
52951   return pBt->pSchema;
52952 }
52953
52954 /*
52955 ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared 
52956 ** btree as the argument handle holds an exclusive lock on the 
52957 ** sqlite_master table. Otherwise SQLITE_OK.
52958 */
52959 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
52960   int rc;
52961   assert( sqlite3_mutex_held(p->db->mutex) );
52962   sqlite3BtreeEnter(p);
52963   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
52964   assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
52965   sqlite3BtreeLeave(p);
52966   return rc;
52967 }
52968
52969
52970 #ifndef SQLITE_OMIT_SHARED_CACHE
52971 /*
52972 ** Obtain a lock on the table whose root page is iTab.  The
52973 ** lock is a write lock if isWritelock is true or a read lock
52974 ** if it is false.
52975 */
52976 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
52977   int rc = SQLITE_OK;
52978   assert( p->inTrans!=TRANS_NONE );
52979   if( p->sharable ){
52980     u8 lockType = READ_LOCK + isWriteLock;
52981     assert( READ_LOCK+1==WRITE_LOCK );
52982     assert( isWriteLock==0 || isWriteLock==1 );
52983
52984     sqlite3BtreeEnter(p);
52985     rc = querySharedCacheTableLock(p, iTab, lockType);
52986     if( rc==SQLITE_OK ){
52987       rc = setSharedCacheTableLock(p, iTab, lockType);
52988     }
52989     sqlite3BtreeLeave(p);
52990   }
52991   return rc;
52992 }
52993 #endif
52994
52995 #ifndef SQLITE_OMIT_INCRBLOB
52996 /*
52997 ** Argument pCsr must be a cursor opened for writing on an 
52998 ** INTKEY table currently pointing at a valid table entry. 
52999 ** This function modifies the data stored as part of that entry.
53000 **
53001 ** Only the data content may only be modified, it is not possible to 
53002 ** change the length of the data stored. If this function is called with
53003 ** parameters that attempt to write past the end of the existing data,
53004 ** no modifications are made and SQLITE_CORRUPT is returned.
53005 */
53006 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
53007   int rc;
53008   assert( cursorHoldsMutex(pCsr) );
53009   assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
53010   assert( pCsr->isIncrblobHandle );
53011
53012   rc = restoreCursorPosition(pCsr);
53013   if( rc!=SQLITE_OK ){
53014     return rc;
53015   }
53016   assert( pCsr->eState!=CURSOR_REQUIRESEEK );
53017   if( pCsr->eState!=CURSOR_VALID ){
53018     return SQLITE_ABORT;
53019   }
53020
53021   /* Check some assumptions: 
53022   **   (a) the cursor is open for writing,
53023   **   (b) there is a read/write transaction open,
53024   **   (c) the connection holds a write-lock on the table (if required),
53025   **   (d) there are no conflicting read-locks, and
53026   **   (e) the cursor points at a valid row of an intKey table.
53027   */
53028   if( !pCsr->wrFlag ){
53029     return SQLITE_READONLY;
53030   }
53031   assert( !pCsr->pBt->readOnly && pCsr->pBt->inTransaction==TRANS_WRITE );
53032   assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
53033   assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
53034   assert( pCsr->apPage[pCsr->iPage]->intKey );
53035
53036   return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
53037 }
53038
53039 /* 
53040 ** Set a flag on this cursor to cache the locations of pages from the 
53041 ** overflow list for the current row. This is used by cursors opened
53042 ** for incremental blob IO only.
53043 **
53044 ** This function sets a flag only. The actual page location cache
53045 ** (stored in BtCursor.aOverflow[]) is allocated and used by function
53046 ** accessPayload() (the worker function for sqlite3BtreeData() and
53047 ** sqlite3BtreePutData()).
53048 */
53049 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *pCur){
53050   assert( cursorHoldsMutex(pCur) );
53051   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
53052   assert(!pCur->isIncrblobHandle);
53053   assert(!pCur->aOverflow);
53054   pCur->isIncrblobHandle = 1;
53055 }
53056 #endif
53057
53058 /*
53059 ** Set both the "read version" (single byte at byte offset 18) and 
53060 ** "write version" (single byte at byte offset 19) fields in the database
53061 ** header to iVersion.
53062 */
53063 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
53064   BtShared *pBt = pBtree->pBt;
53065   int rc;                         /* Return code */
53066  
53067   assert( pBtree->inTrans==TRANS_NONE );
53068   assert( iVersion==1 || iVersion==2 );
53069
53070   /* If setting the version fields to 1, do not automatically open the
53071   ** WAL connection, even if the version fields are currently set to 2.
53072   */
53073   pBt->doNotUseWAL = (u8)(iVersion==1);
53074
53075   rc = sqlite3BtreeBeginTrans(pBtree, 0);
53076   if( rc==SQLITE_OK ){
53077     u8 *aData = pBt->pPage1->aData;
53078     if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
53079       rc = sqlite3BtreeBeginTrans(pBtree, 2);
53080       if( rc==SQLITE_OK ){
53081         rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
53082         if( rc==SQLITE_OK ){
53083           aData[18] = (u8)iVersion;
53084           aData[19] = (u8)iVersion;
53085         }
53086       }
53087     }
53088   }
53089
53090   pBt->doNotUseWAL = 0;
53091   return rc;
53092 }
53093
53094 /************** End of btree.c ***********************************************/
53095 /************** Begin file backup.c ******************************************/
53096 /*
53097 ** 2009 January 28
53098 **
53099 ** The author disclaims copyright to this source code.  In place of
53100 ** a legal notice, here is a blessing:
53101 **
53102 **    May you do good and not evil.
53103 **    May you find forgiveness for yourself and forgive others.
53104 **    May you share freely, never taking more than you give.
53105 **
53106 *************************************************************************
53107 ** This file contains the implementation of the sqlite3_backup_XXX() 
53108 ** API functions and the related features.
53109 */
53110
53111 /* Macro to find the minimum of two numeric values.
53112 */
53113 #ifndef MIN
53114 # define MIN(x,y) ((x)<(y)?(x):(y))
53115 #endif
53116
53117 /*
53118 ** Structure allocated for each backup operation.
53119 */
53120 struct sqlite3_backup {
53121   sqlite3* pDestDb;        /* Destination database handle */
53122   Btree *pDest;            /* Destination b-tree file */
53123   u32 iDestSchema;         /* Original schema cookie in destination */
53124   int bDestLocked;         /* True once a write-transaction is open on pDest */
53125
53126   Pgno iNext;              /* Page number of the next source page to copy */
53127   sqlite3* pSrcDb;         /* Source database handle */
53128   Btree *pSrc;             /* Source b-tree file */
53129
53130   int rc;                  /* Backup process error code */
53131
53132   /* These two variables are set by every call to backup_step(). They are
53133   ** read by calls to backup_remaining() and backup_pagecount().
53134   */
53135   Pgno nRemaining;         /* Number of pages left to copy */
53136   Pgno nPagecount;         /* Total number of pages to copy */
53137
53138   int isAttached;          /* True once backup has been registered with pager */
53139   sqlite3_backup *pNext;   /* Next backup associated with source pager */
53140 };
53141
53142 /*
53143 ** THREAD SAFETY NOTES:
53144 **
53145 **   Once it has been created using backup_init(), a single sqlite3_backup
53146 **   structure may be accessed via two groups of thread-safe entry points:
53147 **
53148 **     * Via the sqlite3_backup_XXX() API function backup_step() and 
53149 **       backup_finish(). Both these functions obtain the source database
53150 **       handle mutex and the mutex associated with the source BtShared 
53151 **       structure, in that order.
53152 **
53153 **     * Via the BackupUpdate() and BackupRestart() functions, which are
53154 **       invoked by the pager layer to report various state changes in
53155 **       the page cache associated with the source database. The mutex
53156 **       associated with the source database BtShared structure will always 
53157 **       be held when either of these functions are invoked.
53158 **
53159 **   The other sqlite3_backup_XXX() API functions, backup_remaining() and
53160 **   backup_pagecount() are not thread-safe functions. If they are called
53161 **   while some other thread is calling backup_step() or backup_finish(),
53162 **   the values returned may be invalid. There is no way for a call to
53163 **   BackupUpdate() or BackupRestart() to interfere with backup_remaining()
53164 **   or backup_pagecount().
53165 **
53166 **   Depending on the SQLite configuration, the database handles and/or
53167 **   the Btree objects may have their own mutexes that require locking.
53168 **   Non-sharable Btrees (in-memory databases for example), do not have
53169 **   associated mutexes.
53170 */
53171
53172 /*
53173 ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
53174 ** in connection handle pDb. If such a database cannot be found, return
53175 ** a NULL pointer and write an error message to pErrorDb.
53176 **
53177 ** If the "temp" database is requested, it may need to be opened by this 
53178 ** function. If an error occurs while doing so, return 0 and write an 
53179 ** error message to pErrorDb.
53180 */
53181 static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
53182   int i = sqlite3FindDbName(pDb, zDb);
53183
53184   if( i==1 ){
53185     Parse *pParse;
53186     int rc = 0;
53187     pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
53188     if( pParse==0 ){
53189       sqlite3Error(pErrorDb, SQLITE_NOMEM, "out of memory");
53190       rc = SQLITE_NOMEM;
53191     }else{
53192       pParse->db = pDb;
53193       if( sqlite3OpenTempDatabase(pParse) ){
53194         sqlite3Error(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
53195         rc = SQLITE_ERROR;
53196       }
53197       sqlite3DbFree(pErrorDb, pParse->zErrMsg);
53198       sqlite3StackFree(pErrorDb, pParse);
53199     }
53200     if( rc ){
53201       return 0;
53202     }
53203   }
53204
53205   if( i<0 ){
53206     sqlite3Error(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
53207     return 0;
53208   }
53209
53210   return pDb->aDb[i].pBt;
53211 }
53212
53213 /*
53214 ** Create an sqlite3_backup process to copy the contents of zSrcDb from
53215 ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
53216 ** a pointer to the new sqlite3_backup object.
53217 **
53218 ** If an error occurs, NULL is returned and an error code and error message
53219 ** stored in database handle pDestDb.
53220 */
53221 SQLITE_API sqlite3_backup *sqlite3_backup_init(
53222   sqlite3* pDestDb,                     /* Database to write to */
53223   const char *zDestDb,                  /* Name of database within pDestDb */
53224   sqlite3* pSrcDb,                      /* Database connection to read from */
53225   const char *zSrcDb                    /* Name of database within pSrcDb */
53226 ){
53227   sqlite3_backup *p;                    /* Value to return */
53228
53229   /* Lock the source database handle. The destination database
53230   ** handle is not locked in this routine, but it is locked in
53231   ** sqlite3_backup_step(). The user is required to ensure that no
53232   ** other thread accesses the destination handle for the duration
53233   ** of the backup operation.  Any attempt to use the destination
53234   ** database connection while a backup is in progress may cause
53235   ** a malfunction or a deadlock.
53236   */
53237   sqlite3_mutex_enter(pSrcDb->mutex);
53238   sqlite3_mutex_enter(pDestDb->mutex);
53239
53240   if( pSrcDb==pDestDb ){
53241     sqlite3Error(
53242         pDestDb, SQLITE_ERROR, "source and destination must be distinct"
53243     );
53244     p = 0;
53245   }else {
53246     /* Allocate space for a new sqlite3_backup object...
53247     ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
53248     ** call to sqlite3_backup_init() and is destroyed by a call to
53249     ** sqlite3_backup_finish(). */
53250     p = (sqlite3_backup *)sqlite3_malloc(sizeof(sqlite3_backup));
53251     if( !p ){
53252       sqlite3Error(pDestDb, SQLITE_NOMEM, 0);
53253     }
53254   }
53255
53256   /* If the allocation succeeded, populate the new object. */
53257   if( p ){
53258     memset(p, 0, sizeof(sqlite3_backup));
53259     p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
53260     p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
53261     p->pDestDb = pDestDb;
53262     p->pSrcDb = pSrcDb;
53263     p->iNext = 1;
53264     p->isAttached = 0;
53265
53266     if( 0==p->pSrc || 0==p->pDest ){
53267       /* One (or both) of the named databases did not exist. An error has
53268       ** already been written into the pDestDb handle. All that is left
53269       ** to do here is free the sqlite3_backup structure.
53270       */
53271       sqlite3_free(p);
53272       p = 0;
53273     }
53274   }
53275   if( p ){
53276     p->pSrc->nBackup++;
53277   }
53278
53279   sqlite3_mutex_leave(pDestDb->mutex);
53280   sqlite3_mutex_leave(pSrcDb->mutex);
53281   return p;
53282 }
53283
53284 /*
53285 ** Argument rc is an SQLite error code. Return true if this error is 
53286 ** considered fatal if encountered during a backup operation. All errors
53287 ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
53288 */
53289 static int isFatalError(int rc){
53290   return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
53291 }
53292
53293 /*
53294 ** Parameter zSrcData points to a buffer containing the data for 
53295 ** page iSrcPg from the source database. Copy this data into the 
53296 ** destination database.
53297 */
53298 static int backupOnePage(sqlite3_backup *p, Pgno iSrcPg, const u8 *zSrcData){
53299   Pager * const pDestPager = sqlite3BtreePager(p->pDest);
53300   const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
53301   int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
53302   const int nCopy = MIN(nSrcPgsz, nDestPgsz);
53303   const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
53304
53305   int rc = SQLITE_OK;
53306   i64 iOff;
53307
53308   assert( p->bDestLocked );
53309   assert( !isFatalError(p->rc) );
53310   assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
53311   assert( zSrcData );
53312
53313   /* Catch the case where the destination is an in-memory database and the
53314   ** page sizes of the source and destination differ. 
53315   */
53316   if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
53317     rc = SQLITE_READONLY;
53318   }
53319
53320 #ifdef SQLITE_HAS_CODEC
53321   /* Backup is not possible if the page size of the destination is changing
53322   ** a a codec is in use.
53323   */
53324   if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
53325     rc = SQLITE_READONLY;
53326   }
53327 #endif
53328
53329   /* This loop runs once for each destination page spanned by the source 
53330   ** page. For each iteration, variable iOff is set to the byte offset
53331   ** of the destination page.
53332   */
53333   for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
53334     DbPage *pDestPg = 0;
53335     Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
53336     if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
53337     if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
53338      && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
53339     ){
53340       const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
53341       u8 *zDestData = sqlite3PagerGetData(pDestPg);
53342       u8 *zOut = &zDestData[iOff%nDestPgsz];
53343
53344       /* Copy the data from the source page into the destination page.
53345       ** Then clear the Btree layer MemPage.isInit flag. Both this module
53346       ** and the pager code use this trick (clearing the first byte
53347       ** of the page 'extra' space to invalidate the Btree layers
53348       ** cached parse of the page). MemPage.isInit is marked 
53349       ** "MUST BE FIRST" for this purpose.
53350       */
53351       memcpy(zOut, zIn, nCopy);
53352       ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
53353     }
53354     sqlite3PagerUnref(pDestPg);
53355   }
53356
53357   return rc;
53358 }
53359
53360 /*
53361 ** If pFile is currently larger than iSize bytes, then truncate it to
53362 ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
53363 ** this function is a no-op.
53364 **
53365 ** Return SQLITE_OK if everything is successful, or an SQLite error 
53366 ** code if an error occurs.
53367 */
53368 static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
53369   i64 iCurrent;
53370   int rc = sqlite3OsFileSize(pFile, &iCurrent);
53371   if( rc==SQLITE_OK && iCurrent>iSize ){
53372     rc = sqlite3OsTruncate(pFile, iSize);
53373   }
53374   return rc;
53375 }
53376
53377 /*
53378 ** Register this backup object with the associated source pager for
53379 ** callbacks when pages are changed or the cache invalidated.
53380 */
53381 static void attachBackupObject(sqlite3_backup *p){
53382   sqlite3_backup **pp;
53383   assert( sqlite3BtreeHoldsMutex(p->pSrc) );
53384   pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
53385   p->pNext = *pp;
53386   *pp = p;
53387   p->isAttached = 1;
53388 }
53389
53390 /*
53391 ** Copy nPage pages from the source b-tree to the destination.
53392 */
53393 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
53394   int rc;
53395   int destMode;       /* Destination journal mode */
53396   int pgszSrc = 0;    /* Source page size */
53397   int pgszDest = 0;   /* Destination page size */
53398
53399   sqlite3_mutex_enter(p->pSrcDb->mutex);
53400   sqlite3BtreeEnter(p->pSrc);
53401   if( p->pDestDb ){
53402     sqlite3_mutex_enter(p->pDestDb->mutex);
53403   }
53404
53405   rc = p->rc;
53406   if( !isFatalError(rc) ){
53407     Pager * const pSrcPager = sqlite3BtreePager(p->pSrc);     /* Source pager */
53408     Pager * const pDestPager = sqlite3BtreePager(p->pDest);   /* Dest pager */
53409     int ii;                            /* Iterator variable */
53410     int nSrcPage = -1;                 /* Size of source db in pages */
53411     int bCloseTrans = 0;               /* True if src db requires unlocking */
53412
53413     /* If the source pager is currently in a write-transaction, return
53414     ** SQLITE_BUSY immediately.
53415     */
53416     if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
53417       rc = SQLITE_BUSY;
53418     }else{
53419       rc = SQLITE_OK;
53420     }
53421
53422     /* Lock the destination database, if it is not locked already. */
53423     if( SQLITE_OK==rc && p->bDestLocked==0
53424      && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2)) 
53425     ){
53426       p->bDestLocked = 1;
53427       sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
53428     }
53429
53430     /* If there is no open read-transaction on the source database, open
53431     ** one now. If a transaction is opened here, then it will be closed
53432     ** before this function exits.
53433     */
53434     if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
53435       rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
53436       bCloseTrans = 1;
53437     }
53438
53439     /* Do not allow backup if the destination database is in WAL mode
53440     ** and the page sizes are different between source and destination */
53441     pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
53442     pgszDest = sqlite3BtreeGetPageSize(p->pDest);
53443     destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
53444     if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
53445       rc = SQLITE_READONLY;
53446     }
53447   
53448     /* Now that there is a read-lock on the source database, query the
53449     ** source pager for the number of pages in the database.
53450     */
53451     nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
53452     assert( nSrcPage>=0 );
53453     for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
53454       const Pgno iSrcPg = p->iNext;                 /* Source page number */
53455       if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
53456         DbPage *pSrcPg;                             /* Source page object */
53457         rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
53458         if( rc==SQLITE_OK ){
53459           rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg));
53460           sqlite3PagerUnref(pSrcPg);
53461         }
53462       }
53463       p->iNext++;
53464     }
53465     if( rc==SQLITE_OK ){
53466       p->nPagecount = nSrcPage;
53467       p->nRemaining = nSrcPage+1-p->iNext;
53468       if( p->iNext>(Pgno)nSrcPage ){
53469         rc = SQLITE_DONE;
53470       }else if( !p->isAttached ){
53471         attachBackupObject(p);
53472       }
53473     }
53474   
53475     /* Update the schema version field in the destination database. This
53476     ** is to make sure that the schema-version really does change in
53477     ** the case where the source and destination databases have the
53478     ** same schema version.
53479     */
53480     if( rc==SQLITE_DONE 
53481      && (rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1))==SQLITE_OK
53482     ){
53483       int nDestTruncate;
53484   
53485       if( p->pDestDb ){
53486         sqlite3ResetInternalSchema(p->pDestDb, 0);
53487       }
53488
53489       /* Set nDestTruncate to the final number of pages in the destination
53490       ** database. The complication here is that the destination page
53491       ** size may be different to the source page size. 
53492       **
53493       ** If the source page size is smaller than the destination page size, 
53494       ** round up. In this case the call to sqlite3OsTruncate() below will
53495       ** fix the size of the file. However it is important to call
53496       ** sqlite3PagerTruncateImage() here so that any pages in the 
53497       ** destination file that lie beyond the nDestTruncate page mark are
53498       ** journalled by PagerCommitPhaseOne() before they are destroyed
53499       ** by the file truncation.
53500       */
53501       assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
53502       assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
53503       if( pgszSrc<pgszDest ){
53504         int ratio = pgszDest/pgszSrc;
53505         nDestTruncate = (nSrcPage+ratio-1)/ratio;
53506         if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
53507           nDestTruncate--;
53508         }
53509       }else{
53510         nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
53511       }
53512       sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
53513
53514       if( pgszSrc<pgszDest ){
53515         /* If the source page-size is smaller than the destination page-size,
53516         ** two extra things may need to happen:
53517         **
53518         **   * The destination may need to be truncated, and
53519         **
53520         **   * Data stored on the pages immediately following the 
53521         **     pending-byte page in the source database may need to be
53522         **     copied into the destination database.
53523         */
53524         const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
53525         sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
53526
53527         assert( pFile );
53528         assert( (i64)nDestTruncate*(i64)pgszDest >= iSize || (
53529               nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
53530            && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
53531         ));
53532         if( SQLITE_OK==(rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1))
53533          && SQLITE_OK==(rc = backupTruncateFile(pFile, iSize))
53534          && SQLITE_OK==(rc = sqlite3PagerSync(pDestPager))
53535         ){
53536           i64 iOff;
53537           i64 iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
53538           for(
53539             iOff=PENDING_BYTE+pgszSrc; 
53540             rc==SQLITE_OK && iOff<iEnd; 
53541             iOff+=pgszSrc
53542           ){
53543             PgHdr *pSrcPg = 0;
53544             const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
53545             rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
53546             if( rc==SQLITE_OK ){
53547               u8 *zData = sqlite3PagerGetData(pSrcPg);
53548               rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
53549             }
53550             sqlite3PagerUnref(pSrcPg);
53551           }
53552         }
53553       }else{
53554         rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
53555       }
53556   
53557       /* Finish committing the transaction to the destination database. */
53558       if( SQLITE_OK==rc
53559        && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest))
53560       ){
53561         rc = SQLITE_DONE;
53562       }
53563     }
53564   
53565     /* If bCloseTrans is true, then this function opened a read transaction
53566     ** on the source database. Close the read transaction here. There is
53567     ** no need to check the return values of the btree methods here, as
53568     ** "committing" a read-only transaction cannot fail.
53569     */
53570     if( bCloseTrans ){
53571       TESTONLY( int rc2 );
53572       TESTONLY( rc2  = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
53573       TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc);
53574       assert( rc2==SQLITE_OK );
53575     }
53576   
53577     if( rc==SQLITE_IOERR_NOMEM ){
53578       rc = SQLITE_NOMEM;
53579     }
53580     p->rc = rc;
53581   }
53582   if( p->pDestDb ){
53583     sqlite3_mutex_leave(p->pDestDb->mutex);
53584   }
53585   sqlite3BtreeLeave(p->pSrc);
53586   sqlite3_mutex_leave(p->pSrcDb->mutex);
53587   return rc;
53588 }
53589
53590 /*
53591 ** Release all resources associated with an sqlite3_backup* handle.
53592 */
53593 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
53594   sqlite3_backup **pp;                 /* Ptr to head of pagers backup list */
53595   sqlite3_mutex *mutex;                /* Mutex to protect source database */
53596   int rc;                              /* Value to return */
53597
53598   /* Enter the mutexes */
53599   if( p==0 ) return SQLITE_OK;
53600   sqlite3_mutex_enter(p->pSrcDb->mutex);
53601   sqlite3BtreeEnter(p->pSrc);
53602   mutex = p->pSrcDb->mutex;
53603   if( p->pDestDb ){
53604     sqlite3_mutex_enter(p->pDestDb->mutex);
53605   }
53606
53607   /* Detach this backup from the source pager. */
53608   if( p->pDestDb ){
53609     p->pSrc->nBackup--;
53610   }
53611   if( p->isAttached ){
53612     pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
53613     while( *pp!=p ){
53614       pp = &(*pp)->pNext;
53615     }
53616     *pp = p->pNext;
53617   }
53618
53619   /* If a transaction is still open on the Btree, roll it back. */
53620   sqlite3BtreeRollback(p->pDest);
53621
53622   /* Set the error code of the destination database handle. */
53623   rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
53624   sqlite3Error(p->pDestDb, rc, 0);
53625
53626   /* Exit the mutexes and free the backup context structure. */
53627   if( p->pDestDb ){
53628     sqlite3_mutex_leave(p->pDestDb->mutex);
53629   }
53630   sqlite3BtreeLeave(p->pSrc);
53631   if( p->pDestDb ){
53632     /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
53633     ** call to sqlite3_backup_init() and is destroyed by a call to
53634     ** sqlite3_backup_finish(). */
53635     sqlite3_free(p);
53636   }
53637   sqlite3_mutex_leave(mutex);
53638   return rc;
53639 }
53640
53641 /*
53642 ** Return the number of pages still to be backed up as of the most recent
53643 ** call to sqlite3_backup_step().
53644 */
53645 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
53646   return p->nRemaining;
53647 }
53648
53649 /*
53650 ** Return the total number of pages in the source database as of the most 
53651 ** recent call to sqlite3_backup_step().
53652 */
53653 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
53654   return p->nPagecount;
53655 }
53656
53657 /*
53658 ** This function is called after the contents of page iPage of the
53659 ** source database have been modified. If page iPage has already been 
53660 ** copied into the destination database, then the data written to the
53661 ** destination is now invalidated. The destination copy of iPage needs
53662 ** to be updated with the new data before the backup operation is
53663 ** complete.
53664 **
53665 ** It is assumed that the mutex associated with the BtShared object
53666 ** corresponding to the source database is held when this function is
53667 ** called.
53668 */
53669 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
53670   sqlite3_backup *p;                   /* Iterator variable */
53671   for(p=pBackup; p; p=p->pNext){
53672     assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
53673     if( !isFatalError(p->rc) && iPage<p->iNext ){
53674       /* The backup process p has already copied page iPage. But now it
53675       ** has been modified by a transaction on the source pager. Copy
53676       ** the new data into the backup.
53677       */
53678       int rc = backupOnePage(p, iPage, aData);
53679       assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
53680       if( rc!=SQLITE_OK ){
53681         p->rc = rc;
53682       }
53683     }
53684   }
53685 }
53686
53687 /*
53688 ** Restart the backup process. This is called when the pager layer
53689 ** detects that the database has been modified by an external database
53690 ** connection. In this case there is no way of knowing which of the
53691 ** pages that have been copied into the destination database are still 
53692 ** valid and which are not, so the entire process needs to be restarted.
53693 **
53694 ** It is assumed that the mutex associated with the BtShared object
53695 ** corresponding to the source database is held when this function is
53696 ** called.
53697 */
53698 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
53699   sqlite3_backup *p;                   /* Iterator variable */
53700   for(p=pBackup; p; p=p->pNext){
53701     assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
53702     p->iNext = 1;
53703   }
53704 }
53705
53706 #ifndef SQLITE_OMIT_VACUUM
53707 /*
53708 ** Copy the complete content of pBtFrom into pBtTo.  A transaction
53709 ** must be active for both files.
53710 **
53711 ** The size of file pTo may be reduced by this operation. If anything 
53712 ** goes wrong, the transaction on pTo is rolled back. If successful, the 
53713 ** transaction is committed before returning.
53714 */
53715 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
53716   int rc;
53717   sqlite3_backup b;
53718   sqlite3BtreeEnter(pTo);
53719   sqlite3BtreeEnter(pFrom);
53720
53721   /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
53722   ** to 0. This is used by the implementations of sqlite3_backup_step()
53723   ** and sqlite3_backup_finish() to detect that they are being called
53724   ** from this function, not directly by the user.
53725   */
53726   memset(&b, 0, sizeof(b));
53727   b.pSrcDb = pFrom->db;
53728   b.pSrc = pFrom;
53729   b.pDest = pTo;
53730   b.iNext = 1;
53731
53732   /* 0x7FFFFFFF is the hard limit for the number of pages in a database
53733   ** file. By passing this as the number of pages to copy to
53734   ** sqlite3_backup_step(), we can guarantee that the copy finishes 
53735   ** within a single call (unless an error occurs). The assert() statement
53736   ** checks this assumption - (p->rc) should be set to either SQLITE_DONE 
53737   ** or an error code.
53738   */
53739   sqlite3_backup_step(&b, 0x7FFFFFFF);
53740   assert( b.rc!=SQLITE_OK );
53741   rc = sqlite3_backup_finish(&b);
53742   if( rc==SQLITE_OK ){
53743     pTo->pBt->pageSizeFixed = 0;
53744   }
53745
53746   sqlite3BtreeLeave(pFrom);
53747   sqlite3BtreeLeave(pTo);
53748   return rc;
53749 }
53750 #endif /* SQLITE_OMIT_VACUUM */
53751
53752 /************** End of backup.c **********************************************/
53753 /************** Begin file vdbemem.c *****************************************/
53754 /*
53755 ** 2004 May 26
53756 **
53757 ** The author disclaims copyright to this source code.  In place of
53758 ** a legal notice, here is a blessing:
53759 **
53760 **    May you do good and not evil.
53761 **    May you find forgiveness for yourself and forgive others.
53762 **    May you share freely, never taking more than you give.
53763 **
53764 *************************************************************************
53765 **
53766 ** This file contains code use to manipulate "Mem" structure.  A "Mem"
53767 ** stores a single value in the VDBE.  Mem is an opaque structure visible
53768 ** only within the VDBE.  Interface routines refer to a Mem using the
53769 ** name sqlite_value
53770 */
53771
53772 /*
53773 ** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
53774 ** P if required.
53775 */
53776 #define expandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
53777
53778 /*
53779 ** If pMem is an object with a valid string representation, this routine
53780 ** ensures the internal encoding for the string representation is
53781 ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
53782 **
53783 ** If pMem is not a string object, or the encoding of the string
53784 ** representation is already stored using the requested encoding, then this
53785 ** routine is a no-op.
53786 **
53787 ** SQLITE_OK is returned if the conversion is successful (or not required).
53788 ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
53789 ** between formats.
53790 */
53791 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
53792   int rc;
53793   assert( (pMem->flags&MEM_RowSet)==0 );
53794   assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
53795            || desiredEnc==SQLITE_UTF16BE );
53796   if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
53797     return SQLITE_OK;
53798   }
53799   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
53800 #ifdef SQLITE_OMIT_UTF16
53801   return SQLITE_ERROR;
53802 #else
53803
53804   /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
53805   ** then the encoding of the value may not have changed.
53806   */
53807   rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
53808   assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
53809   assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);
53810   assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
53811   return rc;
53812 #endif
53813 }
53814
53815 /*
53816 ** Make sure pMem->z points to a writable allocation of at least 
53817 ** n bytes.
53818 **
53819 ** If the memory cell currently contains string or blob data
53820 ** and the third argument passed to this function is true, the 
53821 ** current content of the cell is preserved. Otherwise, it may
53822 ** be discarded.  
53823 **
53824 ** This function sets the MEM_Dyn flag and clears any xDel callback.
53825 ** It also clears MEM_Ephem and MEM_Static. If the preserve flag is 
53826 ** not set, Mem.n is zeroed.
53827 */
53828 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve){
53829   assert( 1 >=
53830     ((pMem->zMalloc && pMem->zMalloc==pMem->z) ? 1 : 0) +
53831     (((pMem->flags&MEM_Dyn)&&pMem->xDel) ? 1 : 0) + 
53832     ((pMem->flags&MEM_Ephem) ? 1 : 0) + 
53833     ((pMem->flags&MEM_Static) ? 1 : 0)
53834   );
53835   assert( (pMem->flags&MEM_RowSet)==0 );
53836
53837   if( n<32 ) n = 32;
53838   if( sqlite3DbMallocSize(pMem->db, pMem->zMalloc)<n ){
53839     if( preserve && pMem->z==pMem->zMalloc ){
53840       pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
53841       preserve = 0;
53842     }else{
53843       sqlite3DbFree(pMem->db, pMem->zMalloc);
53844       pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
53845     }
53846   }
53847
53848   if( pMem->z && preserve && pMem->zMalloc && pMem->z!=pMem->zMalloc ){
53849     memcpy(pMem->zMalloc, pMem->z, pMem->n);
53850   }
53851   if( pMem->flags&MEM_Dyn && pMem->xDel ){
53852     pMem->xDel((void *)(pMem->z));
53853   }
53854
53855   pMem->z = pMem->zMalloc;
53856   if( pMem->z==0 ){
53857     pMem->flags = MEM_Null;
53858   }else{
53859     pMem->flags &= ~(MEM_Ephem|MEM_Static);
53860   }
53861   pMem->xDel = 0;
53862   return (pMem->z ? SQLITE_OK : SQLITE_NOMEM);
53863 }
53864
53865 /*
53866 ** Make the given Mem object MEM_Dyn.  In other words, make it so
53867 ** that any TEXT or BLOB content is stored in memory obtained from
53868 ** malloc().  In this way, we know that the memory is safe to be
53869 ** overwritten or altered.
53870 **
53871 ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
53872 */
53873 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
53874   int f;
53875   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
53876   assert( (pMem->flags&MEM_RowSet)==0 );
53877   expandBlob(pMem);
53878   f = pMem->flags;
53879   if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){
53880     if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
53881       return SQLITE_NOMEM;
53882     }
53883     pMem->z[pMem->n] = 0;
53884     pMem->z[pMem->n+1] = 0;
53885     pMem->flags |= MEM_Term;
53886 #ifdef SQLITE_DEBUG
53887     pMem->pScopyFrom = 0;
53888 #endif
53889   }
53890
53891   return SQLITE_OK;
53892 }
53893
53894 /*
53895 ** If the given Mem* has a zero-filled tail, turn it into an ordinary
53896 ** blob stored in dynamically allocated space.
53897 */
53898 #ifndef SQLITE_OMIT_INCRBLOB
53899 SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
53900   if( pMem->flags & MEM_Zero ){
53901     int nByte;
53902     assert( pMem->flags&MEM_Blob );
53903     assert( (pMem->flags&MEM_RowSet)==0 );
53904     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
53905
53906     /* Set nByte to the number of bytes required to store the expanded blob. */
53907     nByte = pMem->n + pMem->u.nZero;
53908     if( nByte<=0 ){
53909       nByte = 1;
53910     }
53911     if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
53912       return SQLITE_NOMEM;
53913     }
53914
53915     memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
53916     pMem->n += pMem->u.nZero;
53917     pMem->flags &= ~(MEM_Zero|MEM_Term);
53918   }
53919   return SQLITE_OK;
53920 }
53921 #endif
53922
53923
53924 /*
53925 ** Make sure the given Mem is \u0000 terminated.
53926 */
53927 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
53928   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
53929   if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
53930     return SQLITE_OK;   /* Nothing to do */
53931   }
53932   if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
53933     return SQLITE_NOMEM;
53934   }
53935   pMem->z[pMem->n] = 0;
53936   pMem->z[pMem->n+1] = 0;
53937   pMem->flags |= MEM_Term;
53938   return SQLITE_OK;
53939 }
53940
53941 /*
53942 ** Add MEM_Str to the set of representations for the given Mem.  Numbers
53943 ** are converted using sqlite3_snprintf().  Converting a BLOB to a string
53944 ** is a no-op.
53945 **
53946 ** Existing representations MEM_Int and MEM_Real are *not* invalidated.
53947 **
53948 ** A MEM_Null value will never be passed to this function. This function is
53949 ** used for converting values to text for returning to the user (i.e. via
53950 ** sqlite3_value_text()), or for ensuring that values to be used as btree
53951 ** keys are strings. In the former case a NULL pointer is returned the
53952 ** user and the later is an internal programming error.
53953 */
53954 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, int enc){
53955   int rc = SQLITE_OK;
53956   int fg = pMem->flags;
53957   const int nByte = 32;
53958
53959   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
53960   assert( !(fg&MEM_Zero) );
53961   assert( !(fg&(MEM_Str|MEM_Blob)) );
53962   assert( fg&(MEM_Int|MEM_Real) );
53963   assert( (pMem->flags&MEM_RowSet)==0 );
53964   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
53965
53966
53967   if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
53968     return SQLITE_NOMEM;
53969   }
53970
53971   /* For a Real or Integer, use sqlite3_mprintf() to produce the UTF-8
53972   ** string representation of the value. Then, if the required encoding
53973   ** is UTF-16le or UTF-16be do a translation.
53974   ** 
53975   ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
53976   */
53977   if( fg & MEM_Int ){
53978     sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
53979   }else{
53980     assert( fg & MEM_Real );
53981     sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->r);
53982   }
53983   pMem->n = sqlite3Strlen30(pMem->z);
53984   pMem->enc = SQLITE_UTF8;
53985   pMem->flags |= MEM_Str|MEM_Term;
53986   sqlite3VdbeChangeEncoding(pMem, enc);
53987   return rc;
53988 }
53989
53990 /*
53991 ** Memory cell pMem contains the context of an aggregate function.
53992 ** This routine calls the finalize method for that function.  The
53993 ** result of the aggregate is stored back into pMem.
53994 **
53995 ** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
53996 ** otherwise.
53997 */
53998 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
53999   int rc = SQLITE_OK;
54000   if( ALWAYS(pFunc && pFunc->xFinalize) ){
54001     sqlite3_context ctx;
54002     assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
54003     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
54004     memset(&ctx, 0, sizeof(ctx));
54005     ctx.s.flags = MEM_Null;
54006     ctx.s.db = pMem->db;
54007     ctx.pMem = pMem;
54008     ctx.pFunc = pFunc;
54009     pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
54010     assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );
54011     sqlite3DbFree(pMem->db, pMem->zMalloc);
54012     memcpy(pMem, &ctx.s, sizeof(ctx.s));
54013     rc = ctx.isError;
54014   }
54015   return rc;
54016 }
54017
54018 /*
54019 ** If the memory cell contains a string value that must be freed by
54020 ** invoking an external callback, free it now. Calling this function
54021 ** does not free any Mem.zMalloc buffer.
54022 */
54023 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p){
54024   assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
54025   testcase( p->flags & MEM_Agg );
54026   testcase( p->flags & MEM_Dyn );
54027   testcase( p->flags & MEM_RowSet );
54028   testcase( p->flags & MEM_Frame );
54029   if( p->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame) ){
54030     if( p->flags&MEM_Agg ){
54031       sqlite3VdbeMemFinalize(p, p->u.pDef);
54032       assert( (p->flags & MEM_Agg)==0 );
54033       sqlite3VdbeMemRelease(p);
54034     }else if( p->flags&MEM_Dyn && p->xDel ){
54035       assert( (p->flags&MEM_RowSet)==0 );
54036       p->xDel((void *)p->z);
54037       p->xDel = 0;
54038     }else if( p->flags&MEM_RowSet ){
54039       sqlite3RowSetClear(p->u.pRowSet);
54040     }else if( p->flags&MEM_Frame ){
54041       sqlite3VdbeMemSetNull(p);
54042     }
54043   }
54044 }
54045
54046 /*
54047 ** Release any memory held by the Mem. This may leave the Mem in an
54048 ** inconsistent state, for example with (Mem.z==0) and
54049 ** (Mem.type==SQLITE_TEXT).
54050 */
54051 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
54052   sqlite3VdbeMemReleaseExternal(p);
54053   sqlite3DbFree(p->db, p->zMalloc);
54054   p->z = 0;
54055   p->zMalloc = 0;
54056   p->xDel = 0;
54057 }
54058
54059 /*
54060 ** Convert a 64-bit IEEE double into a 64-bit signed integer.
54061 ** If the double is too large, return 0x8000000000000000.
54062 **
54063 ** Most systems appear to do this simply by assigning
54064 ** variables and without the extra range tests.  But
54065 ** there are reports that windows throws an expection
54066 ** if the floating point value is out of range. (See ticket #2880.)
54067 ** Because we do not completely understand the problem, we will
54068 ** take the conservative approach and always do range tests
54069 ** before attempting the conversion.
54070 */
54071 static i64 doubleToInt64(double r){
54072 #ifdef SQLITE_OMIT_FLOATING_POINT
54073   /* When floating-point is omitted, double and int64 are the same thing */
54074   return r;
54075 #else
54076   /*
54077   ** Many compilers we encounter do not define constants for the
54078   ** minimum and maximum 64-bit integers, or they define them
54079   ** inconsistently.  And many do not understand the "LL" notation.
54080   ** So we define our own static constants here using nothing
54081   ** larger than a 32-bit integer constant.
54082   */
54083   static const i64 maxInt = LARGEST_INT64;
54084   static const i64 minInt = SMALLEST_INT64;
54085
54086   if( r<(double)minInt ){
54087     return minInt;
54088   }else if( r>(double)maxInt ){
54089     /* minInt is correct here - not maxInt.  It turns out that assigning
54090     ** a very large positive number to an integer results in a very large
54091     ** negative integer.  This makes no sense, but it is what x86 hardware
54092     ** does so for compatibility we will do the same in software. */
54093     return minInt;
54094   }else{
54095     return (i64)r;
54096   }
54097 #endif
54098 }
54099
54100 /*
54101 ** Return some kind of integer value which is the best we can do
54102 ** at representing the value that *pMem describes as an integer.
54103 ** If pMem is an integer, then the value is exact.  If pMem is
54104 ** a floating-point then the value returned is the integer part.
54105 ** If pMem is a string or blob, then we make an attempt to convert
54106 ** it into a integer and return that.  If pMem represents an
54107 ** an SQL-NULL value, return 0.
54108 **
54109 ** If pMem represents a string value, its encoding might be changed.
54110 */
54111 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
54112   int flags;
54113   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
54114   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
54115   flags = pMem->flags;
54116   if( flags & MEM_Int ){
54117     return pMem->u.i;
54118   }else if( flags & MEM_Real ){
54119     return doubleToInt64(pMem->r);
54120   }else if( flags & (MEM_Str|MEM_Blob) ){
54121     i64 value;
54122     assert( pMem->z || pMem->n==0 );
54123     testcase( pMem->z==0 );
54124     sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
54125     return value;
54126   }else{
54127     return 0;
54128   }
54129 }
54130
54131 /*
54132 ** Return the best representation of pMem that we can get into a
54133 ** double.  If pMem is already a double or an integer, return its
54134 ** value.  If it is a string or blob, try to convert it to a double.
54135 ** If it is a NULL, return 0.0.
54136 */
54137 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
54138   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
54139   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
54140   if( pMem->flags & MEM_Real ){
54141     return pMem->r;
54142   }else if( pMem->flags & MEM_Int ){
54143     return (double)pMem->u.i;
54144   }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
54145     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
54146     double val = (double)0;
54147     sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
54148     return val;
54149   }else{
54150     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
54151     return (double)0;
54152   }
54153 }
54154
54155 /*
54156 ** The MEM structure is already a MEM_Real.  Try to also make it a
54157 ** MEM_Int if we can.
54158 */
54159 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
54160   assert( pMem->flags & MEM_Real );
54161   assert( (pMem->flags & MEM_RowSet)==0 );
54162   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
54163   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
54164
54165   pMem->u.i = doubleToInt64(pMem->r);
54166
54167   /* Only mark the value as an integer if
54168   **
54169   **    (1) the round-trip conversion real->int->real is a no-op, and
54170   **    (2) The integer is neither the largest nor the smallest
54171   **        possible integer (ticket #3922)
54172   **
54173   ** The second and third terms in the following conditional enforces
54174   ** the second condition under the assumption that addition overflow causes
54175   ** values to wrap around.  On x86 hardware, the third term is always
54176   ** true and could be omitted.  But we leave it in because other
54177   ** architectures might behave differently.
54178   */
54179   if( pMem->r==(double)pMem->u.i && pMem->u.i>SMALLEST_INT64
54180       && ALWAYS(pMem->u.i<LARGEST_INT64) ){
54181     pMem->flags |= MEM_Int;
54182   }
54183 }
54184
54185 /*
54186 ** Convert pMem to type integer.  Invalidate any prior representations.
54187 */
54188 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
54189   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
54190   assert( (pMem->flags & MEM_RowSet)==0 );
54191   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
54192
54193   pMem->u.i = sqlite3VdbeIntValue(pMem);
54194   MemSetTypeFlag(pMem, MEM_Int);
54195   return SQLITE_OK;
54196 }
54197
54198 /*
54199 ** Convert pMem so that it is of type MEM_Real.
54200 ** Invalidate any prior representations.
54201 */
54202 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
54203   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
54204   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
54205
54206   pMem->r = sqlite3VdbeRealValue(pMem);
54207   MemSetTypeFlag(pMem, MEM_Real);
54208   return SQLITE_OK;
54209 }
54210
54211 /*
54212 ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
54213 ** Invalidate any prior representations.
54214 **
54215 ** Every effort is made to force the conversion, even if the input
54216 ** is a string that does not look completely like a number.  Convert
54217 ** as much of the string as we can and ignore the rest.
54218 */
54219 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
54220   if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
54221     assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
54222     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
54223     if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
54224       MemSetTypeFlag(pMem, MEM_Int);
54225     }else{
54226       pMem->r = sqlite3VdbeRealValue(pMem);
54227       MemSetTypeFlag(pMem, MEM_Real);
54228       sqlite3VdbeIntegerAffinity(pMem);
54229     }
54230   }
54231   assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
54232   pMem->flags &= ~(MEM_Str|MEM_Blob);
54233   return SQLITE_OK;
54234 }
54235
54236 /*
54237 ** Delete any previous value and set the value stored in *pMem to NULL.
54238 */
54239 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
54240   if( pMem->flags & MEM_Frame ){
54241     sqlite3VdbeFrameDelete(pMem->u.pFrame);
54242   }
54243   if( pMem->flags & MEM_RowSet ){
54244     sqlite3RowSetClear(pMem->u.pRowSet);
54245   }
54246   MemSetTypeFlag(pMem, MEM_Null);
54247   pMem->type = SQLITE_NULL;
54248 }
54249
54250 /*
54251 ** Delete any previous value and set the value to be a BLOB of length
54252 ** n containing all zeros.
54253 */
54254 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
54255   sqlite3VdbeMemRelease(pMem);
54256   pMem->flags = MEM_Blob|MEM_Zero;
54257   pMem->type = SQLITE_BLOB;
54258   pMem->n = 0;
54259   if( n<0 ) n = 0;
54260   pMem->u.nZero = n;
54261   pMem->enc = SQLITE_UTF8;
54262
54263 #ifdef SQLITE_OMIT_INCRBLOB
54264   sqlite3VdbeMemGrow(pMem, n, 0);
54265   if( pMem->z ){
54266     pMem->n = n;
54267     memset(pMem->z, 0, n);
54268   }
54269 #endif
54270 }
54271
54272 /*
54273 ** Delete any previous value and set the value stored in *pMem to val,
54274 ** manifest type INTEGER.
54275 */
54276 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
54277   sqlite3VdbeMemRelease(pMem);
54278   pMem->u.i = val;
54279   pMem->flags = MEM_Int;
54280   pMem->type = SQLITE_INTEGER;
54281 }
54282
54283 #ifndef SQLITE_OMIT_FLOATING_POINT
54284 /*
54285 ** Delete any previous value and set the value stored in *pMem to val,
54286 ** manifest type REAL.
54287 */
54288 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
54289   if( sqlite3IsNaN(val) ){
54290     sqlite3VdbeMemSetNull(pMem);
54291   }else{
54292     sqlite3VdbeMemRelease(pMem);
54293     pMem->r = val;
54294     pMem->flags = MEM_Real;
54295     pMem->type = SQLITE_FLOAT;
54296   }
54297 }
54298 #endif
54299
54300 /*
54301 ** Delete any previous value and set the value of pMem to be an
54302 ** empty boolean index.
54303 */
54304 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
54305   sqlite3 *db = pMem->db;
54306   assert( db!=0 );
54307   assert( (pMem->flags & MEM_RowSet)==0 );
54308   sqlite3VdbeMemRelease(pMem);
54309   pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
54310   if( db->mallocFailed ){
54311     pMem->flags = MEM_Null;
54312   }else{
54313     assert( pMem->zMalloc );
54314     pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc, 
54315                                        sqlite3DbMallocSize(db, pMem->zMalloc));
54316     assert( pMem->u.pRowSet!=0 );
54317     pMem->flags = MEM_RowSet;
54318   }
54319 }
54320
54321 /*
54322 ** Return true if the Mem object contains a TEXT or BLOB that is
54323 ** too large - whose size exceeds SQLITE_MAX_LENGTH.
54324 */
54325 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
54326   assert( p->db!=0 );
54327   if( p->flags & (MEM_Str|MEM_Blob) ){
54328     int n = p->n;
54329     if( p->flags & MEM_Zero ){
54330       n += p->u.nZero;
54331     }
54332     return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
54333   }
54334   return 0; 
54335 }
54336
54337 #ifdef SQLITE_DEBUG
54338 /*
54339 ** This routine prepares a memory cell for modication by breaking
54340 ** its link to a shallow copy and by marking any current shallow
54341 ** copies of this cell as invalid.
54342 **
54343 ** This is used for testing and debugging only - to make sure shallow
54344 ** copies are not misused.
54345 */
54346 SQLITE_PRIVATE void sqlite3VdbeMemPrepareToChange(Vdbe *pVdbe, Mem *pMem){
54347   int i;
54348   Mem *pX;
54349   for(i=1, pX=&pVdbe->aMem[1]; i<=pVdbe->nMem; i++, pX++){
54350     if( pX->pScopyFrom==pMem ){
54351       pX->flags |= MEM_Invalid;
54352       pX->pScopyFrom = 0;
54353     }
54354   }
54355   pMem->pScopyFrom = 0;
54356 }
54357 #endif /* SQLITE_DEBUG */
54358
54359 /*
54360 ** Size of struct Mem not including the Mem.zMalloc member.
54361 */
54362 #define MEMCELLSIZE (size_t)(&(((Mem *)0)->zMalloc))
54363
54364 /*
54365 ** Make an shallow copy of pFrom into pTo.  Prior contents of
54366 ** pTo are freed.  The pFrom->z field is not duplicated.  If
54367 ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
54368 ** and flags gets srcType (either MEM_Ephem or MEM_Static).
54369 */
54370 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
54371   assert( (pFrom->flags & MEM_RowSet)==0 );
54372   sqlite3VdbeMemReleaseExternal(pTo);
54373   memcpy(pTo, pFrom, MEMCELLSIZE);
54374   pTo->xDel = 0;
54375   if( (pFrom->flags&MEM_Static)==0 ){
54376     pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
54377     assert( srcType==MEM_Ephem || srcType==MEM_Static );
54378     pTo->flags |= srcType;
54379   }
54380 }
54381
54382 /*
54383 ** Make a full copy of pFrom into pTo.  Prior contents of pTo are
54384 ** freed before the copy is made.
54385 */
54386 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
54387   int rc = SQLITE_OK;
54388
54389   assert( (pFrom->flags & MEM_RowSet)==0 );
54390   sqlite3VdbeMemReleaseExternal(pTo);
54391   memcpy(pTo, pFrom, MEMCELLSIZE);
54392   pTo->flags &= ~MEM_Dyn;
54393
54394   if( pTo->flags&(MEM_Str|MEM_Blob) ){
54395     if( 0==(pFrom->flags&MEM_Static) ){
54396       pTo->flags |= MEM_Ephem;
54397       rc = sqlite3VdbeMemMakeWriteable(pTo);
54398     }
54399   }
54400
54401   return rc;
54402 }
54403
54404 /*
54405 ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
54406 ** freed. If pFrom contains ephemeral data, a copy is made.
54407 **
54408 ** pFrom contains an SQL NULL when this routine returns.
54409 */
54410 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
54411   assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
54412   assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
54413   assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
54414
54415   sqlite3VdbeMemRelease(pTo);
54416   memcpy(pTo, pFrom, sizeof(Mem));
54417   pFrom->flags = MEM_Null;
54418   pFrom->xDel = 0;
54419   pFrom->zMalloc = 0;
54420 }
54421
54422 /*
54423 ** Change the value of a Mem to be a string or a BLOB.
54424 **
54425 ** The memory management strategy depends on the value of the xDel
54426 ** parameter. If the value passed is SQLITE_TRANSIENT, then the 
54427 ** string is copied into a (possibly existing) buffer managed by the 
54428 ** Mem structure. Otherwise, any existing buffer is freed and the
54429 ** pointer copied.
54430 **
54431 ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
54432 ** size limit) then no memory allocation occurs.  If the string can be
54433 ** stored without allocating memory, then it is.  If a memory allocation
54434 ** is required to store the string, then value of pMem is unchanged.  In
54435 ** either case, SQLITE_TOOBIG is returned.
54436 */
54437 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
54438   Mem *pMem,          /* Memory cell to set to string value */
54439   const char *z,      /* String pointer */
54440   int n,              /* Bytes in string, or negative */
54441   u8 enc,             /* Encoding of z.  0 for BLOBs */
54442   void (*xDel)(void*) /* Destructor function */
54443 ){
54444   int nByte = n;      /* New value for pMem->n */
54445   int iLimit;         /* Maximum allowed string or blob size */
54446   u16 flags = 0;      /* New value for pMem->flags */
54447
54448   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
54449   assert( (pMem->flags & MEM_RowSet)==0 );
54450
54451   /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
54452   if( !z ){
54453     sqlite3VdbeMemSetNull(pMem);
54454     return SQLITE_OK;
54455   }
54456
54457   if( pMem->db ){
54458     iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
54459   }else{
54460     iLimit = SQLITE_MAX_LENGTH;
54461   }
54462   flags = (enc==0?MEM_Blob:MEM_Str);
54463   if( nByte<0 ){
54464     assert( enc!=0 );
54465     if( enc==SQLITE_UTF8 ){
54466       for(nByte=0; nByte<=iLimit && z[nByte]; nByte++){}
54467     }else{
54468       for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
54469     }
54470     flags |= MEM_Term;
54471   }
54472
54473   /* The following block sets the new values of Mem.z and Mem.xDel. It
54474   ** also sets a flag in local variable "flags" to indicate the memory
54475   ** management (one of MEM_Dyn or MEM_Static).
54476   */
54477   if( xDel==SQLITE_TRANSIENT ){
54478     int nAlloc = nByte;
54479     if( flags&MEM_Term ){
54480       nAlloc += (enc==SQLITE_UTF8?1:2);
54481     }
54482     if( nByte>iLimit ){
54483       return SQLITE_TOOBIG;
54484     }
54485     if( sqlite3VdbeMemGrow(pMem, nAlloc, 0) ){
54486       return SQLITE_NOMEM;
54487     }
54488     memcpy(pMem->z, z, nAlloc);
54489   }else if( xDel==SQLITE_DYNAMIC ){
54490     sqlite3VdbeMemRelease(pMem);
54491     pMem->zMalloc = pMem->z = (char *)z;
54492     pMem->xDel = 0;
54493   }else{
54494     sqlite3VdbeMemRelease(pMem);
54495     pMem->z = (char *)z;
54496     pMem->xDel = xDel;
54497     flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
54498   }
54499
54500   pMem->n = nByte;
54501   pMem->flags = flags;
54502   pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
54503   pMem->type = (enc==0 ? SQLITE_BLOB : SQLITE_TEXT);
54504
54505 #ifndef SQLITE_OMIT_UTF16
54506   if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
54507     return SQLITE_NOMEM;
54508   }
54509 #endif
54510
54511   if( nByte>iLimit ){
54512     return SQLITE_TOOBIG;
54513   }
54514
54515   return SQLITE_OK;
54516 }
54517
54518 /*
54519 ** Compare the values contained by the two memory cells, returning
54520 ** negative, zero or positive if pMem1 is less than, equal to, or greater
54521 ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
54522 ** and reals) sorted numerically, followed by text ordered by the collating
54523 ** sequence pColl and finally blob's ordered by memcmp().
54524 **
54525 ** Two NULL values are considered equal by this function.
54526 */
54527 SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
54528   int rc;
54529   int f1, f2;
54530   int combined_flags;
54531
54532   f1 = pMem1->flags;
54533   f2 = pMem2->flags;
54534   combined_flags = f1|f2;
54535   assert( (combined_flags & MEM_RowSet)==0 );
54536  
54537   /* If one value is NULL, it is less than the other. If both values
54538   ** are NULL, return 0.
54539   */
54540   if( combined_flags&MEM_Null ){
54541     return (f2&MEM_Null) - (f1&MEM_Null);
54542   }
54543
54544   /* If one value is a number and the other is not, the number is less.
54545   ** If both are numbers, compare as reals if one is a real, or as integers
54546   ** if both values are integers.
54547   */
54548   if( combined_flags&(MEM_Int|MEM_Real) ){
54549     if( !(f1&(MEM_Int|MEM_Real)) ){
54550       return 1;
54551     }
54552     if( !(f2&(MEM_Int|MEM_Real)) ){
54553       return -1;
54554     }
54555     if( (f1 & f2 & MEM_Int)==0 ){
54556       double r1, r2;
54557       if( (f1&MEM_Real)==0 ){
54558         r1 = (double)pMem1->u.i;
54559       }else{
54560         r1 = pMem1->r;
54561       }
54562       if( (f2&MEM_Real)==0 ){
54563         r2 = (double)pMem2->u.i;
54564       }else{
54565         r2 = pMem2->r;
54566       }
54567       if( r1<r2 ) return -1;
54568       if( r1>r2 ) return 1;
54569       return 0;
54570     }else{
54571       assert( f1&MEM_Int );
54572       assert( f2&MEM_Int );
54573       if( pMem1->u.i < pMem2->u.i ) return -1;
54574       if( pMem1->u.i > pMem2->u.i ) return 1;
54575       return 0;
54576     }
54577   }
54578
54579   /* If one value is a string and the other is a blob, the string is less.
54580   ** If both are strings, compare using the collating functions.
54581   */
54582   if( combined_flags&MEM_Str ){
54583     if( (f1 & MEM_Str)==0 ){
54584       return 1;
54585     }
54586     if( (f2 & MEM_Str)==0 ){
54587       return -1;
54588     }
54589
54590     assert( pMem1->enc==pMem2->enc );
54591     assert( pMem1->enc==SQLITE_UTF8 || 
54592             pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
54593
54594     /* The collation sequence must be defined at this point, even if
54595     ** the user deletes the collation sequence after the vdbe program is
54596     ** compiled (this was not always the case).
54597     */
54598     assert( !pColl || pColl->xCmp );
54599
54600     if( pColl ){
54601       if( pMem1->enc==pColl->enc ){
54602         /* The strings are already in the correct encoding.  Call the
54603         ** comparison function directly */
54604         return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
54605       }else{
54606         const void *v1, *v2;
54607         int n1, n2;
54608         Mem c1;
54609         Mem c2;
54610         memset(&c1, 0, sizeof(c1));
54611         memset(&c2, 0, sizeof(c2));
54612         sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
54613         sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
54614         v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
54615         n1 = v1==0 ? 0 : c1.n;
54616         v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
54617         n2 = v2==0 ? 0 : c2.n;
54618         rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
54619         sqlite3VdbeMemRelease(&c1);
54620         sqlite3VdbeMemRelease(&c2);
54621         return rc;
54622       }
54623     }
54624     /* If a NULL pointer was passed as the collate function, fall through
54625     ** to the blob case and use memcmp().  */
54626   }
54627  
54628   /* Both values must be blobs.  Compare using memcmp().  */
54629   rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
54630   if( rc==0 ){
54631     rc = pMem1->n - pMem2->n;
54632   }
54633   return rc;
54634 }
54635
54636 /*
54637 ** Move data out of a btree key or data field and into a Mem structure.
54638 ** The data or key is taken from the entry that pCur is currently pointing
54639 ** to.  offset and amt determine what portion of the data or key to retrieve.
54640 ** key is true to get the key or false to get data.  The result is written
54641 ** into the pMem element.
54642 **
54643 ** The pMem structure is assumed to be uninitialized.  Any prior content
54644 ** is overwritten without being freed.
54645 **
54646 ** If this routine fails for any reason (malloc returns NULL or unable
54647 ** to read from the disk) then the pMem is left in an inconsistent state.
54648 */
54649 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
54650   BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
54651   int offset,       /* Offset from the start of data to return bytes from. */
54652   int amt,          /* Number of bytes to return. */
54653   int key,          /* If true, retrieve from the btree key, not data. */
54654   Mem *pMem         /* OUT: Return data in this Mem structure. */
54655 ){
54656   char *zData;        /* Data from the btree layer */
54657   int available = 0;  /* Number of bytes available on the local btree page */
54658   int rc = SQLITE_OK; /* Return code */
54659
54660   assert( sqlite3BtreeCursorIsValid(pCur) );
54661
54662   /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert() 
54663   ** that both the BtShared and database handle mutexes are held. */
54664   assert( (pMem->flags & MEM_RowSet)==0 );
54665   if( key ){
54666     zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
54667   }else{
54668     zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
54669   }
54670   assert( zData!=0 );
54671
54672   if( offset+amt<=available && (pMem->flags&MEM_Dyn)==0 ){
54673     sqlite3VdbeMemRelease(pMem);
54674     pMem->z = &zData[offset];
54675     pMem->flags = MEM_Blob|MEM_Ephem;
54676   }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){
54677     pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;
54678     pMem->enc = 0;
54679     pMem->type = SQLITE_BLOB;
54680     if( key ){
54681       rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
54682     }else{
54683       rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
54684     }
54685     pMem->z[amt] = 0;
54686     pMem->z[amt+1] = 0;
54687     if( rc!=SQLITE_OK ){
54688       sqlite3VdbeMemRelease(pMem);
54689     }
54690   }
54691   pMem->n = amt;
54692
54693   return rc;
54694 }
54695
54696 /* This function is only available internally, it is not part of the
54697 ** external API. It works in a similar way to sqlite3_value_text(),
54698 ** except the data returned is in the encoding specified by the second
54699 ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
54700 ** SQLITE_UTF8.
54701 **
54702 ** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
54703 ** If that is the case, then the result must be aligned on an even byte
54704 ** boundary.
54705 */
54706 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
54707   if( !pVal ) return 0;
54708
54709   assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
54710   assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
54711   assert( (pVal->flags & MEM_RowSet)==0 );
54712
54713   if( pVal->flags&MEM_Null ){
54714     return 0;
54715   }
54716   assert( (MEM_Blob>>3) == MEM_Str );
54717   pVal->flags |= (pVal->flags & MEM_Blob)>>3;
54718   expandBlob(pVal);
54719   if( pVal->flags&MEM_Str ){
54720     sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
54721     if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
54722       assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
54723       if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
54724         return 0;
54725       }
54726     }
54727     sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-59893-45467 */
54728   }else{
54729     assert( (pVal->flags&MEM_Blob)==0 );
54730     sqlite3VdbeMemStringify(pVal, enc);
54731     assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
54732   }
54733   assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
54734               || pVal->db->mallocFailed );
54735   if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
54736     return pVal->z;
54737   }else{
54738     return 0;
54739   }
54740 }
54741
54742 /*
54743 ** Create a new sqlite3_value object.
54744 */
54745 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
54746   Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
54747   if( p ){
54748     p->flags = MEM_Null;
54749     p->type = SQLITE_NULL;
54750     p->db = db;
54751   }
54752   return p;
54753 }
54754
54755 /*
54756 ** Create a new sqlite3_value object, containing the value of pExpr.
54757 **
54758 ** This only works for very simple expressions that consist of one constant
54759 ** token (i.e. "5", "5.1", "'a string'"). If the expression can
54760 ** be converted directly into a value, then the value is allocated and
54761 ** a pointer written to *ppVal. The caller is responsible for deallocating
54762 ** the value by passing it to sqlite3ValueFree() later on. If the expression
54763 ** cannot be converted to a value, then *ppVal is set to NULL.
54764 */
54765 SQLITE_PRIVATE int sqlite3ValueFromExpr(
54766   sqlite3 *db,              /* The database connection */
54767   Expr *pExpr,              /* The expression to evaluate */
54768   u8 enc,                   /* Encoding to use */
54769   u8 affinity,              /* Affinity to use */
54770   sqlite3_value **ppVal     /* Write the new value here */
54771 ){
54772   int op;
54773   char *zVal = 0;
54774   sqlite3_value *pVal = 0;
54775   int negInt = 1;
54776   const char *zNeg = "";
54777
54778   if( !pExpr ){
54779     *ppVal = 0;
54780     return SQLITE_OK;
54781   }
54782   op = pExpr->op;
54783
54784   /* op can only be TK_REGISTER if we have compiled with SQLITE_ENABLE_STAT2.
54785   ** The ifdef here is to enable us to achieve 100% branch test coverage even
54786   ** when SQLITE_ENABLE_STAT2 is omitted.
54787   */
54788 #ifdef SQLITE_ENABLE_STAT2
54789   if( op==TK_REGISTER ) op = pExpr->op2;
54790 #else
54791   if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
54792 #endif
54793
54794   /* Handle negative integers in a single step.  This is needed in the
54795   ** case when the value is -9223372036854775808.
54796   */
54797   if( op==TK_UMINUS
54798    && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
54799     pExpr = pExpr->pLeft;
54800     op = pExpr->op;
54801     negInt = -1;
54802     zNeg = "-";
54803   }
54804
54805   if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
54806     pVal = sqlite3ValueNew(db);
54807     if( pVal==0 ) goto no_mem;
54808     if( ExprHasProperty(pExpr, EP_IntValue) ){
54809       sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
54810     }else{
54811       zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
54812       if( zVal==0 ) goto no_mem;
54813       sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
54814       if( op==TK_FLOAT ) pVal->type = SQLITE_FLOAT;
54815     }
54816     if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
54817       sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
54818     }else{
54819       sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
54820     }
54821     if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
54822     if( enc!=SQLITE_UTF8 ){
54823       sqlite3VdbeChangeEncoding(pVal, enc);
54824     }
54825   }else if( op==TK_UMINUS ) {
54826     /* This branch happens for multiple negative signs.  Ex: -(-5) */
54827     if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) ){
54828       sqlite3VdbeMemNumerify(pVal);
54829       pVal->u.i = -1 * pVal->u.i;
54830       /* (double)-1 In case of SQLITE_OMIT_FLOATING_POINT... */
54831       pVal->r = (double)-1 * pVal->r;
54832       sqlite3ValueApplyAffinity(pVal, affinity, enc);
54833     }
54834   }
54835 #ifndef SQLITE_OMIT_BLOB_LITERAL
54836   else if( op==TK_BLOB ){
54837     int nVal;
54838     assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
54839     assert( pExpr->u.zToken[1]=='\'' );
54840     pVal = sqlite3ValueNew(db);
54841     if( !pVal ) goto no_mem;
54842     zVal = &pExpr->u.zToken[2];
54843     nVal = sqlite3Strlen30(zVal)-1;
54844     assert( zVal[nVal]=='\'' );
54845     sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
54846                          0, SQLITE_DYNAMIC);
54847   }
54848 #endif
54849
54850   if( pVal ){
54851     sqlite3VdbeMemStoreType(pVal);
54852   }
54853   *ppVal = pVal;
54854   return SQLITE_OK;
54855
54856 no_mem:
54857   db->mallocFailed = 1;
54858   sqlite3DbFree(db, zVal);
54859   sqlite3ValueFree(pVal);
54860   *ppVal = 0;
54861   return SQLITE_NOMEM;
54862 }
54863
54864 /*
54865 ** Change the string value of an sqlite3_value object
54866 */
54867 SQLITE_PRIVATE void sqlite3ValueSetStr(
54868   sqlite3_value *v,     /* Value to be set */
54869   int n,                /* Length of string z */
54870   const void *z,        /* Text of the new string */
54871   u8 enc,               /* Encoding to use */
54872   void (*xDel)(void*)   /* Destructor for the string */
54873 ){
54874   if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
54875 }
54876
54877 /*
54878 ** Free an sqlite3_value object
54879 */
54880 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
54881   if( !v ) return;
54882   sqlite3VdbeMemRelease((Mem *)v);
54883   sqlite3DbFree(((Mem*)v)->db, v);
54884 }
54885
54886 /*
54887 ** Return the number of bytes in the sqlite3_value object assuming
54888 ** that it uses the encoding "enc"
54889 */
54890 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
54891   Mem *p = (Mem*)pVal;
54892   if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
54893     if( p->flags & MEM_Zero ){
54894       return p->n + p->u.nZero;
54895     }else{
54896       return p->n;
54897     }
54898   }
54899   return 0;
54900 }
54901
54902 /************** End of vdbemem.c *********************************************/
54903 /************** Begin file vdbeaux.c *****************************************/
54904 /*
54905 ** 2003 September 6
54906 **
54907 ** The author disclaims copyright to this source code.  In place of
54908 ** a legal notice, here is a blessing:
54909 **
54910 **    May you do good and not evil.
54911 **    May you find forgiveness for yourself and forgive others.
54912 **    May you share freely, never taking more than you give.
54913 **
54914 *************************************************************************
54915 ** This file contains code used for creating, destroying, and populating
54916 ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)  Prior
54917 ** to version 2.8.7, all this code was combined into the vdbe.c source file.
54918 ** But that file was getting too big so this subroutines were split out.
54919 */
54920
54921
54922
54923 /*
54924 ** When debugging the code generator in a symbolic debugger, one can
54925 ** set the sqlite3VdbeAddopTrace to 1 and all opcodes will be printed
54926 ** as they are added to the instruction stream.
54927 */
54928 #ifdef SQLITE_DEBUG
54929 SQLITE_PRIVATE int sqlite3VdbeAddopTrace = 0;
54930 #endif
54931
54932
54933 /*
54934 ** Create a new virtual database engine.
54935 */
54936 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3 *db){
54937   Vdbe *p;
54938   p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
54939   if( p==0 ) return 0;
54940   p->db = db;
54941   if( db->pVdbe ){
54942     db->pVdbe->pPrev = p;
54943   }
54944   p->pNext = db->pVdbe;
54945   p->pPrev = 0;
54946   db->pVdbe = p;
54947   p->magic = VDBE_MAGIC_INIT;
54948   return p;
54949 }
54950
54951 /*
54952 ** Remember the SQL string for a prepared statement.
54953 */
54954 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
54955   assert( isPrepareV2==1 || isPrepareV2==0 );
54956   if( p==0 ) return;
54957 #ifdef SQLITE_OMIT_TRACE
54958   if( !isPrepareV2 ) return;
54959 #endif
54960   assert( p->zSql==0 );
54961   p->zSql = sqlite3DbStrNDup(p->db, z, n);
54962   p->isPrepareV2 = (u8)isPrepareV2;
54963 }
54964
54965 /*
54966 ** Return the SQL associated with a prepared statement
54967 */
54968 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
54969   Vdbe *p = (Vdbe *)pStmt;
54970   return (p && p->isPrepareV2) ? p->zSql : 0;
54971 }
54972
54973 /*
54974 ** Swap all content between two VDBE structures.
54975 */
54976 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
54977   Vdbe tmp, *pTmp;
54978   char *zTmp;
54979   tmp = *pA;
54980   *pA = *pB;
54981   *pB = tmp;
54982   pTmp = pA->pNext;
54983   pA->pNext = pB->pNext;
54984   pB->pNext = pTmp;
54985   pTmp = pA->pPrev;
54986   pA->pPrev = pB->pPrev;
54987   pB->pPrev = pTmp;
54988   zTmp = pA->zSql;
54989   pA->zSql = pB->zSql;
54990   pB->zSql = zTmp;
54991   pB->isPrepareV2 = pA->isPrepareV2;
54992 }
54993
54994 #ifdef SQLITE_DEBUG
54995 /*
54996 ** Turn tracing on or off
54997 */
54998 SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
54999   p->trace = trace;
55000 }
55001 #endif
55002
55003 /*
55004 ** Resize the Vdbe.aOp array so that it is at least one op larger than 
55005 ** it was.
55006 **
55007 ** If an out-of-memory error occurs while resizing the array, return
55008 ** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain 
55009 ** unchanged (this is so that any opcodes already allocated can be 
55010 ** correctly deallocated along with the rest of the Vdbe).
55011 */
55012 static int growOpArray(Vdbe *p){
55013   VdbeOp *pNew;
55014   int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
55015   pNew = sqlite3DbRealloc(p->db, p->aOp, nNew*sizeof(Op));
55016   if( pNew ){
55017     p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
55018     p->aOp = pNew;
55019   }
55020   return (pNew ? SQLITE_OK : SQLITE_NOMEM);
55021 }
55022
55023 /*
55024 ** Add a new instruction to the list of instructions current in the
55025 ** VDBE.  Return the address of the new instruction.
55026 **
55027 ** Parameters:
55028 **
55029 **    p               Pointer to the VDBE
55030 **
55031 **    op              The opcode for this instruction
55032 **
55033 **    p1, p2, p3      Operands
55034 **
55035 ** Use the sqlite3VdbeResolveLabel() function to fix an address and
55036 ** the sqlite3VdbeChangeP4() function to change the value of the P4
55037 ** operand.
55038 */
55039 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
55040   int i;
55041   VdbeOp *pOp;
55042
55043   i = p->nOp;
55044   assert( p->magic==VDBE_MAGIC_INIT );
55045   assert( op>0 && op<0xff );
55046   if( p->nOpAlloc<=i ){
55047     if( growOpArray(p) ){
55048       return 1;
55049     }
55050   }
55051   p->nOp++;
55052   pOp = &p->aOp[i];
55053   pOp->opcode = (u8)op;
55054   pOp->p5 = 0;
55055   pOp->p1 = p1;
55056   pOp->p2 = p2;
55057   pOp->p3 = p3;
55058   pOp->p4.p = 0;
55059   pOp->p4type = P4_NOTUSED;
55060   p->expired = 0;
55061 #ifdef SQLITE_DEBUG
55062   pOp->zComment = 0;
55063   if( sqlite3VdbeAddopTrace ) sqlite3VdbePrintOp(0, i, &p->aOp[i]);
55064 #endif
55065 #ifdef VDBE_PROFILE
55066   pOp->cycles = 0;
55067   pOp->cnt = 0;
55068 #endif
55069   return i;
55070 }
55071 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
55072   return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
55073 }
55074 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
55075   return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
55076 }
55077 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
55078   return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
55079 }
55080
55081
55082 /*
55083 ** Add an opcode that includes the p4 value as a pointer.
55084 */
55085 SQLITE_PRIVATE int sqlite3VdbeAddOp4(
55086   Vdbe *p,            /* Add the opcode to this VM */
55087   int op,             /* The new opcode */
55088   int p1,             /* The P1 operand */
55089   int p2,             /* The P2 operand */
55090   int p3,             /* The P3 operand */
55091   const char *zP4,    /* The P4 operand */
55092   int p4type          /* P4 operand type */
55093 ){
55094   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
55095   sqlite3VdbeChangeP4(p, addr, zP4, p4type);
55096   return addr;
55097 }
55098
55099 /*
55100 ** Add an opcode that includes the p4 value as an integer.
55101 */
55102 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
55103   Vdbe *p,            /* Add the opcode to this VM */
55104   int op,             /* The new opcode */
55105   int p1,             /* The P1 operand */
55106   int p2,             /* The P2 operand */
55107   int p3,             /* The P3 operand */
55108   int p4              /* The P4 operand as an integer */
55109 ){
55110   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
55111   sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
55112   return addr;
55113 }
55114
55115 /*
55116 ** Create a new symbolic label for an instruction that has yet to be
55117 ** coded.  The symbolic label is really just a negative number.  The
55118 ** label can be used as the P2 value of an operation.  Later, when
55119 ** the label is resolved to a specific address, the VDBE will scan
55120 ** through its operation list and change all values of P2 which match
55121 ** the label into the resolved address.
55122 **
55123 ** The VDBE knows that a P2 value is a label because labels are
55124 ** always negative and P2 values are suppose to be non-negative.
55125 ** Hence, a negative P2 value is a label that has yet to be resolved.
55126 **
55127 ** Zero is returned if a malloc() fails.
55128 */
55129 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *p){
55130   int i;
55131   i = p->nLabel++;
55132   assert( p->magic==VDBE_MAGIC_INIT );
55133   if( i>=p->nLabelAlloc ){
55134     int n = p->nLabelAlloc*2 + 5;
55135     p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
55136                                        n*sizeof(p->aLabel[0]));
55137     p->nLabelAlloc = sqlite3DbMallocSize(p->db, p->aLabel)/sizeof(p->aLabel[0]);
55138   }
55139   if( p->aLabel ){
55140     p->aLabel[i] = -1;
55141   }
55142   return -1-i;
55143 }
55144
55145 /*
55146 ** Resolve label "x" to be the address of the next instruction to
55147 ** be inserted.  The parameter "x" must have been obtained from
55148 ** a prior call to sqlite3VdbeMakeLabel().
55149 */
55150 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *p, int x){
55151   int j = -1-x;
55152   assert( p->magic==VDBE_MAGIC_INIT );
55153   assert( j>=0 && j<p->nLabel );
55154   if( p->aLabel ){
55155     p->aLabel[j] = p->nOp;
55156   }
55157 }
55158
55159 /*
55160 ** Mark the VDBE as one that can only be run one time.
55161 */
55162 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
55163   p->runOnlyOnce = 1;
55164 }
55165
55166 #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
55167
55168 /*
55169 ** The following type and function are used to iterate through all opcodes
55170 ** in a Vdbe main program and each of the sub-programs (triggers) it may 
55171 ** invoke directly or indirectly. It should be used as follows:
55172 **
55173 **   Op *pOp;
55174 **   VdbeOpIter sIter;
55175 **
55176 **   memset(&sIter, 0, sizeof(sIter));
55177 **   sIter.v = v;                            // v is of type Vdbe* 
55178 **   while( (pOp = opIterNext(&sIter)) ){
55179 **     // Do something with pOp
55180 **   }
55181 **   sqlite3DbFree(v->db, sIter.apSub);
55182 ** 
55183 */
55184 typedef struct VdbeOpIter VdbeOpIter;
55185 struct VdbeOpIter {
55186   Vdbe *v;                   /* Vdbe to iterate through the opcodes of */
55187   SubProgram **apSub;        /* Array of subprograms */
55188   int nSub;                  /* Number of entries in apSub */
55189   int iAddr;                 /* Address of next instruction to return */
55190   int iSub;                  /* 0 = main program, 1 = first sub-program etc. */
55191 };
55192 static Op *opIterNext(VdbeOpIter *p){
55193   Vdbe *v = p->v;
55194   Op *pRet = 0;
55195   Op *aOp;
55196   int nOp;
55197
55198   if( p->iSub<=p->nSub ){
55199
55200     if( p->iSub==0 ){
55201       aOp = v->aOp;
55202       nOp = v->nOp;
55203     }else{
55204       aOp = p->apSub[p->iSub-1]->aOp;
55205       nOp = p->apSub[p->iSub-1]->nOp;
55206     }
55207     assert( p->iAddr<nOp );
55208
55209     pRet = &aOp[p->iAddr];
55210     p->iAddr++;
55211     if( p->iAddr==nOp ){
55212       p->iSub++;
55213       p->iAddr = 0;
55214     }
55215   
55216     if( pRet->p4type==P4_SUBPROGRAM ){
55217       int nByte = (p->nSub+1)*sizeof(SubProgram*);
55218       int j;
55219       for(j=0; j<p->nSub; j++){
55220         if( p->apSub[j]==pRet->p4.pProgram ) break;
55221       }
55222       if( j==p->nSub ){
55223         p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
55224         if( !p->apSub ){
55225           pRet = 0;
55226         }else{
55227           p->apSub[p->nSub++] = pRet->p4.pProgram;
55228         }
55229       }
55230     }
55231   }
55232
55233   return pRet;
55234 }
55235
55236 /*
55237 ** Check if the program stored in the VM associated with pParse may
55238 ** throw an ABORT exception (causing the statement, but not entire transaction
55239 ** to be rolled back). This condition is true if the main program or any
55240 ** sub-programs contains any of the following:
55241 **
55242 **   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
55243 **   *  OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
55244 **   *  OP_Destroy
55245 **   *  OP_VUpdate
55246 **   *  OP_VRename
55247 **   *  OP_FkCounter with P2==0 (immediate foreign key constraint)
55248 **
55249 ** Then check that the value of Parse.mayAbort is true if an
55250 ** ABORT may be thrown, or false otherwise. Return true if it does
55251 ** match, or false otherwise. This function is intended to be used as
55252 ** part of an assert statement in the compiler. Similar to:
55253 **
55254 **   assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
55255 */
55256 SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
55257   int hasAbort = 0;
55258   Op *pOp;
55259   VdbeOpIter sIter;
55260   memset(&sIter, 0, sizeof(sIter));
55261   sIter.v = v;
55262
55263   while( (pOp = opIterNext(&sIter))!=0 ){
55264     int opcode = pOp->opcode;
55265     if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename 
55266 #ifndef SQLITE_OMIT_FOREIGN_KEY
55267      || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1) 
55268 #endif
55269      || ((opcode==OP_Halt || opcode==OP_HaltIfNull) 
55270       && (pOp->p1==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
55271     ){
55272       hasAbort = 1;
55273       break;
55274     }
55275   }
55276   sqlite3DbFree(v->db, sIter.apSub);
55277
55278   /* Return true if hasAbort==mayAbort. Or if a malloc failure occured.
55279   ** If malloc failed, then the while() loop above may not have iterated
55280   ** through all opcodes and hasAbort may be set incorrectly. Return
55281   ** true for this case to prevent the assert() in the callers frame
55282   ** from failing.  */
55283   return ( v->db->mallocFailed || hasAbort==mayAbort );
55284 }
55285 #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
55286
55287 /*
55288 ** Loop through the program looking for P2 values that are negative
55289 ** on jump instructions.  Each such value is a label.  Resolve the
55290 ** label by setting the P2 value to its correct non-zero value.
55291 **
55292 ** This routine is called once after all opcodes have been inserted.
55293 **
55294 ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument 
55295 ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by 
55296 ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
55297 **
55298 ** The Op.opflags field is set on all opcodes.
55299 */
55300 static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
55301   int i;
55302   int nMaxArgs = *pMaxFuncArgs;
55303   Op *pOp;
55304   int *aLabel = p->aLabel;
55305   p->readOnly = 1;
55306   for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
55307     u8 opcode = pOp->opcode;
55308
55309     pOp->opflags = sqlite3OpcodeProperty[opcode];
55310     if( opcode==OP_Function || opcode==OP_AggStep ){
55311       if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
55312     }else if( opcode==OP_Transaction && pOp->p2!=0 ){
55313       p->readOnly = 0;
55314 #ifndef SQLITE_OMIT_VIRTUALTABLE
55315     }else if( opcode==OP_VUpdate ){
55316       if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
55317     }else if( opcode==OP_VFilter ){
55318       int n;
55319       assert( p->nOp - i >= 3 );
55320       assert( pOp[-1].opcode==OP_Integer );
55321       n = pOp[-1].p1;
55322       if( n>nMaxArgs ) nMaxArgs = n;
55323 #endif
55324     }
55325
55326     if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
55327       assert( -1-pOp->p2<p->nLabel );
55328       pOp->p2 = aLabel[-1-pOp->p2];
55329     }
55330   }
55331   sqlite3DbFree(p->db, p->aLabel);
55332   p->aLabel = 0;
55333
55334   *pMaxFuncArgs = nMaxArgs;
55335 }
55336
55337 /*
55338 ** Return the address of the next instruction to be inserted.
55339 */
55340 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
55341   assert( p->magic==VDBE_MAGIC_INIT );
55342   return p->nOp;
55343 }
55344
55345 /*
55346 ** This function returns a pointer to the array of opcodes associated with
55347 ** the Vdbe passed as the first argument. It is the callers responsibility
55348 ** to arrange for the returned array to be eventually freed using the 
55349 ** vdbeFreeOpArray() function.
55350 **
55351 ** Before returning, *pnOp is set to the number of entries in the returned
55352 ** array. Also, *pnMaxArg is set to the larger of its current value and 
55353 ** the number of entries in the Vdbe.apArg[] array required to execute the 
55354 ** returned program.
55355 */
55356 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
55357   VdbeOp *aOp = p->aOp;
55358   assert( aOp && !p->db->mallocFailed );
55359
55360   /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
55361   assert( p->aMutex.nMutex==0 );
55362
55363   resolveP2Values(p, pnMaxArg);
55364   *pnOp = p->nOp;
55365   p->aOp = 0;
55366   return aOp;
55367 }
55368
55369 /*
55370 ** Add a whole list of operations to the operation stack.  Return the
55371 ** address of the first operation added.
55372 */
55373 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
55374   int addr;
55375   assert( p->magic==VDBE_MAGIC_INIT );
55376   if( p->nOp + nOp > p->nOpAlloc && growOpArray(p) ){
55377     return 0;
55378   }
55379   addr = p->nOp;
55380   if( ALWAYS(nOp>0) ){
55381     int i;
55382     VdbeOpList const *pIn = aOp;
55383     for(i=0; i<nOp; i++, pIn++){
55384       int p2 = pIn->p2;
55385       VdbeOp *pOut = &p->aOp[i+addr];
55386       pOut->opcode = pIn->opcode;
55387       pOut->p1 = pIn->p1;
55388       if( p2<0 && (sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP)!=0 ){
55389         pOut->p2 = addr + ADDR(p2);
55390       }else{
55391         pOut->p2 = p2;
55392       }
55393       pOut->p3 = pIn->p3;
55394       pOut->p4type = P4_NOTUSED;
55395       pOut->p4.p = 0;
55396       pOut->p5 = 0;
55397 #ifdef SQLITE_DEBUG
55398       pOut->zComment = 0;
55399       if( sqlite3VdbeAddopTrace ){
55400         sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
55401       }
55402 #endif
55403     }
55404     p->nOp += nOp;
55405   }
55406   return addr;
55407 }
55408
55409 /*
55410 ** Change the value of the P1 operand for a specific instruction.
55411 ** This routine is useful when a large program is loaded from a
55412 ** static array using sqlite3VdbeAddOpList but we want to make a
55413 ** few minor changes to the program.
55414 */
55415 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, int addr, int val){
55416   assert( p!=0 );
55417   assert( addr>=0 );
55418   if( p->nOp>addr ){
55419     p->aOp[addr].p1 = val;
55420   }
55421 }
55422
55423 /*
55424 ** Change the value of the P2 operand for a specific instruction.
55425 ** This routine is useful for setting a jump destination.
55426 */
55427 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, int addr, int val){
55428   assert( p!=0 );
55429   assert( addr>=0 );
55430   if( p->nOp>addr ){
55431     p->aOp[addr].p2 = val;
55432   }
55433 }
55434
55435 /*
55436 ** Change the value of the P3 operand for a specific instruction.
55437 */
55438 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, int addr, int val){
55439   assert( p!=0 );
55440   assert( addr>=0 );
55441   if( p->nOp>addr ){
55442     p->aOp[addr].p3 = val;
55443   }
55444 }
55445
55446 /*
55447 ** Change the value of the P5 operand for the most recently
55448 ** added operation.
55449 */
55450 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
55451   assert( p!=0 );
55452   if( p->aOp ){
55453     assert( p->nOp>0 );
55454     p->aOp[p->nOp-1].p5 = val;
55455   }
55456 }
55457
55458 /*
55459 ** Change the P2 operand of instruction addr so that it points to
55460 ** the address of the next instruction to be coded.
55461 */
55462 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
55463   sqlite3VdbeChangeP2(p, addr, p->nOp);
55464 }
55465
55466
55467 /*
55468 ** If the input FuncDef structure is ephemeral, then free it.  If
55469 ** the FuncDef is not ephermal, then do nothing.
55470 */
55471 static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
55472   if( ALWAYS(pDef) && (pDef->flags & SQLITE_FUNC_EPHEM)!=0 ){
55473     sqlite3DbFree(db, pDef);
55474   }
55475 }
55476
55477 static void vdbeFreeOpArray(sqlite3 *, Op *, int);
55478
55479 /*
55480 ** Delete a P4 value if necessary.
55481 */
55482 static void freeP4(sqlite3 *db, int p4type, void *p4){
55483   if( p4 ){
55484     assert( db );
55485     switch( p4type ){
55486       case P4_REAL:
55487       case P4_INT64:
55488       case P4_DYNAMIC:
55489       case P4_KEYINFO:
55490       case P4_INTARRAY:
55491       case P4_KEYINFO_HANDOFF: {
55492         sqlite3DbFree(db, p4);
55493         break;
55494       }
55495       case P4_MPRINTF: {
55496         if( db->pnBytesFreed==0 ) sqlite3_free(p4);
55497         break;
55498       }
55499       case P4_VDBEFUNC: {
55500         VdbeFunc *pVdbeFunc = (VdbeFunc *)p4;
55501         freeEphemeralFunction(db, pVdbeFunc->pFunc);
55502         if( db->pnBytesFreed==0 ) sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
55503         sqlite3DbFree(db, pVdbeFunc);
55504         break;
55505       }
55506       case P4_FUNCDEF: {
55507         freeEphemeralFunction(db, (FuncDef*)p4);
55508         break;
55509       }
55510       case P4_MEM: {
55511         if( db->pnBytesFreed==0 ){
55512           sqlite3ValueFree((sqlite3_value*)p4);
55513         }else{
55514           Mem *p = (Mem*)p4;
55515           sqlite3DbFree(db, p->zMalloc);
55516           sqlite3DbFree(db, p);
55517         }
55518         break;
55519       }
55520       case P4_VTAB : {
55521         if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
55522         break;
55523       }
55524     }
55525   }
55526 }
55527
55528 /*
55529 ** Free the space allocated for aOp and any p4 values allocated for the
55530 ** opcodes contained within. If aOp is not NULL it is assumed to contain 
55531 ** nOp entries. 
55532 */
55533 static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
55534   if( aOp ){
55535     Op *pOp;
55536     for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
55537       freeP4(db, pOp->p4type, pOp->p4.p);
55538 #ifdef SQLITE_DEBUG
55539       sqlite3DbFree(db, pOp->zComment);
55540 #endif     
55541     }
55542   }
55543   sqlite3DbFree(db, aOp);
55544 }
55545
55546 /*
55547 ** Link the SubProgram object passed as the second argument into the linked
55548 ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
55549 ** objects when the VM is no longer required.
55550 */
55551 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
55552   p->pNext = pVdbe->pProgram;
55553   pVdbe->pProgram = p;
55554 }
55555
55556 /*
55557 ** Change N opcodes starting at addr to No-ops.
55558 */
55559 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr, int N){
55560   if( p->aOp ){
55561     VdbeOp *pOp = &p->aOp[addr];
55562     sqlite3 *db = p->db;
55563     while( N-- ){
55564       freeP4(db, pOp->p4type, pOp->p4.p);
55565       memset(pOp, 0, sizeof(pOp[0]));
55566       pOp->opcode = OP_Noop;
55567       pOp++;
55568     }
55569   }
55570 }
55571
55572 /*
55573 ** Change the value of the P4 operand for a specific instruction.
55574 ** This routine is useful when a large program is loaded from a
55575 ** static array using sqlite3VdbeAddOpList but we want to make a
55576 ** few minor changes to the program.
55577 **
55578 ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
55579 ** the string is made into memory obtained from sqlite3_malloc().
55580 ** A value of n==0 means copy bytes of zP4 up to and including the
55581 ** first null byte.  If n>0 then copy n+1 bytes of zP4.
55582 **
55583 ** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure.
55584 ** A copy is made of the KeyInfo structure into memory obtained from
55585 ** sqlite3_malloc, to be freed when the Vdbe is finalized.
55586 ** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure
55587 ** stored in memory that the caller has obtained from sqlite3_malloc. The 
55588 ** caller should not free the allocation, it will be freed when the Vdbe is
55589 ** finalized.
55590 ** 
55591 ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
55592 ** to a string or structure that is guaranteed to exist for the lifetime of
55593 ** the Vdbe. In these cases we can just copy the pointer.
55594 **
55595 ** If addr<0 then change P4 on the most recently inserted instruction.
55596 */
55597 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
55598   Op *pOp;
55599   sqlite3 *db;
55600   assert( p!=0 );
55601   db = p->db;
55602   assert( p->magic==VDBE_MAGIC_INIT );
55603   if( p->aOp==0 || db->mallocFailed ){
55604     if ( n!=P4_KEYINFO && n!=P4_VTAB ) {
55605       freeP4(db, n, (void*)*(char**)&zP4);
55606     }
55607     return;
55608   }
55609   assert( p->nOp>0 );
55610   assert( addr<p->nOp );
55611   if( addr<0 ){
55612     addr = p->nOp - 1;
55613   }
55614   pOp = &p->aOp[addr];
55615   freeP4(db, pOp->p4type, pOp->p4.p);
55616   pOp->p4.p = 0;
55617   if( n==P4_INT32 ){
55618     /* Note: this cast is safe, because the origin data point was an int
55619     ** that was cast to a (const char *). */
55620     pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
55621     pOp->p4type = P4_INT32;
55622   }else if( zP4==0 ){
55623     pOp->p4.p = 0;
55624     pOp->p4type = P4_NOTUSED;
55625   }else if( n==P4_KEYINFO ){
55626     KeyInfo *pKeyInfo;
55627     int nField, nByte;
55628
55629     nField = ((KeyInfo*)zP4)->nField;
55630     nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
55631     pKeyInfo = sqlite3DbMallocRaw(0, nByte);
55632     pOp->p4.pKeyInfo = pKeyInfo;
55633     if( pKeyInfo ){
55634       u8 *aSortOrder;
55635       memcpy((char*)pKeyInfo, zP4, nByte - nField);
55636       aSortOrder = pKeyInfo->aSortOrder;
55637       if( aSortOrder ){
55638         pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
55639         memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);
55640       }
55641       pOp->p4type = P4_KEYINFO;
55642     }else{
55643       p->db->mallocFailed = 1;
55644       pOp->p4type = P4_NOTUSED;
55645     }
55646   }else if( n==P4_KEYINFO_HANDOFF ){
55647     pOp->p4.p = (void*)zP4;
55648     pOp->p4type = P4_KEYINFO;
55649   }else if( n==P4_VTAB ){
55650     pOp->p4.p = (void*)zP4;
55651     pOp->p4type = P4_VTAB;
55652     sqlite3VtabLock((VTable *)zP4);
55653     assert( ((VTable *)zP4)->db==p->db );
55654   }else if( n<0 ){
55655     pOp->p4.p = (void*)zP4;
55656     pOp->p4type = (signed char)n;
55657   }else{
55658     if( n==0 ) n = sqlite3Strlen30(zP4);
55659     pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
55660     pOp->p4type = P4_DYNAMIC;
55661   }
55662 }
55663
55664 #ifndef NDEBUG
55665 /*
55666 ** Change the comment on the the most recently coded instruction.  Or
55667 ** insert a No-op and add the comment to that new instruction.  This
55668 ** makes the code easier to read during debugging.  None of this happens
55669 ** in a production build.
55670 */
55671 SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
55672   va_list ap;
55673   if( !p ) return;
55674   assert( p->nOp>0 || p->aOp==0 );
55675   assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
55676   if( p->nOp ){
55677     char **pz = &p->aOp[p->nOp-1].zComment;
55678     va_start(ap, zFormat);
55679     sqlite3DbFree(p->db, *pz);
55680     *pz = sqlite3VMPrintf(p->db, zFormat, ap);
55681     va_end(ap);
55682   }
55683 }
55684 SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
55685   va_list ap;
55686   if( !p ) return;
55687   sqlite3VdbeAddOp0(p, OP_Noop);
55688   assert( p->nOp>0 || p->aOp==0 );
55689   assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
55690   if( p->nOp ){
55691     char **pz = &p->aOp[p->nOp-1].zComment;
55692     va_start(ap, zFormat);
55693     sqlite3DbFree(p->db, *pz);
55694     *pz = sqlite3VMPrintf(p->db, zFormat, ap);
55695     va_end(ap);
55696   }
55697 }
55698 #endif  /* NDEBUG */
55699
55700 /*
55701 ** Return the opcode for a given address.  If the address is -1, then
55702 ** return the most recently inserted opcode.
55703 **
55704 ** If a memory allocation error has occurred prior to the calling of this
55705 ** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode
55706 ** is readable but not writable, though it is cast to a writable value.
55707 ** The return of a dummy opcode allows the call to continue functioning
55708 ** after a OOM fault without having to check to see if the return from 
55709 ** this routine is a valid pointer.  But because the dummy.opcode is 0,
55710 ** dummy will never be written to.  This is verified by code inspection and
55711 ** by running with Valgrind.
55712 **
55713 ** About the #ifdef SQLITE_OMIT_TRACE:  Normally, this routine is never called
55714 ** unless p->nOp>0.  This is because in the absense of SQLITE_OMIT_TRACE,
55715 ** an OP_Trace instruction is always inserted by sqlite3VdbeGet() as soon as
55716 ** a new VDBE is created.  So we are free to set addr to p->nOp-1 without
55717 ** having to double-check to make sure that the result is non-negative. But
55718 ** if SQLITE_OMIT_TRACE is defined, the OP_Trace is omitted and we do need to
55719 ** check the value of p->nOp-1 before continuing.
55720 */
55721 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
55722   /* C89 specifies that the constant "dummy" will be initialized to all
55723   ** zeros, which is correct.  MSVC generates a warning, nevertheless. */
55724   static const VdbeOp dummy;  /* Ignore the MSVC warning about no initializer */
55725   assert( p->magic==VDBE_MAGIC_INIT );
55726   if( addr<0 ){
55727 #ifdef SQLITE_OMIT_TRACE
55728     if( p->nOp==0 ) return (VdbeOp*)&dummy;
55729 #endif
55730     addr = p->nOp - 1;
55731   }
55732   assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
55733   if( p->db->mallocFailed ){
55734     return (VdbeOp*)&dummy;
55735   }else{
55736     return &p->aOp[addr];
55737   }
55738 }
55739
55740 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
55741      || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
55742 /*
55743 ** Compute a string that describes the P4 parameter for an opcode.
55744 ** Use zTemp for any required temporary buffer space.
55745 */
55746 static char *displayP4(Op *pOp, char *zTemp, int nTemp){
55747   char *zP4 = zTemp;
55748   assert( nTemp>=20 );
55749   switch( pOp->p4type ){
55750     case P4_KEYINFO_STATIC:
55751     case P4_KEYINFO: {
55752       int i, j;
55753       KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
55754       sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
55755       i = sqlite3Strlen30(zTemp);
55756       for(j=0; j<pKeyInfo->nField; j++){
55757         CollSeq *pColl = pKeyInfo->aColl[j];
55758         if( pColl ){
55759           int n = sqlite3Strlen30(pColl->zName);
55760           if( i+n>nTemp-6 ){
55761             memcpy(&zTemp[i],",...",4);
55762             break;
55763           }
55764           zTemp[i++] = ',';
55765           if( pKeyInfo->aSortOrder && pKeyInfo->aSortOrder[j] ){
55766             zTemp[i++] = '-';
55767           }
55768           memcpy(&zTemp[i], pColl->zName,n+1);
55769           i += n;
55770         }else if( i+4<nTemp-6 ){
55771           memcpy(&zTemp[i],",nil",4);
55772           i += 4;
55773         }
55774       }
55775       zTemp[i++] = ')';
55776       zTemp[i] = 0;
55777       assert( i<nTemp );
55778       break;
55779     }
55780     case P4_COLLSEQ: {
55781       CollSeq *pColl = pOp->p4.pColl;
55782       sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
55783       break;
55784     }
55785     case P4_FUNCDEF: {
55786       FuncDef *pDef = pOp->p4.pFunc;
55787       sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
55788       break;
55789     }
55790     case P4_INT64: {
55791       sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
55792       break;
55793     }
55794     case P4_INT32: {
55795       sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
55796       break;
55797     }
55798     case P4_REAL: {
55799       sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
55800       break;
55801     }
55802     case P4_MEM: {
55803       Mem *pMem = pOp->p4.pMem;
55804       assert( (pMem->flags & MEM_Null)==0 );
55805       if( pMem->flags & MEM_Str ){
55806         zP4 = pMem->z;
55807       }else if( pMem->flags & MEM_Int ){
55808         sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
55809       }else if( pMem->flags & MEM_Real ){
55810         sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
55811       }else{
55812         assert( pMem->flags & MEM_Blob );
55813         zP4 = "(blob)";
55814       }
55815       break;
55816     }
55817 #ifndef SQLITE_OMIT_VIRTUALTABLE
55818     case P4_VTAB: {
55819       sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
55820       sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
55821       break;
55822     }
55823 #endif
55824     case P4_INTARRAY: {
55825       sqlite3_snprintf(nTemp, zTemp, "intarray");
55826       break;
55827     }
55828     case P4_SUBPROGRAM: {
55829       sqlite3_snprintf(nTemp, zTemp, "program");
55830       break;
55831     }
55832     default: {
55833       zP4 = pOp->p4.z;
55834       if( zP4==0 ){
55835         zP4 = zTemp;
55836         zTemp[0] = 0;
55837       }
55838     }
55839   }
55840   assert( zP4!=0 );
55841   return zP4;
55842 }
55843 #endif
55844
55845 /*
55846 ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
55847 **
55848 ** The prepared statement has to know in advance which Btree objects
55849 ** will be used so that it can acquire mutexes on them all in sorted
55850 ** order (via sqlite3VdbeMutexArrayEnter().  Mutexes are acquired
55851 ** in order (and released in reverse order) to avoid deadlocks.
55852 */
55853 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
55854   int mask;
55855   assert( i>=0 && i<p->db->nDb && i<sizeof(u32)*8 );
55856   assert( i<(int)sizeof(p->btreeMask)*8 );
55857   mask = ((u32)1)<<i;
55858   if( (p->btreeMask & mask)==0 ){
55859     p->btreeMask |= mask;
55860     sqlite3BtreeMutexArrayInsert(&p->aMutex, p->db->aDb[i].pBt);
55861   }
55862 }
55863
55864
55865 #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
55866 /*
55867 ** Print a single opcode.  This routine is used for debugging only.
55868 */
55869 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
55870   char *zP4;
55871   char zPtr[50];
55872   static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n";
55873   if( pOut==0 ) pOut = stdout;
55874   zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
55875   fprintf(pOut, zFormat1, pc, 
55876       sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
55877 #ifdef SQLITE_DEBUG
55878       pOp->zComment ? pOp->zComment : ""
55879 #else
55880       ""
55881 #endif
55882   );
55883   fflush(pOut);
55884 }
55885 #endif
55886
55887 /*
55888 ** Release an array of N Mem elements
55889 */
55890 static void releaseMemArray(Mem *p, int N){
55891   if( p && N ){
55892     Mem *pEnd;
55893     sqlite3 *db = p->db;
55894     u8 malloc_failed = db->mallocFailed;
55895     if( db->pnBytesFreed ){
55896       for(pEnd=&p[N]; p<pEnd; p++){
55897         sqlite3DbFree(db, p->zMalloc);
55898       }
55899       return;
55900     }
55901     for(pEnd=&p[N]; p<pEnd; p++){
55902       assert( (&p[1])==pEnd || p[0].db==p[1].db );
55903
55904       /* This block is really an inlined version of sqlite3VdbeMemRelease()
55905       ** that takes advantage of the fact that the memory cell value is 
55906       ** being set to NULL after releasing any dynamic resources.
55907       **
55908       ** The justification for duplicating code is that according to 
55909       ** callgrind, this causes a certain test case to hit the CPU 4.7 
55910       ** percent less (x86 linux, gcc version 4.1.2, -O6) than if 
55911       ** sqlite3MemRelease() were called from here. With -O2, this jumps
55912       ** to 6.6 percent. The test case is inserting 1000 rows into a table 
55913       ** with no indexes using a single prepared INSERT statement, bind() 
55914       ** and reset(). Inserts are grouped into a transaction.
55915       */
55916       if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
55917         sqlite3VdbeMemRelease(p);
55918       }else if( p->zMalloc ){
55919         sqlite3DbFree(db, p->zMalloc);
55920         p->zMalloc = 0;
55921       }
55922
55923       p->flags = MEM_Null;
55924     }
55925     db->mallocFailed = malloc_failed;
55926   }
55927 }
55928
55929 /*
55930 ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
55931 ** allocated by the OP_Program opcode in sqlite3VdbeExec().
55932 */
55933 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
55934   int i;
55935   Mem *aMem = VdbeFrameMem(p);
55936   VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
55937   for(i=0; i<p->nChildCsr; i++){
55938     sqlite3VdbeFreeCursor(p->v, apCsr[i]);
55939   }
55940   releaseMemArray(aMem, p->nChildMem);
55941   sqlite3DbFree(p->v->db, p);
55942 }
55943
55944 #ifndef SQLITE_OMIT_EXPLAIN
55945 /*
55946 ** Give a listing of the program in the virtual machine.
55947 **
55948 ** The interface is the same as sqlite3VdbeExec().  But instead of
55949 ** running the code, it invokes the callback once for each instruction.
55950 ** This feature is used to implement "EXPLAIN".
55951 **
55952 ** When p->explain==1, each instruction is listed.  When
55953 ** p->explain==2, only OP_Explain instructions are listed and these
55954 ** are shown in a different format.  p->explain==2 is used to implement
55955 ** EXPLAIN QUERY PLAN.
55956 **
55957 ** When p->explain==1, first the main program is listed, then each of
55958 ** the trigger subprograms are listed one by one.
55959 */
55960 SQLITE_PRIVATE int sqlite3VdbeList(
55961   Vdbe *p                   /* The VDBE */
55962 ){
55963   int nRow;                            /* Stop when row count reaches this */
55964   int nSub = 0;                        /* Number of sub-vdbes seen so far */
55965   SubProgram **apSub = 0;              /* Array of sub-vdbes */
55966   Mem *pSub = 0;                       /* Memory cell hold array of subprogs */
55967   sqlite3 *db = p->db;                 /* The database connection */
55968   int i;                               /* Loop counter */
55969   int rc = SQLITE_OK;                  /* Return code */
55970   Mem *pMem = p->pResultSet = &p->aMem[1];  /* First Mem of result set */
55971
55972   assert( p->explain );
55973   assert( p->magic==VDBE_MAGIC_RUN );
55974   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
55975
55976   /* Even though this opcode does not use dynamic strings for
55977   ** the result, result columns may become dynamic if the user calls
55978   ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
55979   */
55980   releaseMemArray(pMem, 8);
55981
55982   if( p->rc==SQLITE_NOMEM ){
55983     /* This happens if a malloc() inside a call to sqlite3_column_text() or
55984     ** sqlite3_column_text16() failed.  */
55985     db->mallocFailed = 1;
55986     return SQLITE_ERROR;
55987   }
55988
55989   /* When the number of output rows reaches nRow, that means the
55990   ** listing has finished and sqlite3_step() should return SQLITE_DONE.
55991   ** nRow is the sum of the number of rows in the main program, plus
55992   ** the sum of the number of rows in all trigger subprograms encountered
55993   ** so far.  The nRow value will increase as new trigger subprograms are
55994   ** encountered, but p->pc will eventually catch up to nRow.
55995   */
55996   nRow = p->nOp;
55997   if( p->explain==1 ){
55998     /* The first 8 memory cells are used for the result set.  So we will
55999     ** commandeer the 9th cell to use as storage for an array of pointers
56000     ** to trigger subprograms.  The VDBE is guaranteed to have at least 9
56001     ** cells.  */
56002     assert( p->nMem>9 );
56003     pSub = &p->aMem[9];
56004     if( pSub->flags&MEM_Blob ){
56005       /* On the first call to sqlite3_step(), pSub will hold a NULL.  It is
56006       ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
56007       nSub = pSub->n/sizeof(Vdbe*);
56008       apSub = (SubProgram **)pSub->z;
56009     }
56010     for(i=0; i<nSub; i++){
56011       nRow += apSub[i]->nOp;
56012     }
56013   }
56014
56015   do{
56016     i = p->pc++;
56017   }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
56018   if( i>=nRow ){
56019     p->rc = SQLITE_OK;
56020     rc = SQLITE_DONE;
56021   }else if( db->u1.isInterrupted ){
56022     p->rc = SQLITE_INTERRUPT;
56023     rc = SQLITE_ERROR;
56024     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
56025   }else{
56026     char *z;
56027     Op *pOp;
56028     if( i<p->nOp ){
56029       /* The output line number is small enough that we are still in the
56030       ** main program. */
56031       pOp = &p->aOp[i];
56032     }else{
56033       /* We are currently listing subprograms.  Figure out which one and
56034       ** pick up the appropriate opcode. */
56035       int j;
56036       i -= p->nOp;
56037       for(j=0; i>=apSub[j]->nOp; j++){
56038         i -= apSub[j]->nOp;
56039       }
56040       pOp = &apSub[j]->aOp[i];
56041     }
56042     if( p->explain==1 ){
56043       pMem->flags = MEM_Int;
56044       pMem->type = SQLITE_INTEGER;
56045       pMem->u.i = i;                                /* Program counter */
56046       pMem++;
56047   
56048       pMem->flags = MEM_Static|MEM_Str|MEM_Term;
56049       pMem->z = (char*)sqlite3OpcodeName(pOp->opcode);  /* Opcode */
56050       assert( pMem->z!=0 );
56051       pMem->n = sqlite3Strlen30(pMem->z);
56052       pMem->type = SQLITE_TEXT;
56053       pMem->enc = SQLITE_UTF8;
56054       pMem++;
56055
56056       /* When an OP_Program opcode is encounter (the only opcode that has
56057       ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
56058       ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
56059       ** has not already been seen.
56060       */
56061       if( pOp->p4type==P4_SUBPROGRAM ){
56062         int nByte = (nSub+1)*sizeof(SubProgram*);
56063         int j;
56064         for(j=0; j<nSub; j++){
56065           if( apSub[j]==pOp->p4.pProgram ) break;
56066         }
56067         if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, 1) ){
56068           apSub = (SubProgram **)pSub->z;
56069           apSub[nSub++] = pOp->p4.pProgram;
56070           pSub->flags |= MEM_Blob;
56071           pSub->n = nSub*sizeof(SubProgram*);
56072         }
56073       }
56074     }
56075
56076     pMem->flags = MEM_Int;
56077     pMem->u.i = pOp->p1;                          /* P1 */
56078     pMem->type = SQLITE_INTEGER;
56079     pMem++;
56080
56081     pMem->flags = MEM_Int;
56082     pMem->u.i = pOp->p2;                          /* P2 */
56083     pMem->type = SQLITE_INTEGER;
56084     pMem++;
56085
56086     if( p->explain==1 ){
56087       pMem->flags = MEM_Int;
56088       pMem->u.i = pOp->p3;                          /* P3 */
56089       pMem->type = SQLITE_INTEGER;
56090       pMem++;
56091     }
56092
56093     if( sqlite3VdbeMemGrow(pMem, 32, 0) ){            /* P4 */
56094       assert( p->db->mallocFailed );
56095       return SQLITE_ERROR;
56096     }
56097     pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
56098     z = displayP4(pOp, pMem->z, 32);
56099     if( z!=pMem->z ){
56100       sqlite3VdbeMemSetStr(pMem, z, -1, SQLITE_UTF8, 0);
56101     }else{
56102       assert( pMem->z!=0 );
56103       pMem->n = sqlite3Strlen30(pMem->z);
56104       pMem->enc = SQLITE_UTF8;
56105     }
56106     pMem->type = SQLITE_TEXT;
56107     pMem++;
56108
56109     if( p->explain==1 ){
56110       if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
56111         assert( p->db->mallocFailed );
56112         return SQLITE_ERROR;
56113       }
56114       pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
56115       pMem->n = 2;
56116       sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
56117       pMem->type = SQLITE_TEXT;
56118       pMem->enc = SQLITE_UTF8;
56119       pMem++;
56120   
56121 #ifdef SQLITE_DEBUG
56122       if( pOp->zComment ){
56123         pMem->flags = MEM_Str|MEM_Term;
56124         pMem->z = pOp->zComment;
56125         pMem->n = sqlite3Strlen30(pMem->z);
56126         pMem->enc = SQLITE_UTF8;
56127         pMem->type = SQLITE_TEXT;
56128       }else
56129 #endif
56130       {
56131         pMem->flags = MEM_Null;                       /* Comment */
56132         pMem->type = SQLITE_NULL;
56133       }
56134     }
56135
56136     p->nResColumn = 8 - 5*(p->explain-1);
56137     p->rc = SQLITE_OK;
56138     rc = SQLITE_ROW;
56139   }
56140   return rc;
56141 }
56142 #endif /* SQLITE_OMIT_EXPLAIN */
56143
56144 #ifdef SQLITE_DEBUG
56145 /*
56146 ** Print the SQL that was used to generate a VDBE program.
56147 */
56148 SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
56149   int nOp = p->nOp;
56150   VdbeOp *pOp;
56151   if( nOp<1 ) return;
56152   pOp = &p->aOp[0];
56153   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
56154     const char *z = pOp->p4.z;
56155     while( sqlite3Isspace(*z) ) z++;
56156     printf("SQL: [%s]\n", z);
56157   }
56158 }
56159 #endif
56160
56161 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
56162 /*
56163 ** Print an IOTRACE message showing SQL content.
56164 */
56165 SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
56166   int nOp = p->nOp;
56167   VdbeOp *pOp;
56168   if( sqlite3IoTrace==0 ) return;
56169   if( nOp<1 ) return;
56170   pOp = &p->aOp[0];
56171   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
56172     int i, j;
56173     char z[1000];
56174     sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
56175     for(i=0; sqlite3Isspace(z[i]); i++){}
56176     for(j=0; z[i]; i++){
56177       if( sqlite3Isspace(z[i]) ){
56178         if( z[i-1]!=' ' ){
56179           z[j++] = ' ';
56180         }
56181       }else{
56182         z[j++] = z[i];
56183       }
56184     }
56185     z[j] = 0;
56186     sqlite3IoTrace("SQL %s\n", z);
56187   }
56188 }
56189 #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
56190
56191 /*
56192 ** Allocate space from a fixed size buffer and return a pointer to
56193 ** that space.  If insufficient space is available, return NULL.
56194 **
56195 ** The pBuf parameter is the initial value of a pointer which will
56196 ** receive the new memory.  pBuf is normally NULL.  If pBuf is not
56197 ** NULL, it means that memory space has already been allocated and that
56198 ** this routine should not allocate any new memory.  When pBuf is not
56199 ** NULL simply return pBuf.  Only allocate new memory space when pBuf
56200 ** is NULL.
56201 **
56202 ** nByte is the number of bytes of space needed.
56203 **
56204 ** *ppFrom points to available space and pEnd points to the end of the
56205 ** available space.  When space is allocated, *ppFrom is advanced past
56206 ** the end of the allocated space.
56207 **
56208 ** *pnByte is a counter of the number of bytes of space that have failed
56209 ** to allocate.  If there is insufficient space in *ppFrom to satisfy the
56210 ** request, then increment *pnByte by the amount of the request.
56211 */
56212 static void *allocSpace(
56213   void *pBuf,          /* Where return pointer will be stored */
56214   int nByte,           /* Number of bytes to allocate */
56215   u8 **ppFrom,         /* IN/OUT: Allocate from *ppFrom */
56216   u8 *pEnd,            /* Pointer to 1 byte past the end of *ppFrom buffer */
56217   int *pnByte          /* If allocation cannot be made, increment *pnByte */
56218 ){
56219   assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
56220   if( pBuf ) return pBuf;
56221   nByte = ROUND8(nByte);
56222   if( &(*ppFrom)[nByte] <= pEnd ){
56223     pBuf = (void*)*ppFrom;
56224     *ppFrom += nByte;
56225   }else{
56226     *pnByte += nByte;
56227   }
56228   return pBuf;
56229 }
56230
56231 /*
56232 ** Prepare a virtual machine for execution.  This involves things such
56233 ** as allocating stack space and initializing the program counter.
56234 ** After the VDBE has be prepped, it can be executed by one or more
56235 ** calls to sqlite3VdbeExec().  
56236 **
56237 ** This is the only way to move a VDBE from VDBE_MAGIC_INIT to
56238 ** VDBE_MAGIC_RUN.
56239 **
56240 ** This function may be called more than once on a single virtual machine.
56241 ** The first call is made while compiling the SQL statement. Subsequent
56242 ** calls are made as part of the process of resetting a statement to be
56243 ** re-executed (from a call to sqlite3_reset()). The nVar, nMem, nCursor 
56244 ** and isExplain parameters are only passed correct values the first time
56245 ** the function is called. On subsequent calls, from sqlite3_reset(), nVar
56246 ** is passed -1 and nMem, nCursor and isExplain are all passed zero.
56247 */
56248 SQLITE_PRIVATE void sqlite3VdbeMakeReady(
56249   Vdbe *p,                       /* The VDBE */
56250   int nVar,                      /* Number of '?' see in the SQL statement */
56251   int nMem,                      /* Number of memory cells to allocate */
56252   int nCursor,                   /* Number of cursors to allocate */
56253   int nArg,                      /* Maximum number of args in SubPrograms */
56254   int isExplain,                 /* True if the EXPLAIN keywords is present */
56255   int usesStmtJournal            /* True to set Vdbe.usesStmtJournal */
56256 ){
56257   int n;
56258   sqlite3 *db = p->db;
56259
56260   assert( p!=0 );
56261   assert( p->magic==VDBE_MAGIC_INIT );
56262
56263   /* There should be at least one opcode.
56264   */
56265   assert( p->nOp>0 );
56266
56267   /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
56268   p->magic = VDBE_MAGIC_RUN;
56269
56270   /* For each cursor required, also allocate a memory cell. Memory
56271   ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
56272   ** the vdbe program. Instead they are used to allocate space for
56273   ** VdbeCursor/BtCursor structures. The blob of memory associated with 
56274   ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
56275   ** stores the blob of memory associated with cursor 1, etc.
56276   **
56277   ** See also: allocateCursor().
56278   */
56279   nMem += nCursor;
56280
56281   /* Allocate space for memory registers, SQL variables, VDBE cursors and 
56282   ** an array to marshal SQL function arguments in. This is only done the
56283   ** first time this function is called for a given VDBE, not when it is
56284   ** being called from sqlite3_reset() to reset the virtual machine.
56285   */
56286   if( nVar>=0 && ALWAYS(db->mallocFailed==0) ){
56287     u8 *zCsr = (u8 *)&p->aOp[p->nOp];       /* Memory avaliable for alloation */
56288     u8 *zEnd = (u8 *)&p->aOp[p->nOpAlloc];  /* First byte past available mem */
56289     int nByte;                              /* How much extra memory needed */
56290
56291     resolveP2Values(p, &nArg);
56292     p->usesStmtJournal = (u8)usesStmtJournal;
56293     if( isExplain && nMem<10 ){
56294       nMem = 10;
56295     }
56296     memset(zCsr, 0, zEnd-zCsr);
56297     zCsr += (zCsr - (u8*)0)&7;
56298     assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
56299
56300     /* Memory for registers, parameters, cursor, etc, is allocated in two
56301     ** passes.  On the first pass, we try to reuse unused space at the 
56302     ** end of the opcode array.  If we are unable to satisfy all memory
56303     ** requirements by reusing the opcode array tail, then the second
56304     ** pass will fill in the rest using a fresh allocation.  
56305     **
56306     ** This two-pass approach that reuses as much memory as possible from
56307     ** the leftover space at the end of the opcode array can significantly
56308     ** reduce the amount of memory held by a prepared statement.
56309     */
56310     do {
56311       nByte = 0;
56312       p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
56313       p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
56314       p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
56315       p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
56316       p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
56317                             &zCsr, zEnd, &nByte);
56318       if( nByte ){
56319         p->pFree = sqlite3DbMallocZero(db, nByte);
56320       }
56321       zCsr = p->pFree;
56322       zEnd = &zCsr[nByte];
56323     }while( nByte && !db->mallocFailed );
56324
56325     p->nCursor = (u16)nCursor;
56326     if( p->aVar ){
56327       p->nVar = (ynVar)nVar;
56328       for(n=0; n<nVar; n++){
56329         p->aVar[n].flags = MEM_Null;
56330         p->aVar[n].db = db;
56331       }
56332     }
56333     if( p->aMem ){
56334       p->aMem--;                      /* aMem[] goes from 1..nMem */
56335       p->nMem = nMem;                 /*       not from 0..nMem-1 */
56336       for(n=1; n<=nMem; n++){
56337         p->aMem[n].flags = MEM_Null;
56338         p->aMem[n].db = db;
56339       }
56340     }
56341   }
56342 #ifdef SQLITE_DEBUG
56343   for(n=1; n<p->nMem; n++){
56344     assert( p->aMem[n].db==db );
56345   }
56346 #endif
56347
56348   p->pc = -1;
56349   p->rc = SQLITE_OK;
56350   p->errorAction = OE_Abort;
56351   p->explain |= isExplain;
56352   p->magic = VDBE_MAGIC_RUN;
56353   p->nChange = 0;
56354   p->cacheCtr = 1;
56355   p->minWriteFileFormat = 255;
56356   p->iStatement = 0;
56357   p->nFkConstraint = 0;
56358 #ifdef VDBE_PROFILE
56359   {
56360     int i;
56361     for(i=0; i<p->nOp; i++){
56362       p->aOp[i].cnt = 0;
56363       p->aOp[i].cycles = 0;
56364     }
56365   }
56366 #endif
56367 }
56368
56369 /*
56370 ** Close a VDBE cursor and release all the resources that cursor 
56371 ** happens to hold.
56372 */
56373 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
56374   if( pCx==0 ){
56375     return;
56376   }
56377   if( pCx->pBt ){
56378     sqlite3BtreeClose(pCx->pBt);
56379     /* The pCx->pCursor will be close automatically, if it exists, by
56380     ** the call above. */
56381   }else if( pCx->pCursor ){
56382     sqlite3BtreeCloseCursor(pCx->pCursor);
56383   }
56384 #ifndef SQLITE_OMIT_VIRTUALTABLE
56385   if( pCx->pVtabCursor ){
56386     sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
56387     const sqlite3_module *pModule = pCx->pModule;
56388     p->inVtabMethod = 1;
56389     pModule->xClose(pVtabCursor);
56390     p->inVtabMethod = 0;
56391   }
56392 #endif
56393 }
56394
56395 /*
56396 ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
56397 ** is used, for example, when a trigger sub-program is halted to restore
56398 ** control to the main program.
56399 */
56400 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
56401   Vdbe *v = pFrame->v;
56402   v->aOp = pFrame->aOp;
56403   v->nOp = pFrame->nOp;
56404   v->aMem = pFrame->aMem;
56405   v->nMem = pFrame->nMem;
56406   v->apCsr = pFrame->apCsr;
56407   v->nCursor = pFrame->nCursor;
56408   v->db->lastRowid = pFrame->lastRowid;
56409   v->nChange = pFrame->nChange;
56410   return pFrame->pc;
56411 }
56412
56413 /*
56414 ** Close all cursors.
56415 **
56416 ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory 
56417 ** cell array. This is necessary as the memory cell array may contain
56418 ** pointers to VdbeFrame objects, which may in turn contain pointers to
56419 ** open cursors.
56420 */
56421 static void closeAllCursors(Vdbe *p){
56422   if( p->pFrame ){
56423     VdbeFrame *pFrame = p->pFrame;
56424     for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
56425     sqlite3VdbeFrameRestore(pFrame);
56426   }
56427   p->pFrame = 0;
56428   p->nFrame = 0;
56429
56430   if( p->apCsr ){
56431     int i;
56432     for(i=0; i<p->nCursor; i++){
56433       VdbeCursor *pC = p->apCsr[i];
56434       if( pC ){
56435         sqlite3VdbeFreeCursor(p, pC);
56436         p->apCsr[i] = 0;
56437       }
56438     }
56439   }
56440   if( p->aMem ){
56441     releaseMemArray(&p->aMem[1], p->nMem);
56442   }
56443 }
56444
56445 /*
56446 ** Clean up the VM after execution.
56447 **
56448 ** This routine will automatically close any cursors, lists, and/or
56449 ** sorters that were left open.  It also deletes the values of
56450 ** variables in the aVar[] array.
56451 */
56452 static void Cleanup(Vdbe *p){
56453   sqlite3 *db = p->db;
56454
56455 #ifdef SQLITE_DEBUG
56456   /* Execute assert() statements to ensure that the Vdbe.apCsr[] and 
56457   ** Vdbe.aMem[] arrays have already been cleaned up.  */
56458   int i;
56459   for(i=0; i<p->nCursor; i++) assert( p->apCsr==0 || p->apCsr[i]==0 );
56460   for(i=1; i<=p->nMem; i++) assert( p->aMem==0 || p->aMem[i].flags==MEM_Null );
56461 #endif
56462
56463   sqlite3DbFree(db, p->zErrMsg);
56464   p->zErrMsg = 0;
56465   p->pResultSet = 0;
56466 }
56467
56468 /*
56469 ** Set the number of result columns that will be returned by this SQL
56470 ** statement. This is now set at compile time, rather than during
56471 ** execution of the vdbe program so that sqlite3_column_count() can
56472 ** be called on an SQL statement before sqlite3_step().
56473 */
56474 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
56475   Mem *pColName;
56476   int n;
56477   sqlite3 *db = p->db;
56478
56479   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
56480   sqlite3DbFree(db, p->aColName);
56481   n = nResColumn*COLNAME_N;
56482   p->nResColumn = (u16)nResColumn;
56483   p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
56484   if( p->aColName==0 ) return;
56485   while( n-- > 0 ){
56486     pColName->flags = MEM_Null;
56487     pColName->db = p->db;
56488     pColName++;
56489   }
56490 }
56491
56492 /*
56493 ** Set the name of the idx'th column to be returned by the SQL statement.
56494 ** zName must be a pointer to a nul terminated string.
56495 **
56496 ** This call must be made after a call to sqlite3VdbeSetNumCols().
56497 **
56498 ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
56499 ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
56500 ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
56501 */
56502 SQLITE_PRIVATE int sqlite3VdbeSetColName(
56503   Vdbe *p,                         /* Vdbe being configured */
56504   int idx,                         /* Index of column zName applies to */
56505   int var,                         /* One of the COLNAME_* constants */
56506   const char *zName,               /* Pointer to buffer containing name */
56507   void (*xDel)(void*)              /* Memory management strategy for zName */
56508 ){
56509   int rc;
56510   Mem *pColName;
56511   assert( idx<p->nResColumn );
56512   assert( var<COLNAME_N );
56513   if( p->db->mallocFailed ){
56514     assert( !zName || xDel!=SQLITE_DYNAMIC );
56515     return SQLITE_NOMEM;
56516   }
56517   assert( p->aColName!=0 );
56518   pColName = &(p->aColName[idx+var*p->nResColumn]);
56519   rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
56520   assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
56521   return rc;
56522 }
56523
56524 /*
56525 ** A read or write transaction may or may not be active on database handle
56526 ** db. If a transaction is active, commit it. If there is a
56527 ** write-transaction spanning more than one database file, this routine
56528 ** takes care of the master journal trickery.
56529 */
56530 static int vdbeCommit(sqlite3 *db, Vdbe *p){
56531   int i;
56532   int nTrans = 0;  /* Number of databases with an active write-transaction */
56533   int rc = SQLITE_OK;
56534   int needXcommit = 0;
56535
56536 #ifdef SQLITE_OMIT_VIRTUALTABLE
56537   /* With this option, sqlite3VtabSync() is defined to be simply 
56538   ** SQLITE_OK so p is not used. 
56539   */
56540   UNUSED_PARAMETER(p);
56541 #endif
56542
56543   /* Before doing anything else, call the xSync() callback for any
56544   ** virtual module tables written in this transaction. This has to
56545   ** be done before determining whether a master journal file is 
56546   ** required, as an xSync() callback may add an attached database
56547   ** to the transaction.
56548   */
56549   rc = sqlite3VtabSync(db, &p->zErrMsg);
56550
56551   /* This loop determines (a) if the commit hook should be invoked and
56552   ** (b) how many database files have open write transactions, not 
56553   ** including the temp database. (b) is important because if more than 
56554   ** one database file has an open write transaction, a master journal
56555   ** file is required for an atomic commit.
56556   */ 
56557   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 
56558     Btree *pBt = db->aDb[i].pBt;
56559     if( sqlite3BtreeIsInTrans(pBt) ){
56560       needXcommit = 1;
56561       if( i!=1 ) nTrans++;
56562       rc = sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt));
56563     }
56564   }
56565   if( rc!=SQLITE_OK ){
56566     return rc;
56567   }
56568
56569   /* If there are any write-transactions at all, invoke the commit hook */
56570   if( needXcommit && db->xCommitCallback ){
56571     rc = db->xCommitCallback(db->pCommitArg);
56572     if( rc ){
56573       return SQLITE_CONSTRAINT;
56574     }
56575   }
56576
56577   /* The simple case - no more than one database file (not counting the
56578   ** TEMP database) has a transaction active.   There is no need for the
56579   ** master-journal.
56580   **
56581   ** If the return value of sqlite3BtreeGetFilename() is a zero length
56582   ** string, it means the main database is :memory: or a temp file.  In 
56583   ** that case we do not support atomic multi-file commits, so use the 
56584   ** simple case then too.
56585   */
56586   if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
56587    || nTrans<=1
56588   ){
56589     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
56590       Btree *pBt = db->aDb[i].pBt;
56591       if( pBt ){
56592         rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
56593       }
56594     }
56595
56596     /* Do the commit only if all databases successfully complete phase 1. 
56597     ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
56598     ** IO error while deleting or truncating a journal file. It is unlikely,
56599     ** but could happen. In this case abandon processing and return the error.
56600     */
56601     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
56602       Btree *pBt = db->aDb[i].pBt;
56603       if( pBt ){
56604         rc = sqlite3BtreeCommitPhaseTwo(pBt);
56605       }
56606     }
56607     if( rc==SQLITE_OK ){
56608       sqlite3VtabCommit(db);
56609     }
56610   }
56611
56612   /* The complex case - There is a multi-file write-transaction active.
56613   ** This requires a master journal file to ensure the transaction is
56614   ** committed atomicly.
56615   */
56616 #ifndef SQLITE_OMIT_DISKIO
56617   else{
56618     sqlite3_vfs *pVfs = db->pVfs;
56619     int needSync = 0;
56620     char *zMaster = 0;   /* File-name for the master journal */
56621     char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
56622     sqlite3_file *pMaster = 0;
56623     i64 offset = 0;
56624     int res;
56625
56626     /* Select a master journal file name */
56627     do {
56628       u32 iRandom;
56629       sqlite3DbFree(db, zMaster);
56630       sqlite3_randomness(sizeof(iRandom), &iRandom);
56631       zMaster = sqlite3MPrintf(db, "%s-mj%08X", zMainFile, iRandom&0x7fffffff);
56632       if( !zMaster ){
56633         return SQLITE_NOMEM;
56634       }
56635       rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
56636     }while( rc==SQLITE_OK && res );
56637     if( rc==SQLITE_OK ){
56638       /* Open the master journal. */
56639       rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster, 
56640           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
56641           SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
56642       );
56643     }
56644     if( rc!=SQLITE_OK ){
56645       sqlite3DbFree(db, zMaster);
56646       return rc;
56647     }
56648  
56649     /* Write the name of each database file in the transaction into the new
56650     ** master journal file. If an error occurs at this point close
56651     ** and delete the master journal file. All the individual journal files
56652     ** still have 'null' as the master journal pointer, so they will roll
56653     ** back independently if a failure occurs.
56654     */
56655     for(i=0; i<db->nDb; i++){
56656       Btree *pBt = db->aDb[i].pBt;
56657       if( sqlite3BtreeIsInTrans(pBt) ){
56658         char const *zFile = sqlite3BtreeGetJournalname(pBt);
56659         if( zFile==0 ){
56660           continue;  /* Ignore TEMP and :memory: databases */
56661         }
56662         assert( zFile[0]!=0 );
56663         if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
56664           needSync = 1;
56665         }
56666         rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
56667         offset += sqlite3Strlen30(zFile)+1;
56668         if( rc!=SQLITE_OK ){
56669           sqlite3OsCloseFree(pMaster);
56670           sqlite3OsDelete(pVfs, zMaster, 0);
56671           sqlite3DbFree(db, zMaster);
56672           return rc;
56673         }
56674       }
56675     }
56676
56677     /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
56678     ** flag is set this is not required.
56679     */
56680     if( needSync 
56681      && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
56682      && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
56683     ){
56684       sqlite3OsCloseFree(pMaster);
56685       sqlite3OsDelete(pVfs, zMaster, 0);
56686       sqlite3DbFree(db, zMaster);
56687       return rc;
56688     }
56689
56690     /* Sync all the db files involved in the transaction. The same call
56691     ** sets the master journal pointer in each individual journal. If
56692     ** an error occurs here, do not delete the master journal file.
56693     **
56694     ** If the error occurs during the first call to
56695     ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
56696     ** master journal file will be orphaned. But we cannot delete it,
56697     ** in case the master journal file name was written into the journal
56698     ** file before the failure occurred.
56699     */
56700     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 
56701       Btree *pBt = db->aDb[i].pBt;
56702       if( pBt ){
56703         rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
56704       }
56705     }
56706     sqlite3OsCloseFree(pMaster);
56707     assert( rc!=SQLITE_BUSY );
56708     if( rc!=SQLITE_OK ){
56709       sqlite3DbFree(db, zMaster);
56710       return rc;
56711     }
56712
56713     /* Delete the master journal file. This commits the transaction. After
56714     ** doing this the directory is synced again before any individual
56715     ** transaction files are deleted.
56716     */
56717     rc = sqlite3OsDelete(pVfs, zMaster, 1);
56718     sqlite3DbFree(db, zMaster);
56719     zMaster = 0;
56720     if( rc ){
56721       return rc;
56722     }
56723
56724     /* All files and directories have already been synced, so the following
56725     ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
56726     ** deleting or truncating journals. If something goes wrong while
56727     ** this is happening we don't really care. The integrity of the
56728     ** transaction is already guaranteed, but some stray 'cold' journals
56729     ** may be lying around. Returning an error code won't help matters.
56730     */
56731     disable_simulated_io_errors();
56732     sqlite3BeginBenignMalloc();
56733     for(i=0; i<db->nDb; i++){ 
56734       Btree *pBt = db->aDb[i].pBt;
56735       if( pBt ){
56736         sqlite3BtreeCommitPhaseTwo(pBt);
56737       }
56738     }
56739     sqlite3EndBenignMalloc();
56740     enable_simulated_io_errors();
56741
56742     sqlite3VtabCommit(db);
56743   }
56744 #endif
56745
56746   return rc;
56747 }
56748
56749 /* 
56750 ** This routine checks that the sqlite3.activeVdbeCnt count variable
56751 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
56752 ** currently active. An assertion fails if the two counts do not match.
56753 ** This is an internal self-check only - it is not an essential processing
56754 ** step.
56755 **
56756 ** This is a no-op if NDEBUG is defined.
56757 */
56758 #ifndef NDEBUG
56759 static void checkActiveVdbeCnt(sqlite3 *db){
56760   Vdbe *p;
56761   int cnt = 0;
56762   int nWrite = 0;
56763   p = db->pVdbe;
56764   while( p ){
56765     if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
56766       cnt++;
56767       if( p->readOnly==0 ) nWrite++;
56768     }
56769     p = p->pNext;
56770   }
56771   assert( cnt==db->activeVdbeCnt );
56772   assert( nWrite==db->writeVdbeCnt );
56773 }
56774 #else
56775 #define checkActiveVdbeCnt(x)
56776 #endif
56777
56778 /*
56779 ** For every Btree that in database connection db which 
56780 ** has been modified, "trip" or invalidate each cursor in
56781 ** that Btree might have been modified so that the cursor
56782 ** can never be used again.  This happens when a rollback
56783 *** occurs.  We have to trip all the other cursors, even
56784 ** cursor from other VMs in different database connections,
56785 ** so that none of them try to use the data at which they
56786 ** were pointing and which now may have been changed due
56787 ** to the rollback.
56788 **
56789 ** Remember that a rollback can delete tables complete and
56790 ** reorder rootpages.  So it is not sufficient just to save
56791 ** the state of the cursor.  We have to invalidate the cursor
56792 ** so that it is never used again.
56793 */
56794 static void invalidateCursorsOnModifiedBtrees(sqlite3 *db){
56795   int i;
56796   for(i=0; i<db->nDb; i++){
56797     Btree *p = db->aDb[i].pBt;
56798     if( p && sqlite3BtreeIsInTrans(p) ){
56799       sqlite3BtreeTripAllCursors(p, SQLITE_ABORT);
56800     }
56801   }
56802 }
56803
56804 /*
56805 ** If the Vdbe passed as the first argument opened a statement-transaction,
56806 ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
56807 ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
56808 ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the 
56809 ** statement transaction is commtted.
56810 **
56811 ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned. 
56812 ** Otherwise SQLITE_OK.
56813 */
56814 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
56815   sqlite3 *const db = p->db;
56816   int rc = SQLITE_OK;
56817
56818   /* If p->iStatement is greater than zero, then this Vdbe opened a 
56819   ** statement transaction that should be closed here. The only exception
56820   ** is that an IO error may have occured, causing an emergency rollback.
56821   ** In this case (db->nStatement==0), and there is nothing to do.
56822   */
56823   if( db->nStatement && p->iStatement ){
56824     int i;
56825     const int iSavepoint = p->iStatement-1;
56826
56827     assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
56828     assert( db->nStatement>0 );
56829     assert( p->iStatement==(db->nStatement+db->nSavepoint) );
56830
56831     for(i=0; i<db->nDb; i++){ 
56832       int rc2 = SQLITE_OK;
56833       Btree *pBt = db->aDb[i].pBt;
56834       if( pBt ){
56835         if( eOp==SAVEPOINT_ROLLBACK ){
56836           rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
56837         }
56838         if( rc2==SQLITE_OK ){
56839           rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
56840         }
56841         if( rc==SQLITE_OK ){
56842           rc = rc2;
56843         }
56844       }
56845     }
56846     db->nStatement--;
56847     p->iStatement = 0;
56848
56849     /* If the statement transaction is being rolled back, also restore the 
56850     ** database handles deferred constraint counter to the value it had when 
56851     ** the statement transaction was opened.  */
56852     if( eOp==SAVEPOINT_ROLLBACK ){
56853       db->nDeferredCons = p->nStmtDefCons;
56854     }
56855   }
56856   return rc;
56857 }
56858
56859 /*
56860 ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
56861 ** this routine obtains the mutex associated with each BtShared structure
56862 ** that may be accessed by the VM passed as an argument. In doing so it
56863 ** sets the BtShared.db member of each of the BtShared structures, ensuring
56864 ** that the correct busy-handler callback is invoked if required.
56865 **
56866 ** If SQLite is not threadsafe but does support shared-cache mode, then
56867 ** sqlite3BtreeEnterAll() is invoked to set the BtShared.db variables
56868 ** of all of BtShared structures accessible via the database handle 
56869 ** associated with the VM. Of course only a subset of these structures
56870 ** will be accessed by the VM, and we could use Vdbe.btreeMask to figure
56871 ** that subset out, but there is no advantage to doing so.
56872 **
56873 ** If SQLite is not threadsafe and does not support shared-cache mode, this
56874 ** function is a no-op.
56875 */
56876 #ifndef SQLITE_OMIT_SHARED_CACHE
56877 SQLITE_PRIVATE void sqlite3VdbeMutexArrayEnter(Vdbe *p){
56878 #if SQLITE_THREADSAFE
56879   sqlite3BtreeMutexArrayEnter(&p->aMutex);
56880 #else
56881   sqlite3BtreeEnterAll(p->db);
56882 #endif
56883 }
56884 #endif
56885
56886 /*
56887 ** This function is called when a transaction opened by the database 
56888 ** handle associated with the VM passed as an argument is about to be 
56889 ** committed. If there are outstanding deferred foreign key constraint
56890 ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
56891 **
56892 ** If there are outstanding FK violations and this function returns 
56893 ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT and write
56894 ** an error message to it. Then return SQLITE_ERROR.
56895 */
56896 #ifndef SQLITE_OMIT_FOREIGN_KEY
56897 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
56898   sqlite3 *db = p->db;
56899   if( (deferred && db->nDeferredCons>0) || (!deferred && p->nFkConstraint>0) ){
56900     p->rc = SQLITE_CONSTRAINT;
56901     p->errorAction = OE_Abort;
56902     sqlite3SetString(&p->zErrMsg, db, "foreign key constraint failed");
56903     return SQLITE_ERROR;
56904   }
56905   return SQLITE_OK;
56906 }
56907 #endif
56908
56909 /*
56910 ** This routine is called the when a VDBE tries to halt.  If the VDBE
56911 ** has made changes and is in autocommit mode, then commit those
56912 ** changes.  If a rollback is needed, then do the rollback.
56913 **
56914 ** This routine is the only way to move the state of a VM from
56915 ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
56916 ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
56917 **
56918 ** Return an error code.  If the commit could not complete because of
56919 ** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
56920 ** means the close did not happen and needs to be repeated.
56921 */
56922 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
56923   int rc;                         /* Used to store transient return codes */
56924   sqlite3 *db = p->db;
56925
56926   /* This function contains the logic that determines if a statement or
56927   ** transaction will be committed or rolled back as a result of the
56928   ** execution of this virtual machine. 
56929   **
56930   ** If any of the following errors occur:
56931   **
56932   **     SQLITE_NOMEM
56933   **     SQLITE_IOERR
56934   **     SQLITE_FULL
56935   **     SQLITE_INTERRUPT
56936   **
56937   ** Then the internal cache might have been left in an inconsistent
56938   ** state.  We need to rollback the statement transaction, if there is
56939   ** one, or the complete transaction if there is no statement transaction.
56940   */
56941
56942   if( p->db->mallocFailed ){
56943     p->rc = SQLITE_NOMEM;
56944   }
56945   closeAllCursors(p);
56946   if( p->magic!=VDBE_MAGIC_RUN ){
56947     return SQLITE_OK;
56948   }
56949   checkActiveVdbeCnt(db);
56950
56951   /* No commit or rollback needed if the program never started */
56952   if( p->pc>=0 ){
56953     int mrc;   /* Primary error code from p->rc */
56954     int eStatementOp = 0;
56955     int isSpecialError;            /* Set to true if a 'special' error */
56956
56957     /* Lock all btrees used by the statement */
56958     sqlite3VdbeMutexArrayEnter(p);
56959
56960     /* Check for one of the special errors */
56961     mrc = p->rc & 0xff;
56962     assert( p->rc!=SQLITE_IOERR_BLOCKED );  /* This error no longer exists */
56963     isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
56964                      || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
56965     if( isSpecialError ){
56966       /* If the query was read-only and the error code is SQLITE_INTERRUPT, 
56967       ** no rollback is necessary. Otherwise, at least a savepoint 
56968       ** transaction must be rolled back to restore the database to a 
56969       ** consistent state.
56970       **
56971       ** Even if the statement is read-only, it is important to perform
56972       ** a statement or transaction rollback operation. If the error 
56973       ** occured while writing to the journal, sub-journal or database
56974       ** file as part of an effort to free up cache space (see function
56975       ** pagerStress() in pager.c), the rollback is required to restore 
56976       ** the pager to a consistent state.
56977       */
56978       if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
56979         if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
56980           eStatementOp = SAVEPOINT_ROLLBACK;
56981         }else{
56982           /* We are forced to roll back the active transaction. Before doing
56983           ** so, abort any other statements this handle currently has active.
56984           */
56985           invalidateCursorsOnModifiedBtrees(db);
56986           sqlite3RollbackAll(db);
56987           sqlite3CloseSavepoints(db);
56988           db->autoCommit = 1;
56989         }
56990       }
56991     }
56992
56993     /* Check for immediate foreign key violations. */
56994     if( p->rc==SQLITE_OK ){
56995       sqlite3VdbeCheckFk(p, 0);
56996     }
56997   
56998     /* If the auto-commit flag is set and this is the only active writer 
56999     ** VM, then we do either a commit or rollback of the current transaction. 
57000     **
57001     ** Note: This block also runs if one of the special errors handled 
57002     ** above has occurred. 
57003     */
57004     if( !sqlite3VtabInSync(db) 
57005      && db->autoCommit 
57006      && db->writeVdbeCnt==(p->readOnly==0) 
57007     ){
57008       if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
57009         if( sqlite3VdbeCheckFk(p, 1) ){
57010           sqlite3BtreeMutexArrayLeave(&p->aMutex);
57011           return SQLITE_ERROR;
57012         }
57013         /* The auto-commit flag is true, the vdbe program was successful 
57014         ** or hit an 'OR FAIL' constraint and there are no deferred foreign
57015         ** key constraints to hold up the transaction. This means a commit 
57016         ** is required.  */
57017         rc = vdbeCommit(db, p);
57018         if( rc==SQLITE_BUSY ){
57019           sqlite3BtreeMutexArrayLeave(&p->aMutex);
57020           return SQLITE_BUSY;
57021         }else if( rc!=SQLITE_OK ){
57022           p->rc = rc;
57023           sqlite3RollbackAll(db);
57024         }else{
57025           db->nDeferredCons = 0;
57026           sqlite3CommitInternalChanges(db);
57027         }
57028       }else{
57029         sqlite3RollbackAll(db);
57030       }
57031       db->nStatement = 0;
57032     }else if( eStatementOp==0 ){
57033       if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
57034         eStatementOp = SAVEPOINT_RELEASE;
57035       }else if( p->errorAction==OE_Abort ){
57036         eStatementOp = SAVEPOINT_ROLLBACK;
57037       }else{
57038         invalidateCursorsOnModifiedBtrees(db);
57039         sqlite3RollbackAll(db);
57040         sqlite3CloseSavepoints(db);
57041         db->autoCommit = 1;
57042       }
57043     }
57044   
57045     /* If eStatementOp is non-zero, then a statement transaction needs to
57046     ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
57047     ** do so. If this operation returns an error, and the current statement
57048     ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
57049     ** current statement error code.
57050     **
57051     ** Note that sqlite3VdbeCloseStatement() can only fail if eStatementOp
57052     ** is SAVEPOINT_ROLLBACK.  But if p->rc==SQLITE_OK then eStatementOp
57053     ** must be SAVEPOINT_RELEASE.  Hence the NEVER(p->rc==SQLITE_OK) in 
57054     ** the following code.
57055     */
57056     if( eStatementOp ){
57057       rc = sqlite3VdbeCloseStatement(p, eStatementOp);
57058       if( rc ){
57059         assert( eStatementOp==SAVEPOINT_ROLLBACK );
57060         if( NEVER(p->rc==SQLITE_OK) || p->rc==SQLITE_CONSTRAINT ){
57061           p->rc = rc;
57062           sqlite3DbFree(db, p->zErrMsg);
57063           p->zErrMsg = 0;
57064         }
57065         invalidateCursorsOnModifiedBtrees(db);
57066         sqlite3RollbackAll(db);
57067         sqlite3CloseSavepoints(db);
57068         db->autoCommit = 1;
57069       }
57070     }
57071   
57072     /* If this was an INSERT, UPDATE or DELETE and no statement transaction
57073     ** has been rolled back, update the database connection change-counter. 
57074     */
57075     if( p->changeCntOn ){
57076       if( eStatementOp!=SAVEPOINT_ROLLBACK ){
57077         sqlite3VdbeSetChanges(db, p->nChange);
57078       }else{
57079         sqlite3VdbeSetChanges(db, 0);
57080       }
57081       p->nChange = 0;
57082     }
57083   
57084     /* Rollback or commit any schema changes that occurred. */
57085     if( p->rc!=SQLITE_OK && db->flags&SQLITE_InternChanges ){
57086       sqlite3ResetInternalSchema(db, 0);
57087       db->flags = (db->flags | SQLITE_InternChanges);
57088     }
57089
57090     /* Release the locks */
57091     sqlite3BtreeMutexArrayLeave(&p->aMutex);
57092   }
57093
57094   /* We have successfully halted and closed the VM.  Record this fact. */
57095   if( p->pc>=0 ){
57096     db->activeVdbeCnt--;
57097     if( !p->readOnly ){
57098       db->writeVdbeCnt--;
57099     }
57100     assert( db->activeVdbeCnt>=db->writeVdbeCnt );
57101   }
57102   p->magic = VDBE_MAGIC_HALT;
57103   checkActiveVdbeCnt(db);
57104   if( p->db->mallocFailed ){
57105     p->rc = SQLITE_NOMEM;
57106   }
57107
57108   /* If the auto-commit flag is set to true, then any locks that were held
57109   ** by connection db have now been released. Call sqlite3ConnectionUnlocked() 
57110   ** to invoke any required unlock-notify callbacks.
57111   */
57112   if( db->autoCommit ){
57113     sqlite3ConnectionUnlocked(db);
57114   }
57115
57116   assert( db->activeVdbeCnt>0 || db->autoCommit==0 || db->nStatement==0 );
57117   return SQLITE_OK;
57118 }
57119
57120
57121 /*
57122 ** Each VDBE holds the result of the most recent sqlite3_step() call
57123 ** in p->rc.  This routine sets that result back to SQLITE_OK.
57124 */
57125 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
57126   p->rc = SQLITE_OK;
57127 }
57128
57129 /*
57130 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
57131 ** Write any error messages into *pzErrMsg.  Return the result code.
57132 **
57133 ** After this routine is run, the VDBE should be ready to be executed
57134 ** again.
57135 **
57136 ** To look at it another way, this routine resets the state of the
57137 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
57138 ** VDBE_MAGIC_INIT.
57139 */
57140 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
57141   sqlite3 *db;
57142   db = p->db;
57143
57144   /* If the VM did not run to completion or if it encountered an
57145   ** error, then it might not have been halted properly.  So halt
57146   ** it now.
57147   */
57148   sqlite3VdbeHalt(p);
57149
57150   /* If the VDBE has be run even partially, then transfer the error code
57151   ** and error message from the VDBE into the main database structure.  But
57152   ** if the VDBE has just been set to run but has not actually executed any
57153   ** instructions yet, leave the main database error information unchanged.
57154   */
57155   if( p->pc>=0 ){
57156     if( p->zErrMsg ){
57157       sqlite3BeginBenignMalloc();
57158       sqlite3ValueSetStr(db->pErr,-1,p->zErrMsg,SQLITE_UTF8,SQLITE_TRANSIENT);
57159       sqlite3EndBenignMalloc();
57160       db->errCode = p->rc;
57161       sqlite3DbFree(db, p->zErrMsg);
57162       p->zErrMsg = 0;
57163     }else if( p->rc ){
57164       sqlite3Error(db, p->rc, 0);
57165     }else{
57166       sqlite3Error(db, SQLITE_OK, 0);
57167     }
57168     if( p->runOnlyOnce ) p->expired = 1;
57169   }else if( p->rc && p->expired ){
57170     /* The expired flag was set on the VDBE before the first call
57171     ** to sqlite3_step(). For consistency (since sqlite3_step() was
57172     ** called), set the database error in this case as well.
57173     */
57174     sqlite3Error(db, p->rc, 0);
57175     sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
57176     sqlite3DbFree(db, p->zErrMsg);
57177     p->zErrMsg = 0;
57178   }
57179
57180   /* Reclaim all memory used by the VDBE
57181   */
57182   Cleanup(p);
57183
57184   /* Save profiling information from this VDBE run.
57185   */
57186 #ifdef VDBE_PROFILE
57187   {
57188     FILE *out = fopen("vdbe_profile.out", "a");
57189     if( out ){
57190       int i;
57191       fprintf(out, "---- ");
57192       for(i=0; i<p->nOp; i++){
57193         fprintf(out, "%02x", p->aOp[i].opcode);
57194       }
57195       fprintf(out, "\n");
57196       for(i=0; i<p->nOp; i++){
57197         fprintf(out, "%6d %10lld %8lld ",
57198            p->aOp[i].cnt,
57199            p->aOp[i].cycles,
57200            p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
57201         );
57202         sqlite3VdbePrintOp(out, i, &p->aOp[i]);
57203       }
57204       fclose(out);
57205     }
57206   }
57207 #endif
57208   p->magic = VDBE_MAGIC_INIT;
57209   return p->rc & db->errMask;
57210 }
57211  
57212 /*
57213 ** Clean up and delete a VDBE after execution.  Return an integer which is
57214 ** the result code.  Write any error message text into *pzErrMsg.
57215 */
57216 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
57217   int rc = SQLITE_OK;
57218   if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
57219     rc = sqlite3VdbeReset(p);
57220     assert( (rc & p->db->errMask)==rc );
57221   }
57222   sqlite3VdbeDelete(p);
57223   return rc;
57224 }
57225
57226 /*
57227 ** Call the destructor for each auxdata entry in pVdbeFunc for which
57228 ** the corresponding bit in mask is clear.  Auxdata entries beyond 31
57229 ** are always destroyed.  To destroy all auxdata entries, call this
57230 ** routine with mask==0.
57231 */
57232 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
57233   int i;
57234   for(i=0; i<pVdbeFunc->nAux; i++){
57235     struct AuxData *pAux = &pVdbeFunc->apAux[i];
57236     if( (i>31 || !(mask&(((u32)1)<<i))) && pAux->pAux ){
57237       if( pAux->xDelete ){
57238         pAux->xDelete(pAux->pAux);
57239       }
57240       pAux->pAux = 0;
57241     }
57242   }
57243 }
57244
57245 /*
57246 ** Free all memory associated with the Vdbe passed as the second argument.
57247 ** The difference between this function and sqlite3VdbeDelete() is that
57248 ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
57249 ** the database connection.
57250 */
57251 SQLITE_PRIVATE void sqlite3VdbeDeleteObject(sqlite3 *db, Vdbe *p){
57252   SubProgram *pSub, *pNext;
57253   assert( p->db==0 || p->db==db );
57254   releaseMemArray(p->aVar, p->nVar);
57255   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
57256   for(pSub=p->pProgram; pSub; pSub=pNext){
57257     pNext = pSub->pNext;
57258     vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
57259     sqlite3DbFree(db, pSub);
57260   }
57261   vdbeFreeOpArray(db, p->aOp, p->nOp);
57262   sqlite3DbFree(db, p->aLabel);
57263   sqlite3DbFree(db, p->aColName);
57264   sqlite3DbFree(db, p->zSql);
57265   sqlite3DbFree(db, p->pFree);
57266   sqlite3DbFree(db, p);
57267 }
57268
57269 /*
57270 ** Delete an entire VDBE.
57271 */
57272 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
57273   sqlite3 *db;
57274
57275   if( NEVER(p==0) ) return;
57276   db = p->db;
57277   if( p->pPrev ){
57278     p->pPrev->pNext = p->pNext;
57279   }else{
57280     assert( db->pVdbe==p );
57281     db->pVdbe = p->pNext;
57282   }
57283   if( p->pNext ){
57284     p->pNext->pPrev = p->pPrev;
57285   }
57286   p->magic = VDBE_MAGIC_DEAD;
57287   p->db = 0;
57288   sqlite3VdbeDeleteObject(db, p);
57289 }
57290
57291 /*
57292 ** Make sure the cursor p is ready to read or write the row to which it
57293 ** was last positioned.  Return an error code if an OOM fault or I/O error
57294 ** prevents us from positioning the cursor to its correct position.
57295 **
57296 ** If a MoveTo operation is pending on the given cursor, then do that
57297 ** MoveTo now.  If no move is pending, check to see if the row has been
57298 ** deleted out from under the cursor and if it has, mark the row as
57299 ** a NULL row.
57300 **
57301 ** If the cursor is already pointing to the correct row and that row has
57302 ** not been deleted out from under the cursor, then this routine is a no-op.
57303 */
57304 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
57305   if( p->deferredMoveto ){
57306     int res, rc;
57307 #ifdef SQLITE_TEST
57308     extern int sqlite3_search_count;
57309 #endif
57310     assert( p->isTable );
57311     rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
57312     if( rc ) return rc;
57313     p->lastRowid = p->movetoTarget;
57314     if( res!=0 ) return SQLITE_CORRUPT_BKPT;
57315     p->rowidIsValid = 1;
57316 #ifdef SQLITE_TEST
57317     sqlite3_search_count++;
57318 #endif
57319     p->deferredMoveto = 0;
57320     p->cacheStatus = CACHE_STALE;
57321   }else if( ALWAYS(p->pCursor) ){
57322     int hasMoved;
57323     int rc = sqlite3BtreeCursorHasMoved(p->pCursor, &hasMoved);
57324     if( rc ) return rc;
57325     if( hasMoved ){
57326       p->cacheStatus = CACHE_STALE;
57327       p->nullRow = 1;
57328     }
57329   }
57330   return SQLITE_OK;
57331 }
57332
57333 /*
57334 ** The following functions:
57335 **
57336 ** sqlite3VdbeSerialType()
57337 ** sqlite3VdbeSerialTypeLen()
57338 ** sqlite3VdbeSerialLen()
57339 ** sqlite3VdbeSerialPut()
57340 ** sqlite3VdbeSerialGet()
57341 **
57342 ** encapsulate the code that serializes values for storage in SQLite
57343 ** data and index records. Each serialized value consists of a
57344 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
57345 ** integer, stored as a varint.
57346 **
57347 ** In an SQLite index record, the serial type is stored directly before
57348 ** the blob of data that it corresponds to. In a table record, all serial
57349 ** types are stored at the start of the record, and the blobs of data at
57350 ** the end. Hence these functions allow the caller to handle the
57351 ** serial-type and data blob seperately.
57352 **
57353 ** The following table describes the various storage classes for data:
57354 **
57355 **   serial type        bytes of data      type
57356 **   --------------     ---------------    ---------------
57357 **      0                     0            NULL
57358 **      1                     1            signed integer
57359 **      2                     2            signed integer
57360 **      3                     3            signed integer
57361 **      4                     4            signed integer
57362 **      5                     6            signed integer
57363 **      6                     8            signed integer
57364 **      7                     8            IEEE float
57365 **      8                     0            Integer constant 0
57366 **      9                     0            Integer constant 1
57367 **     10,11                               reserved for expansion
57368 **    N>=12 and even       (N-12)/2        BLOB
57369 **    N>=13 and odd        (N-13)/2        text
57370 **
57371 ** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
57372 ** of SQLite will not understand those serial types.
57373 */
57374
57375 /*
57376 ** Return the serial-type for the value stored in pMem.
57377 */
57378 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
57379   int flags = pMem->flags;
57380   int n;
57381
57382   if( flags&MEM_Null ){
57383     return 0;
57384   }
57385   if( flags&MEM_Int ){
57386     /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
57387 #   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
57388     i64 i = pMem->u.i;
57389     u64 u;
57390     if( file_format>=4 && (i&1)==i ){
57391       return 8+(u32)i;
57392     }
57393     u = i<0 ? -i : i;
57394     if( u<=127 ) return 1;
57395     if( u<=32767 ) return 2;
57396     if( u<=8388607 ) return 3;
57397     if( u<=2147483647 ) return 4;
57398     if( u<=MAX_6BYTE ) return 5;
57399     return 6;
57400   }
57401   if( flags&MEM_Real ){
57402     return 7;
57403   }
57404   assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
57405   n = pMem->n;
57406   if( flags & MEM_Zero ){
57407     n += pMem->u.nZero;
57408   }
57409   assert( n>=0 );
57410   return ((n*2) + 12 + ((flags&MEM_Str)!=0));
57411 }
57412
57413 /*
57414 ** Return the length of the data corresponding to the supplied serial-type.
57415 */
57416 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
57417   if( serial_type>=12 ){
57418     return (serial_type-12)/2;
57419   }else{
57420     static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
57421     return aSize[serial_type];
57422   }
57423 }
57424
57425 /*
57426 ** If we are on an architecture with mixed-endian floating 
57427 ** points (ex: ARM7) then swap the lower 4 bytes with the 
57428 ** upper 4 bytes.  Return the result.
57429 **
57430 ** For most architectures, this is a no-op.
57431 **
57432 ** (later):  It is reported to me that the mixed-endian problem
57433 ** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
57434 ** that early versions of GCC stored the two words of a 64-bit
57435 ** float in the wrong order.  And that error has been propagated
57436 ** ever since.  The blame is not necessarily with GCC, though.
57437 ** GCC might have just copying the problem from a prior compiler.
57438 ** I am also told that newer versions of GCC that follow a different
57439 ** ABI get the byte order right.
57440 **
57441 ** Developers using SQLite on an ARM7 should compile and run their
57442 ** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
57443 ** enabled, some asserts below will ensure that the byte order of
57444 ** floating point values is correct.
57445 **
57446 ** (2007-08-30)  Frank van Vugt has studied this problem closely
57447 ** and has send his findings to the SQLite developers.  Frank
57448 ** writes that some Linux kernels offer floating point hardware
57449 ** emulation that uses only 32-bit mantissas instead of a full 
57450 ** 48-bits as required by the IEEE standard.  (This is the
57451 ** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
57452 ** byte swapping becomes very complicated.  To avoid problems,
57453 ** the necessary byte swapping is carried out using a 64-bit integer
57454 ** rather than a 64-bit float.  Frank assures us that the code here
57455 ** works for him.  We, the developers, have no way to independently
57456 ** verify this, but Frank seems to know what he is talking about
57457 ** so we trust him.
57458 */
57459 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
57460 static u64 floatSwap(u64 in){
57461   union {
57462     u64 r;
57463     u32 i[2];
57464   } u;
57465   u32 t;
57466
57467   u.r = in;
57468   t = u.i[0];
57469   u.i[0] = u.i[1];
57470   u.i[1] = t;
57471   return u.r;
57472 }
57473 # define swapMixedEndianFloat(X)  X = floatSwap(X)
57474 #else
57475 # define swapMixedEndianFloat(X)
57476 #endif
57477
57478 /*
57479 ** Write the serialized data blob for the value stored in pMem into 
57480 ** buf. It is assumed that the caller has allocated sufficient space.
57481 ** Return the number of bytes written.
57482 **
57483 ** nBuf is the amount of space left in buf[].  nBuf must always be
57484 ** large enough to hold the entire field.  Except, if the field is
57485 ** a blob with a zero-filled tail, then buf[] might be just the right
57486 ** size to hold everything except for the zero-filled tail.  If buf[]
57487 ** is only big enough to hold the non-zero prefix, then only write that
57488 ** prefix into buf[].  But if buf[] is large enough to hold both the
57489 ** prefix and the tail then write the prefix and set the tail to all
57490 ** zeros.
57491 **
57492 ** Return the number of bytes actually written into buf[].  The number
57493 ** of bytes in the zero-filled tail is included in the return value only
57494 ** if those bytes were zeroed in buf[].
57495 */ 
57496 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
57497   u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
57498   u32 len;
57499
57500   /* Integer and Real */
57501   if( serial_type<=7 && serial_type>0 ){
57502     u64 v;
57503     u32 i;
57504     if( serial_type==7 ){
57505       assert( sizeof(v)==sizeof(pMem->r) );
57506       memcpy(&v, &pMem->r, sizeof(v));
57507       swapMixedEndianFloat(v);
57508     }else{
57509       v = pMem->u.i;
57510     }
57511     len = i = sqlite3VdbeSerialTypeLen(serial_type);
57512     assert( len<=(u32)nBuf );
57513     while( i-- ){
57514       buf[i] = (u8)(v&0xFF);
57515       v >>= 8;
57516     }
57517     return len;
57518   }
57519
57520   /* String or blob */
57521   if( serial_type>=12 ){
57522     assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
57523              == (int)sqlite3VdbeSerialTypeLen(serial_type) );
57524     assert( pMem->n<=nBuf );
57525     len = pMem->n;
57526     memcpy(buf, pMem->z, len);
57527     if( pMem->flags & MEM_Zero ){
57528       len += pMem->u.nZero;
57529       assert( nBuf>=0 );
57530       if( len > (u32)nBuf ){
57531         len = (u32)nBuf;
57532       }
57533       memset(&buf[pMem->n], 0, len-pMem->n);
57534     }
57535     return len;
57536   }
57537
57538   /* NULL or constants 0 or 1 */
57539   return 0;
57540 }
57541
57542 /*
57543 ** Deserialize the data blob pointed to by buf as serial type serial_type
57544 ** and store the result in pMem.  Return the number of bytes read.
57545 */ 
57546 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
57547   const unsigned char *buf,     /* Buffer to deserialize from */
57548   u32 serial_type,              /* Serial type to deserialize */
57549   Mem *pMem                     /* Memory cell to write value into */
57550 ){
57551   switch( serial_type ){
57552     case 10:   /* Reserved for future use */
57553     case 11:   /* Reserved for future use */
57554     case 0: {  /* NULL */
57555       pMem->flags = MEM_Null;
57556       break;
57557     }
57558     case 1: { /* 1-byte signed integer */
57559       pMem->u.i = (signed char)buf[0];
57560       pMem->flags = MEM_Int;
57561       return 1;
57562     }
57563     case 2: { /* 2-byte signed integer */
57564       pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
57565       pMem->flags = MEM_Int;
57566       return 2;
57567     }
57568     case 3: { /* 3-byte signed integer */
57569       pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
57570       pMem->flags = MEM_Int;
57571       return 3;
57572     }
57573     case 4: { /* 4-byte signed integer */
57574       pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
57575       pMem->flags = MEM_Int;
57576       return 4;
57577     }
57578     case 5: { /* 6-byte signed integer */
57579       u64 x = (((signed char)buf[0])<<8) | buf[1];
57580       u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
57581       x = (x<<32) | y;
57582       pMem->u.i = *(i64*)&x;
57583       pMem->flags = MEM_Int;
57584       return 6;
57585     }
57586     case 6:   /* 8-byte signed integer */
57587     case 7: { /* IEEE floating point */
57588       u64 x;
57589       u32 y;
57590 #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
57591       /* Verify that integers and floating point values use the same
57592       ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
57593       ** defined that 64-bit floating point values really are mixed
57594       ** endian.
57595       */
57596       static const u64 t1 = ((u64)0x3ff00000)<<32;
57597       static const double r1 = 1.0;
57598       u64 t2 = t1;
57599       swapMixedEndianFloat(t2);
57600       assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
57601 #endif
57602
57603       x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
57604       y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
57605       x = (x<<32) | y;
57606       if( serial_type==6 ){
57607         pMem->u.i = *(i64*)&x;
57608         pMem->flags = MEM_Int;
57609       }else{
57610         assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
57611         swapMixedEndianFloat(x);
57612         memcpy(&pMem->r, &x, sizeof(x));
57613         pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
57614       }
57615       return 8;
57616     }
57617     case 8:    /* Integer 0 */
57618     case 9: {  /* Integer 1 */
57619       pMem->u.i = serial_type-8;
57620       pMem->flags = MEM_Int;
57621       return 0;
57622     }
57623     default: {
57624       u32 len = (serial_type-12)/2;
57625       pMem->z = (char *)buf;
57626       pMem->n = len;
57627       pMem->xDel = 0;
57628       if( serial_type&0x01 ){
57629         pMem->flags = MEM_Str | MEM_Ephem;
57630       }else{
57631         pMem->flags = MEM_Blob | MEM_Ephem;
57632       }
57633       return len;
57634     }
57635   }
57636   return 0;
57637 }
57638
57639
57640 /*
57641 ** Given the nKey-byte encoding of a record in pKey[], parse the
57642 ** record into a UnpackedRecord structure.  Return a pointer to
57643 ** that structure.
57644 **
57645 ** The calling function might provide szSpace bytes of memory
57646 ** space at pSpace.  This space can be used to hold the returned
57647 ** VDbeParsedRecord structure if it is large enough.  If it is
57648 ** not big enough, space is obtained from sqlite3_malloc().
57649 **
57650 ** The returned structure should be closed by a call to
57651 ** sqlite3VdbeDeleteUnpackedRecord().
57652 */ 
57653 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(
57654   KeyInfo *pKeyInfo,     /* Information about the record format */
57655   int nKey,              /* Size of the binary record */
57656   const void *pKey,      /* The binary record */
57657   char *pSpace,          /* Unaligned space available to hold the object */
57658   int szSpace            /* Size of pSpace[] in bytes */
57659 ){
57660   const unsigned char *aKey = (const unsigned char *)pKey;
57661   UnpackedRecord *p;  /* The unpacked record that we will return */
57662   int nByte;          /* Memory space needed to hold p, in bytes */
57663   int d;
57664   u32 idx;
57665   u16 u;              /* Unsigned loop counter */
57666   u32 szHdr;
57667   Mem *pMem;
57668   int nOff;           /* Increase pSpace by this much to 8-byte align it */
57669   
57670   /*
57671   ** We want to shift the pointer pSpace up such that it is 8-byte aligned.
57672   ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift 
57673   ** it by.  If pSpace is already 8-byte aligned, nOff should be zero.
57674   */
57675   nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
57676   pSpace += nOff;
57677   szSpace -= nOff;
57678   nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
57679   if( nByte>szSpace ){
57680     p = sqlite3DbMallocRaw(pKeyInfo->db, nByte);
57681     if( p==0 ) return 0;
57682     p->flags = UNPACKED_NEED_FREE | UNPACKED_NEED_DESTROY;
57683   }else{
57684     p = (UnpackedRecord*)pSpace;
57685     p->flags = UNPACKED_NEED_DESTROY;
57686   }
57687   p->pKeyInfo = pKeyInfo;
57688   p->nField = pKeyInfo->nField + 1;
57689   p->aMem = pMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
57690   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
57691   idx = getVarint32(aKey, szHdr);
57692   d = szHdr;
57693   u = 0;
57694   while( idx<szHdr && u<p->nField && d<=nKey ){
57695     u32 serial_type;
57696
57697     idx += getVarint32(&aKey[idx], serial_type);
57698     pMem->enc = pKeyInfo->enc;
57699     pMem->db = pKeyInfo->db;
57700     pMem->flags = 0;
57701     pMem->zMalloc = 0;
57702     d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
57703     pMem++;
57704     u++;
57705   }
57706   assert( u<=pKeyInfo->nField + 1 );
57707   p->nField = u;
57708   return (void*)p;
57709 }
57710
57711 /*
57712 ** This routine destroys a UnpackedRecord object.
57713 */
57714 SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord *p){
57715   int i;
57716   Mem *pMem;
57717
57718   assert( p!=0 );
57719   assert( p->flags & UNPACKED_NEED_DESTROY );
57720   for(i=0, pMem=p->aMem; i<p->nField; i++, pMem++){
57721     /* The unpacked record is always constructed by the
57722     ** sqlite3VdbeUnpackRecord() function above, which makes all
57723     ** strings and blobs static.  And none of the elements are
57724     ** ever transformed, so there is never anything to delete.
57725     */
57726     if( NEVER(pMem->zMalloc) ) sqlite3VdbeMemRelease(pMem);
57727   }
57728   if( p->flags & UNPACKED_NEED_FREE ){
57729     sqlite3DbFree(p->pKeyInfo->db, p);
57730   }
57731 }
57732
57733 /*
57734 ** This function compares the two table rows or index records
57735 ** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
57736 ** or positive integer if key1 is less than, equal to or 
57737 ** greater than key2.  The {nKey1, pKey1} key must be a blob
57738 ** created by th OP_MakeRecord opcode of the VDBE.  The pPKey2
57739 ** key must be a parsed key such as obtained from
57740 ** sqlite3VdbeParseRecord.
57741 **
57742 ** Key1 and Key2 do not have to contain the same number of fields.
57743 ** The key with fewer fields is usually compares less than the 
57744 ** longer key.  However if the UNPACKED_INCRKEY flags in pPKey2 is set
57745 ** and the common prefixes are equal, then key1 is less than key2.
57746 ** Or if the UNPACKED_MATCH_PREFIX flag is set and the prefixes are
57747 ** equal, then the keys are considered to be equal and
57748 ** the parts beyond the common prefix are ignored.
57749 **
57750 ** If the UNPACKED_IGNORE_ROWID flag is set, then the last byte of
57751 ** the header of pKey1 is ignored.  It is assumed that pKey1 is
57752 ** an index key, and thus ends with a rowid value.  The last byte
57753 ** of the header will therefore be the serial type of the rowid:
57754 ** one of 1, 2, 3, 4, 5, 6, 8, or 9 - the integer serial types.
57755 ** The serial type of the final rowid will always be a single byte.
57756 ** By ignoring this last byte of the header, we force the comparison
57757 ** to ignore the rowid at the end of key1.
57758 */
57759 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
57760   int nKey1, const void *pKey1, /* Left key */
57761   UnpackedRecord *pPKey2        /* Right key */
57762 ){
57763   int d1;            /* Offset into aKey[] of next data element */
57764   u32 idx1;          /* Offset into aKey[] of next header element */
57765   u32 szHdr1;        /* Number of bytes in header */
57766   int i = 0;
57767   int nField;
57768   int rc = 0;
57769   const unsigned char *aKey1 = (const unsigned char *)pKey1;
57770   KeyInfo *pKeyInfo;
57771   Mem mem1;
57772
57773   pKeyInfo = pPKey2->pKeyInfo;
57774   mem1.enc = pKeyInfo->enc;
57775   mem1.db = pKeyInfo->db;
57776   /* mem1.flags = 0;  // Will be initialized by sqlite3VdbeSerialGet() */
57777   VVA_ONLY( mem1.zMalloc = 0; ) /* Only needed by assert() statements */
57778
57779   /* Compilers may complain that mem1.u.i is potentially uninitialized.
57780   ** We could initialize it, as shown here, to silence those complaints.
57781   ** But in fact, mem1.u.i will never actually be used initialized, and doing 
57782   ** the unnecessary initialization has a measurable negative performance
57783   ** impact, since this routine is a very high runner.  And so, we choose
57784   ** to ignore the compiler warnings and leave this variable uninitialized.
57785   */
57786   /*  mem1.u.i = 0;  // not needed, here to silence compiler warning */
57787   
57788   idx1 = getVarint32(aKey1, szHdr1);
57789   d1 = szHdr1;
57790   if( pPKey2->flags & UNPACKED_IGNORE_ROWID ){
57791     szHdr1--;
57792   }
57793   nField = pKeyInfo->nField;
57794   while( idx1<szHdr1 && i<pPKey2->nField ){
57795     u32 serial_type1;
57796
57797     /* Read the serial types for the next element in each key. */
57798     idx1 += getVarint32( aKey1+idx1, serial_type1 );
57799     if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;
57800
57801     /* Extract the values to be compared.
57802     */
57803     d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
57804
57805     /* Do the comparison
57806     */
57807     rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
57808                            i<nField ? pKeyInfo->aColl[i] : 0);
57809     if( rc!=0 ){
57810       assert( mem1.zMalloc==0 );  /* See comment below */
57811
57812       /* Invert the result if we are using DESC sort order. */
57813       if( pKeyInfo->aSortOrder && i<nField && pKeyInfo->aSortOrder[i] ){
57814         rc = -rc;
57815       }
57816     
57817       /* If the PREFIX_SEARCH flag is set and all fields except the final
57818       ** rowid field were equal, then clear the PREFIX_SEARCH flag and set 
57819       ** pPKey2->rowid to the value of the rowid field in (pKey1, nKey1).
57820       ** This is used by the OP_IsUnique opcode.
57821       */
57822       if( (pPKey2->flags & UNPACKED_PREFIX_SEARCH) && i==(pPKey2->nField-1) ){
57823         assert( idx1==szHdr1 && rc );
57824         assert( mem1.flags & MEM_Int );
57825         pPKey2->flags &= ~UNPACKED_PREFIX_SEARCH;
57826         pPKey2->rowid = mem1.u.i;
57827       }
57828     
57829       return rc;
57830     }
57831     i++;
57832   }
57833
57834   /* No memory allocation is ever used on mem1.  Prove this using
57835   ** the following assert().  If the assert() fails, it indicates a
57836   ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
57837   */
57838   assert( mem1.zMalloc==0 );
57839
57840   /* rc==0 here means that one of the keys ran out of fields and
57841   ** all the fields up to that point were equal. If the UNPACKED_INCRKEY
57842   ** flag is set, then break the tie by treating key2 as larger.
57843   ** If the UPACKED_PREFIX_MATCH flag is set, then keys with common prefixes
57844   ** are considered to be equal.  Otherwise, the longer key is the 
57845   ** larger.  As it happens, the pPKey2 will always be the longer
57846   ** if there is a difference.
57847   */
57848   assert( rc==0 );
57849   if( pPKey2->flags & UNPACKED_INCRKEY ){
57850     rc = -1;
57851   }else if( pPKey2->flags & UNPACKED_PREFIX_MATCH ){
57852     /* Leave rc==0 */
57853   }else if( idx1<szHdr1 ){
57854     rc = 1;
57855   }
57856   return rc;
57857 }
57858  
57859
57860 /*
57861 ** pCur points at an index entry created using the OP_MakeRecord opcode.
57862 ** Read the rowid (the last field in the record) and store it in *rowid.
57863 ** Return SQLITE_OK if everything works, or an error code otherwise.
57864 **
57865 ** pCur might be pointing to text obtained from a corrupt database file.
57866 ** So the content cannot be trusted.  Do appropriate checks on the content.
57867 */
57868 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
57869   i64 nCellKey = 0;
57870   int rc;
57871   u32 szHdr;        /* Size of the header */
57872   u32 typeRowid;    /* Serial type of the rowid */
57873   u32 lenRowid;     /* Size of the rowid */
57874   Mem m, v;
57875
57876   UNUSED_PARAMETER(db);
57877
57878   /* Get the size of the index entry.  Only indices entries of less
57879   ** than 2GiB are support - anything large must be database corruption.
57880   ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
57881   ** this code can safely assume that nCellKey is 32-bits  
57882   */
57883   assert( sqlite3BtreeCursorIsValid(pCur) );
57884   rc = sqlite3BtreeKeySize(pCur, &nCellKey);
57885   assert( rc==SQLITE_OK );     /* pCur is always valid so KeySize cannot fail */
57886   assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
57887
57888   /* Read in the complete content of the index entry */
57889   memset(&m, 0, sizeof(m));
57890   rc = sqlite3VdbeMemFromBtree(pCur, 0, (int)nCellKey, 1, &m);
57891   if( rc ){
57892     return rc;
57893   }
57894
57895   /* The index entry must begin with a header size */
57896   (void)getVarint32((u8*)m.z, szHdr);
57897   testcase( szHdr==3 );
57898   testcase( szHdr==m.n );
57899   if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
57900     goto idx_rowid_corruption;
57901   }
57902
57903   /* The last field of the index should be an integer - the ROWID.
57904   ** Verify that the last entry really is an integer. */
57905   (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
57906   testcase( typeRowid==1 );
57907   testcase( typeRowid==2 );
57908   testcase( typeRowid==3 );
57909   testcase( typeRowid==4 );
57910   testcase( typeRowid==5 );
57911   testcase( typeRowid==6 );
57912   testcase( typeRowid==8 );
57913   testcase( typeRowid==9 );
57914   if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
57915     goto idx_rowid_corruption;
57916   }
57917   lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
57918   testcase( (u32)m.n==szHdr+lenRowid );
57919   if( unlikely((u32)m.n<szHdr+lenRowid) ){
57920     goto idx_rowid_corruption;
57921   }
57922
57923   /* Fetch the integer off the end of the index record */
57924   sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
57925   *rowid = v.u.i;
57926   sqlite3VdbeMemRelease(&m);
57927   return SQLITE_OK;
57928
57929   /* Jump here if database corruption is detected after m has been
57930   ** allocated.  Free the m object and return SQLITE_CORRUPT. */
57931 idx_rowid_corruption:
57932   testcase( m.zMalloc!=0 );
57933   sqlite3VdbeMemRelease(&m);
57934   return SQLITE_CORRUPT_BKPT;
57935 }
57936
57937 /*
57938 ** Compare the key of the index entry that cursor pC is pointing to against
57939 ** the key string in pUnpacked.  Write into *pRes a number
57940 ** that is negative, zero, or positive if pC is less than, equal to,
57941 ** or greater than pUnpacked.  Return SQLITE_OK on success.
57942 **
57943 ** pUnpacked is either created without a rowid or is truncated so that it
57944 ** omits the rowid at the end.  The rowid at the end of the index entry
57945 ** is ignored as well.  Hence, this routine only compares the prefixes 
57946 ** of the keys prior to the final rowid, not the entire key.
57947 */
57948 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
57949   VdbeCursor *pC,             /* The cursor to compare against */
57950   UnpackedRecord *pUnpacked,  /* Unpacked version of key to compare against */
57951   int *res                    /* Write the comparison result here */
57952 ){
57953   i64 nCellKey = 0;
57954   int rc;
57955   BtCursor *pCur = pC->pCursor;
57956   Mem m;
57957
57958   assert( sqlite3BtreeCursorIsValid(pCur) );
57959   rc = sqlite3BtreeKeySize(pCur, &nCellKey);
57960   assert( rc==SQLITE_OK );    /* pCur is always valid so KeySize cannot fail */
57961   /* nCellKey will always be between 0 and 0xffffffff because of the say
57962   ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
57963   if( nCellKey<=0 || nCellKey>0x7fffffff ){
57964     *res = 0;
57965     return SQLITE_CORRUPT_BKPT;
57966   }
57967   memset(&m, 0, sizeof(m));
57968   rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (int)nCellKey, 1, &m);
57969   if( rc ){
57970     return rc;
57971   }
57972   assert( pUnpacked->flags & UNPACKED_IGNORE_ROWID );
57973   *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
57974   sqlite3VdbeMemRelease(&m);
57975   return SQLITE_OK;
57976 }
57977
57978 /*
57979 ** This routine sets the value to be returned by subsequent calls to
57980 ** sqlite3_changes() on the database handle 'db'. 
57981 */
57982 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
57983   assert( sqlite3_mutex_held(db->mutex) );
57984   db->nChange = nChange;
57985   db->nTotalChange += nChange;
57986 }
57987
57988 /*
57989 ** Set a flag in the vdbe to update the change counter when it is finalised
57990 ** or reset.
57991 */
57992 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
57993   v->changeCntOn = 1;
57994 }
57995
57996 /*
57997 ** Mark every prepared statement associated with a database connection
57998 ** as expired.
57999 **
58000 ** An expired statement means that recompilation of the statement is
58001 ** recommend.  Statements expire when things happen that make their
58002 ** programs obsolete.  Removing user-defined functions or collating
58003 ** sequences, or changing an authorization function are the types of
58004 ** things that make prepared statements obsolete.
58005 */
58006 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
58007   Vdbe *p;
58008   for(p = db->pVdbe; p; p=p->pNext){
58009     p->expired = 1;
58010   }
58011 }
58012
58013 /*
58014 ** Return the database associated with the Vdbe.
58015 */
58016 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
58017   return v->db;
58018 }
58019
58020 /*
58021 ** Return a pointer to an sqlite3_value structure containing the value bound
58022 ** parameter iVar of VM v. Except, if the value is an SQL NULL, return 
58023 ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
58024 ** constants) to the value before returning it.
58025 **
58026 ** The returned value must be freed by the caller using sqlite3ValueFree().
58027 */
58028 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe *v, int iVar, u8 aff){
58029   assert( iVar>0 );
58030   if( v ){
58031     Mem *pMem = &v->aVar[iVar-1];
58032     if( 0==(pMem->flags & MEM_Null) ){
58033       sqlite3_value *pRet = sqlite3ValueNew(v->db);
58034       if( pRet ){
58035         sqlite3VdbeMemCopy((Mem *)pRet, pMem);
58036         sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
58037         sqlite3VdbeMemStoreType((Mem *)pRet);
58038       }
58039       return pRet;
58040     }
58041   }
58042   return 0;
58043 }
58044
58045 /*
58046 ** Configure SQL variable iVar so that binding a new value to it signals
58047 ** to sqlite3_reoptimize() that re-preparing the statement may result
58048 ** in a better query plan.
58049 */
58050 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
58051   assert( iVar>0 );
58052   if( iVar>32 ){
58053     v->expmask = 0xffffffff;
58054   }else{
58055     v->expmask |= ((u32)1 << (iVar-1));
58056   }
58057 }
58058
58059 /************** End of vdbeaux.c *********************************************/
58060 /************** Begin file vdbeapi.c *****************************************/
58061 /*
58062 ** 2004 May 26
58063 **
58064 ** The author disclaims copyright to this source code.  In place of
58065 ** a legal notice, here is a blessing:
58066 **
58067 **    May you do good and not evil.
58068 **    May you find forgiveness for yourself and forgive others.
58069 **    May you share freely, never taking more than you give.
58070 **
58071 *************************************************************************
58072 **
58073 ** This file contains code use to implement APIs that are part of the
58074 ** VDBE.
58075 */
58076
58077 #ifndef SQLITE_OMIT_DEPRECATED
58078 /*
58079 ** Return TRUE (non-zero) of the statement supplied as an argument needs
58080 ** to be recompiled.  A statement needs to be recompiled whenever the
58081 ** execution environment changes in a way that would alter the program
58082 ** that sqlite3_prepare() generates.  For example, if new functions or
58083 ** collating sequences are registered or if an authorizer function is
58084 ** added or changed.
58085 */
58086 SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
58087   Vdbe *p = (Vdbe*)pStmt;
58088   return p==0 || p->expired;
58089 }
58090 #endif
58091
58092 /*
58093 ** Check on a Vdbe to make sure it has not been finalized.  Log
58094 ** an error and return true if it has been finalized (or is otherwise
58095 ** invalid).  Return false if it is ok.
58096 */
58097 static int vdbeSafety(Vdbe *p){
58098   if( p->db==0 ){
58099     sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
58100     return 1;
58101   }else{
58102     return 0;
58103   }
58104 }
58105 static int vdbeSafetyNotNull(Vdbe *p){
58106   if( p==0 ){
58107     sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
58108     return 1;
58109   }else{
58110     return vdbeSafety(p);
58111   }
58112 }
58113
58114 /*
58115 ** The following routine destroys a virtual machine that is created by
58116 ** the sqlite3_compile() routine. The integer returned is an SQLITE_
58117 ** success/failure code that describes the result of executing the virtual
58118 ** machine.
58119 **
58120 ** This routine sets the error code and string returned by
58121 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
58122 */
58123 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
58124   int rc;
58125   if( pStmt==0 ){
58126     /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
58127     ** pointer is a harmless no-op. */
58128     rc = SQLITE_OK;
58129   }else{
58130     Vdbe *v = (Vdbe*)pStmt;
58131     sqlite3 *db = v->db;
58132 #if SQLITE_THREADSAFE
58133     sqlite3_mutex *mutex;
58134 #endif
58135     if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
58136 #if SQLITE_THREADSAFE
58137     mutex = v->db->mutex;
58138 #endif
58139     sqlite3_mutex_enter(mutex);
58140     rc = sqlite3VdbeFinalize(v);
58141     rc = sqlite3ApiExit(db, rc);
58142     sqlite3_mutex_leave(mutex);
58143   }
58144   return rc;
58145 }
58146
58147 /*
58148 ** Terminate the current execution of an SQL statement and reset it
58149 ** back to its starting state so that it can be reused. A success code from
58150 ** the prior execution is returned.
58151 **
58152 ** This routine sets the error code and string returned by
58153 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
58154 */
58155 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
58156   int rc;
58157   if( pStmt==0 ){
58158     rc = SQLITE_OK;
58159   }else{
58160     Vdbe *v = (Vdbe*)pStmt;
58161     sqlite3_mutex_enter(v->db->mutex);
58162     rc = sqlite3VdbeReset(v);
58163     sqlite3VdbeMakeReady(v, -1, 0, 0, 0, 0, 0);
58164     assert( (rc & (v->db->errMask))==rc );
58165     rc = sqlite3ApiExit(v->db, rc);
58166     sqlite3_mutex_leave(v->db->mutex);
58167   }
58168   return rc;
58169 }
58170
58171 /*
58172 ** Set all the parameters in the compiled SQL statement to NULL.
58173 */
58174 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
58175   int i;
58176   int rc = SQLITE_OK;
58177   Vdbe *p = (Vdbe*)pStmt;
58178 #if SQLITE_THREADSAFE
58179   sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
58180 #endif
58181   sqlite3_mutex_enter(mutex);
58182   for(i=0; i<p->nVar; i++){
58183     sqlite3VdbeMemRelease(&p->aVar[i]);
58184     p->aVar[i].flags = MEM_Null;
58185   }
58186   if( p->isPrepareV2 && p->expmask ){
58187     p->expired = 1;
58188   }
58189   sqlite3_mutex_leave(mutex);
58190   return rc;
58191 }
58192
58193
58194 /**************************** sqlite3_value_  *******************************
58195 ** The following routines extract information from a Mem or sqlite3_value
58196 ** structure.
58197 */
58198 SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
58199   Mem *p = (Mem*)pVal;
58200   if( p->flags & (MEM_Blob|MEM_Str) ){
58201     sqlite3VdbeMemExpandBlob(p);
58202     p->flags &= ~MEM_Str;
58203     p->flags |= MEM_Blob;
58204     return p->n ? p->z : 0;
58205   }else{
58206     return sqlite3_value_text(pVal);
58207   }
58208 }
58209 SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
58210   return sqlite3ValueBytes(pVal, SQLITE_UTF8);
58211 }
58212 SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
58213   return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
58214 }
58215 SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
58216   return sqlite3VdbeRealValue((Mem*)pVal);
58217 }
58218 SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
58219   return (int)sqlite3VdbeIntValue((Mem*)pVal);
58220 }
58221 SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
58222   return sqlite3VdbeIntValue((Mem*)pVal);
58223 }
58224 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
58225   return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
58226 }
58227 #ifndef SQLITE_OMIT_UTF16
58228 SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
58229   return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
58230 }
58231 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
58232   return sqlite3ValueText(pVal, SQLITE_UTF16BE);
58233 }
58234 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
58235   return sqlite3ValueText(pVal, SQLITE_UTF16LE);
58236 }
58237 #endif /* SQLITE_OMIT_UTF16 */
58238 SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
58239   return pVal->type;
58240 }
58241
58242 /**************************** sqlite3_result_  *******************************
58243 ** The following routines are used by user-defined functions to specify
58244 ** the function result.
58245 **
58246 ** The setStrOrError() funtion calls sqlite3VdbeMemSetStr() to store the
58247 ** result as a string or blob but if the string or blob is too large, it
58248 ** then sets the error code to SQLITE_TOOBIG
58249 */
58250 static void setResultStrOrError(
58251   sqlite3_context *pCtx,  /* Function context */
58252   const char *z,          /* String pointer */
58253   int n,                  /* Bytes in string, or negative */
58254   u8 enc,                 /* Encoding of z.  0 for BLOBs */
58255   void (*xDel)(void*)     /* Destructor function */
58256 ){
58257   if( sqlite3VdbeMemSetStr(&pCtx->s, z, n, enc, xDel)==SQLITE_TOOBIG ){
58258     sqlite3_result_error_toobig(pCtx);
58259   }
58260 }
58261 SQLITE_API void sqlite3_result_blob(
58262   sqlite3_context *pCtx, 
58263   const void *z, 
58264   int n, 
58265   void (*xDel)(void *)
58266 ){
58267   assert( n>=0 );
58268   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
58269   setResultStrOrError(pCtx, z, n, 0, xDel);
58270 }
58271 SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
58272   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
58273   sqlite3VdbeMemSetDouble(&pCtx->s, rVal);
58274 }
58275 SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
58276   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
58277   pCtx->isError = SQLITE_ERROR;
58278   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
58279 }
58280 #ifndef SQLITE_OMIT_UTF16
58281 SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
58282   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
58283   pCtx->isError = SQLITE_ERROR;
58284   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
58285 }
58286 #endif
58287 SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
58288   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
58289   sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
58290 }
58291 SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
58292   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
58293   sqlite3VdbeMemSetInt64(&pCtx->s, iVal);
58294 }
58295 SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
58296   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
58297   sqlite3VdbeMemSetNull(&pCtx->s);
58298 }
58299 SQLITE_API void sqlite3_result_text(
58300   sqlite3_context *pCtx, 
58301   const char *z, 
58302   int n,
58303   void (*xDel)(void *)
58304 ){
58305   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
58306   setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
58307 }
58308 #ifndef SQLITE_OMIT_UTF16
58309 SQLITE_API void sqlite3_result_text16(
58310   sqlite3_context *pCtx, 
58311   const void *z, 
58312   int n, 
58313   void (*xDel)(void *)
58314 ){
58315   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
58316   setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
58317 }
58318 SQLITE_API void sqlite3_result_text16be(
58319   sqlite3_context *pCtx, 
58320   const void *z, 
58321   int n, 
58322   void (*xDel)(void *)
58323 ){
58324   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
58325   setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
58326 }
58327 SQLITE_API void sqlite3_result_text16le(
58328   sqlite3_context *pCtx, 
58329   const void *z, 
58330   int n, 
58331   void (*xDel)(void *)
58332 ){
58333   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
58334   setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
58335 }
58336 #endif /* SQLITE_OMIT_UTF16 */
58337 SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
58338   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
58339   sqlite3VdbeMemCopy(&pCtx->s, pValue);
58340 }
58341 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
58342   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
58343   sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
58344 }
58345 SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
58346   pCtx->isError = errCode;
58347   if( pCtx->s.flags & MEM_Null ){
58348     sqlite3VdbeMemSetStr(&pCtx->s, sqlite3ErrStr(errCode), -1, 
58349                          SQLITE_UTF8, SQLITE_STATIC);
58350   }
58351 }
58352
58353 /* Force an SQLITE_TOOBIG error. */
58354 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
58355   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
58356   pCtx->isError = SQLITE_TOOBIG;
58357   sqlite3VdbeMemSetStr(&pCtx->s, "string or blob too big", -1, 
58358                        SQLITE_UTF8, SQLITE_STATIC);
58359 }
58360
58361 /* An SQLITE_NOMEM error. */
58362 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
58363   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
58364   sqlite3VdbeMemSetNull(&pCtx->s);
58365   pCtx->isError = SQLITE_NOMEM;
58366   pCtx->s.db->mallocFailed = 1;
58367 }
58368
58369 /*
58370 ** This function is called after a transaction has been committed. It 
58371 ** invokes callbacks registered with sqlite3_wal_hook() as required.
58372 */
58373 static int doWalCallbacks(sqlite3 *db){
58374   int rc = SQLITE_OK;
58375 #ifndef SQLITE_OMIT_WAL
58376   int i;
58377   for(i=0; i<db->nDb; i++){
58378     Btree *pBt = db->aDb[i].pBt;
58379     if( pBt ){
58380       int nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
58381       if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
58382         rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);
58383       }
58384     }
58385   }
58386 #endif
58387   return rc;
58388 }
58389
58390 /*
58391 ** Execute the statement pStmt, either until a row of data is ready, the
58392 ** statement is completely executed or an error occurs.
58393 **
58394 ** This routine implements the bulk of the logic behind the sqlite_step()
58395 ** API.  The only thing omitted is the automatic recompile if a 
58396 ** schema change has occurred.  That detail is handled by the
58397 ** outer sqlite3_step() wrapper procedure.
58398 */
58399 static int sqlite3Step(Vdbe *p){
58400   sqlite3 *db;
58401   int rc;
58402
58403   assert(p);
58404   if( p->magic!=VDBE_MAGIC_RUN ){
58405     /* We used to require that sqlite3_reset() be called before retrying
58406     ** sqlite3_step() after any error.  But after 3.6.23, we changed this
58407     ** so that sqlite3_reset() would be called automatically instead of
58408     ** throwing the error.
58409     */
58410     sqlite3_reset((sqlite3_stmt*)p);
58411   }
58412
58413   /* Check that malloc() has not failed. If it has, return early. */
58414   db = p->db;
58415   if( db->mallocFailed ){
58416     p->rc = SQLITE_NOMEM;
58417     return SQLITE_NOMEM;
58418   }
58419
58420   if( p->pc<=0 && p->expired ){
58421     p->rc = SQLITE_SCHEMA;
58422     rc = SQLITE_ERROR;
58423     goto end_of_step;
58424   }
58425   if( p->pc<0 ){
58426     /* If there are no other statements currently running, then
58427     ** reset the interrupt flag.  This prevents a call to sqlite3_interrupt
58428     ** from interrupting a statement that has not yet started.
58429     */
58430     if( db->activeVdbeCnt==0 ){
58431       db->u1.isInterrupted = 0;
58432     }
58433
58434     assert( db->writeVdbeCnt>0 || db->autoCommit==0 || db->nDeferredCons==0 );
58435
58436 #ifndef SQLITE_OMIT_TRACE
58437     if( db->xProfile && !db->init.busy ){
58438       sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
58439     }
58440 #endif
58441
58442     db->activeVdbeCnt++;
58443     if( p->readOnly==0 ) db->writeVdbeCnt++;
58444     p->pc = 0;
58445   }
58446 #ifndef SQLITE_OMIT_EXPLAIN
58447   if( p->explain ){
58448     rc = sqlite3VdbeList(p);
58449   }else
58450 #endif /* SQLITE_OMIT_EXPLAIN */
58451   {
58452     rc = sqlite3VdbeExec(p);
58453   }
58454
58455 #ifndef SQLITE_OMIT_TRACE
58456   /* Invoke the profile callback if there is one
58457   */
58458   if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){
58459     sqlite3_int64 iNow;
58460     sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
58461     db->xProfile(db->pProfileArg, p->zSql, (iNow - p->startTime)*1000000);
58462   }
58463 #endif
58464
58465   if( rc==SQLITE_DONE ){
58466     assert( p->rc==SQLITE_OK );
58467     p->rc = doWalCallbacks(db);
58468     if( p->rc!=SQLITE_OK ){
58469       rc = SQLITE_ERROR;
58470     }
58471   }
58472
58473   db->errCode = rc;
58474   if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
58475     p->rc = SQLITE_NOMEM;
58476   }
58477 end_of_step:
58478   /* At this point local variable rc holds the value that should be 
58479   ** returned if this statement was compiled using the legacy 
58480   ** sqlite3_prepare() interface. According to the docs, this can only
58481   ** be one of the values in the first assert() below. Variable p->rc 
58482   ** contains the value that would be returned if sqlite3_finalize() 
58483   ** were called on statement p.
58484   */
58485   assert( rc==SQLITE_ROW  || rc==SQLITE_DONE   || rc==SQLITE_ERROR 
58486        || rc==SQLITE_BUSY || rc==SQLITE_MISUSE
58487   );
58488   assert( p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE );
58489   if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
58490     /* If this statement was prepared using sqlite3_prepare_v2(), and an
58491     ** error has occured, then return the error code in p->rc to the
58492     ** caller. Set the error code in the database handle to the same value.
58493     */ 
58494     rc = db->errCode = p->rc;
58495   }
58496   return (rc&db->errMask);
58497 }
58498
58499 /*
58500 ** This is the top-level implementation of sqlite3_step().  Call
58501 ** sqlite3Step() to do most of the work.  If a schema error occurs,
58502 ** call sqlite3Reprepare() and try again.
58503 */
58504 SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
58505   int rc = SQLITE_OK;      /* Result from sqlite3Step() */
58506   int rc2 = SQLITE_OK;     /* Result from sqlite3Reprepare() */
58507   Vdbe *v = (Vdbe*)pStmt;  /* the prepared statement */
58508   int cnt = 0;             /* Counter to prevent infinite loop of reprepares */
58509   sqlite3 *db;             /* The database connection */
58510
58511   if( vdbeSafetyNotNull(v) ){
58512     return SQLITE_MISUSE_BKPT;
58513   }
58514   db = v->db;
58515   sqlite3_mutex_enter(db->mutex);
58516   while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
58517          && cnt++ < 5
58518          && (rc2 = rc = sqlite3Reprepare(v))==SQLITE_OK ){
58519     sqlite3_reset(pStmt);
58520     v->expired = 0;
58521   }
58522   if( rc2!=SQLITE_OK && ALWAYS(v->isPrepareV2) && ALWAYS(db->pErr) ){
58523     /* This case occurs after failing to recompile an sql statement. 
58524     ** The error message from the SQL compiler has already been loaded 
58525     ** into the database handle. This block copies the error message 
58526     ** from the database handle into the statement and sets the statement
58527     ** program counter to 0 to ensure that when the statement is 
58528     ** finalized or reset the parser error message is available via
58529     ** sqlite3_errmsg() and sqlite3_errcode().
58530     */
58531     const char *zErr = (const char *)sqlite3_value_text(db->pErr); 
58532     sqlite3DbFree(db, v->zErrMsg);
58533     if( !db->mallocFailed ){
58534       v->zErrMsg = sqlite3DbStrDup(db, zErr);
58535       v->rc = rc2;
58536     } else {
58537       v->zErrMsg = 0;
58538       v->rc = rc = SQLITE_NOMEM;
58539     }
58540   }
58541   rc = sqlite3ApiExit(db, rc);
58542   sqlite3_mutex_leave(db->mutex);
58543   return rc;
58544 }
58545
58546 /*
58547 ** Extract the user data from a sqlite3_context structure and return a
58548 ** pointer to it.
58549 */
58550 SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
58551   assert( p && p->pFunc );
58552   return p->pFunc->pUserData;
58553 }
58554
58555 /*
58556 ** Extract the user data from a sqlite3_context structure and return a
58557 ** pointer to it.
58558 **
58559 ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
58560 ** returns a copy of the pointer to the database connection (the 1st
58561 ** parameter) of the sqlite3_create_function() and
58562 ** sqlite3_create_function16() routines that originally registered the
58563 ** application defined function.
58564 */
58565 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
58566   assert( p && p->pFunc );
58567   return p->s.db;
58568 }
58569
58570 /*
58571 ** The following is the implementation of an SQL function that always
58572 ** fails with an error message stating that the function is used in the
58573 ** wrong context.  The sqlite3_overload_function() API might construct
58574 ** SQL function that use this routine so that the functions will exist
58575 ** for name resolution but are actually overloaded by the xFindFunction
58576 ** method of virtual tables.
58577 */
58578 SQLITE_PRIVATE void sqlite3InvalidFunction(
58579   sqlite3_context *context,  /* The function calling context */
58580   int NotUsed,               /* Number of arguments to the function */
58581   sqlite3_value **NotUsed2   /* Value of each argument */
58582 ){
58583   const char *zName = context->pFunc->zName;
58584   char *zErr;
58585   UNUSED_PARAMETER2(NotUsed, NotUsed2);
58586   zErr = sqlite3_mprintf(
58587       "unable to use function %s in the requested context", zName);
58588   sqlite3_result_error(context, zErr, -1);
58589   sqlite3_free(zErr);
58590 }
58591
58592 /*
58593 ** Allocate or return the aggregate context for a user function.  A new
58594 ** context is allocated on the first call.  Subsequent calls return the
58595 ** same context that was returned on prior calls.
58596 */
58597 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
58598   Mem *pMem;
58599   assert( p && p->pFunc && p->pFunc->xStep );
58600   assert( sqlite3_mutex_held(p->s.db->mutex) );
58601   pMem = p->pMem;
58602   testcase( nByte<0 );
58603   if( (pMem->flags & MEM_Agg)==0 ){
58604     if( nByte<=0 ){
58605       sqlite3VdbeMemReleaseExternal(pMem);
58606       pMem->flags = MEM_Null;
58607       pMem->z = 0;
58608     }else{
58609       sqlite3VdbeMemGrow(pMem, nByte, 0);
58610       pMem->flags = MEM_Agg;
58611       pMem->u.pDef = p->pFunc;
58612       if( pMem->z ){
58613         memset(pMem->z, 0, nByte);
58614       }
58615     }
58616   }
58617   return (void*)pMem->z;
58618 }
58619
58620 /*
58621 ** Return the auxilary data pointer, if any, for the iArg'th argument to
58622 ** the user-function defined by pCtx.
58623 */
58624 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
58625   VdbeFunc *pVdbeFunc;
58626
58627   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
58628   pVdbeFunc = pCtx->pVdbeFunc;
58629   if( !pVdbeFunc || iArg>=pVdbeFunc->nAux || iArg<0 ){
58630     return 0;
58631   }
58632   return pVdbeFunc->apAux[iArg].pAux;
58633 }
58634
58635 /*
58636 ** Set the auxilary data pointer and delete function, for the iArg'th
58637 ** argument to the user-function defined by pCtx. Any previous value is
58638 ** deleted by calling the delete function specified when it was set.
58639 */
58640 SQLITE_API void sqlite3_set_auxdata(
58641   sqlite3_context *pCtx, 
58642   int iArg, 
58643   void *pAux, 
58644   void (*xDelete)(void*)
58645 ){
58646   struct AuxData *pAuxData;
58647   VdbeFunc *pVdbeFunc;
58648   if( iArg<0 ) goto failed;
58649
58650   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
58651   pVdbeFunc = pCtx->pVdbeFunc;
58652   if( !pVdbeFunc || pVdbeFunc->nAux<=iArg ){
58653     int nAux = (pVdbeFunc ? pVdbeFunc->nAux : 0);
58654     int nMalloc = sizeof(VdbeFunc) + sizeof(struct AuxData)*iArg;
58655     pVdbeFunc = sqlite3DbRealloc(pCtx->s.db, pVdbeFunc, nMalloc);
58656     if( !pVdbeFunc ){
58657       goto failed;
58658     }
58659     pCtx->pVdbeFunc = pVdbeFunc;
58660     memset(&pVdbeFunc->apAux[nAux], 0, sizeof(struct AuxData)*(iArg+1-nAux));
58661     pVdbeFunc->nAux = iArg+1;
58662     pVdbeFunc->pFunc = pCtx->pFunc;
58663   }
58664
58665   pAuxData = &pVdbeFunc->apAux[iArg];
58666   if( pAuxData->pAux && pAuxData->xDelete ){
58667     pAuxData->xDelete(pAuxData->pAux);
58668   }
58669   pAuxData->pAux = pAux;
58670   pAuxData->xDelete = xDelete;
58671   return;
58672
58673 failed:
58674   if( xDelete ){
58675     xDelete(pAux);
58676   }
58677 }
58678
58679 #ifndef SQLITE_OMIT_DEPRECATED
58680 /*
58681 ** Return the number of times the Step function of a aggregate has been 
58682 ** called.
58683 **
58684 ** This function is deprecated.  Do not use it for new code.  It is
58685 ** provide only to avoid breaking legacy code.  New aggregate function
58686 ** implementations should keep their own counts within their aggregate
58687 ** context.
58688 */
58689 SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
58690   assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
58691   return p->pMem->n;
58692 }
58693 #endif
58694
58695 /*
58696 ** Return the number of columns in the result set for the statement pStmt.
58697 */
58698 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
58699   Vdbe *pVm = (Vdbe *)pStmt;
58700   return pVm ? pVm->nResColumn : 0;
58701 }
58702
58703 /*
58704 ** Return the number of values available from the current row of the
58705 ** currently executing statement pStmt.
58706 */
58707 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
58708   Vdbe *pVm = (Vdbe *)pStmt;
58709   if( pVm==0 || pVm->pResultSet==0 ) return 0;
58710   return pVm->nResColumn;
58711 }
58712
58713
58714 /*
58715 ** Check to see if column iCol of the given statement is valid.  If
58716 ** it is, return a pointer to the Mem for the value of that column.
58717 ** If iCol is not valid, return a pointer to a Mem which has a value
58718 ** of NULL.
58719 */
58720 static Mem *columnMem(sqlite3_stmt *pStmt, int i){
58721   Vdbe *pVm;
58722   int vals;
58723   Mem *pOut;
58724
58725   pVm = (Vdbe *)pStmt;
58726   if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
58727     sqlite3_mutex_enter(pVm->db->mutex);
58728     vals = sqlite3_data_count(pStmt);
58729     pOut = &pVm->pResultSet[i];
58730   }else{
58731     /* If the value passed as the second argument is out of range, return
58732     ** a pointer to the following static Mem object which contains the
58733     ** value SQL NULL. Even though the Mem structure contains an element
58734     ** of type i64, on certain architecture (x86) with certain compiler
58735     ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
58736     ** instead of an 8-byte one. This all works fine, except that when
58737     ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
58738     ** that a Mem structure is located on an 8-byte boundary. To prevent
58739     ** this assert() from failing, when building with SQLITE_DEBUG defined
58740     ** using gcc, force nullMem to be 8-byte aligned using the magical
58741     ** __attribute__((aligned(8))) macro.  */
58742     static const Mem nullMem 
58743 #if defined(SQLITE_DEBUG) && defined(__GNUC__)
58744       __attribute__((aligned(8))) 
58745 #endif
58746       = {{0}, (double)0, 0, "", 0, MEM_Null, SQLITE_NULL, 0, 0, 0 };
58747
58748     if( pVm && ALWAYS(pVm->db) ){
58749       sqlite3_mutex_enter(pVm->db->mutex);
58750       sqlite3Error(pVm->db, SQLITE_RANGE, 0);
58751     }
58752     pOut = (Mem*)&nullMem;
58753   }
58754   return pOut;
58755 }
58756
58757 /*
58758 ** This function is called after invoking an sqlite3_value_XXX function on a 
58759 ** column value (i.e. a value returned by evaluating an SQL expression in the
58760 ** select list of a SELECT statement) that may cause a malloc() failure. If 
58761 ** malloc() has failed, the threads mallocFailed flag is cleared and the result
58762 ** code of statement pStmt set to SQLITE_NOMEM.
58763 **
58764 ** Specifically, this is called from within:
58765 **
58766 **     sqlite3_column_int()
58767 **     sqlite3_column_int64()
58768 **     sqlite3_column_text()
58769 **     sqlite3_column_text16()
58770 **     sqlite3_column_real()
58771 **     sqlite3_column_bytes()
58772 **     sqlite3_column_bytes16()
58773 **     sqiite3_column_blob()
58774 */
58775 static void columnMallocFailure(sqlite3_stmt *pStmt)
58776 {
58777   /* If malloc() failed during an encoding conversion within an
58778   ** sqlite3_column_XXX API, then set the return code of the statement to
58779   ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
58780   ** and _finalize() will return NOMEM.
58781   */
58782   Vdbe *p = (Vdbe *)pStmt;
58783   if( p ){
58784     p->rc = sqlite3ApiExit(p->db, p->rc);
58785     sqlite3_mutex_leave(p->db->mutex);
58786   }
58787 }
58788
58789 /**************************** sqlite3_column_  *******************************
58790 ** The following routines are used to access elements of the current row
58791 ** in the result set.
58792 */
58793 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
58794   const void *val;
58795   val = sqlite3_value_blob( columnMem(pStmt,i) );
58796   /* Even though there is no encoding conversion, value_blob() might
58797   ** need to call malloc() to expand the result of a zeroblob() 
58798   ** expression. 
58799   */
58800   columnMallocFailure(pStmt);
58801   return val;
58802 }
58803 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
58804   int val = sqlite3_value_bytes( columnMem(pStmt,i) );
58805   columnMallocFailure(pStmt);
58806   return val;
58807 }
58808 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
58809   int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
58810   columnMallocFailure(pStmt);
58811   return val;
58812 }
58813 SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
58814   double val = sqlite3_value_double( columnMem(pStmt,i) );
58815   columnMallocFailure(pStmt);
58816   return val;
58817 }
58818 SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
58819   int val = sqlite3_value_int( columnMem(pStmt,i) );
58820   columnMallocFailure(pStmt);
58821   return val;
58822 }
58823 SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
58824   sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
58825   columnMallocFailure(pStmt);
58826   return val;
58827 }
58828 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
58829   const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
58830   columnMallocFailure(pStmt);
58831   return val;
58832 }
58833 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
58834   Mem *pOut = columnMem(pStmt, i);
58835   if( pOut->flags&MEM_Static ){
58836     pOut->flags &= ~MEM_Static;
58837     pOut->flags |= MEM_Ephem;
58838   }
58839   columnMallocFailure(pStmt);
58840   return (sqlite3_value *)pOut;
58841 }
58842 #ifndef SQLITE_OMIT_UTF16
58843 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
58844   const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
58845   columnMallocFailure(pStmt);
58846   return val;
58847 }
58848 #endif /* SQLITE_OMIT_UTF16 */
58849 SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
58850   int iType = sqlite3_value_type( columnMem(pStmt,i) );
58851   columnMallocFailure(pStmt);
58852   return iType;
58853 }
58854
58855 /* The following function is experimental and subject to change or
58856 ** removal */
58857 /*int sqlite3_column_numeric_type(sqlite3_stmt *pStmt, int i){
58858 **  return sqlite3_value_numeric_type( columnMem(pStmt,i) );
58859 **}
58860 */
58861
58862 /*
58863 ** Convert the N-th element of pStmt->pColName[] into a string using
58864 ** xFunc() then return that string.  If N is out of range, return 0.
58865 **
58866 ** There are up to 5 names for each column.  useType determines which
58867 ** name is returned.  Here are the names:
58868 **
58869 **    0      The column name as it should be displayed for output
58870 **    1      The datatype name for the column
58871 **    2      The name of the database that the column derives from
58872 **    3      The name of the table that the column derives from
58873 **    4      The name of the table column that the result column derives from
58874 **
58875 ** If the result is not a simple column reference (if it is an expression
58876 ** or a constant) then useTypes 2, 3, and 4 return NULL.
58877 */
58878 static const void *columnName(
58879   sqlite3_stmt *pStmt,
58880   int N,
58881   const void *(*xFunc)(Mem*),
58882   int useType
58883 ){
58884   const void *ret = 0;
58885   Vdbe *p = (Vdbe *)pStmt;
58886   int n;
58887   sqlite3 *db = p->db;
58888   
58889   assert( db!=0 );
58890   n = sqlite3_column_count(pStmt);
58891   if( N<n && N>=0 ){
58892     N += useType*n;
58893     sqlite3_mutex_enter(db->mutex);
58894     assert( db->mallocFailed==0 );
58895     ret = xFunc(&p->aColName[N]);
58896      /* A malloc may have failed inside of the xFunc() call. If this
58897     ** is the case, clear the mallocFailed flag and return NULL.
58898     */
58899     if( db->mallocFailed ){
58900       db->mallocFailed = 0;
58901       ret = 0;
58902     }
58903     sqlite3_mutex_leave(db->mutex);
58904   }
58905   return ret;
58906 }
58907
58908 /*
58909 ** Return the name of the Nth column of the result set returned by SQL
58910 ** statement pStmt.
58911 */
58912 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
58913   return columnName(
58914       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
58915 }
58916 #ifndef SQLITE_OMIT_UTF16
58917 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
58918   return columnName(
58919       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
58920 }
58921 #endif
58922
58923 /*
58924 ** Constraint:  If you have ENABLE_COLUMN_METADATA then you must
58925 ** not define OMIT_DECLTYPE.
58926 */
58927 #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
58928 # error "Must not define both SQLITE_OMIT_DECLTYPE \
58929          and SQLITE_ENABLE_COLUMN_METADATA"
58930 #endif
58931
58932 #ifndef SQLITE_OMIT_DECLTYPE
58933 /*
58934 ** Return the column declaration type (if applicable) of the 'i'th column
58935 ** of the result set of SQL statement pStmt.
58936 */
58937 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
58938   return columnName(
58939       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
58940 }
58941 #ifndef SQLITE_OMIT_UTF16
58942 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
58943   return columnName(
58944       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
58945 }
58946 #endif /* SQLITE_OMIT_UTF16 */
58947 #endif /* SQLITE_OMIT_DECLTYPE */
58948
58949 #ifdef SQLITE_ENABLE_COLUMN_METADATA
58950 /*
58951 ** Return the name of the database from which a result column derives.
58952 ** NULL is returned if the result column is an expression or constant or
58953 ** anything else which is not an unabiguous reference to a database column.
58954 */
58955 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
58956   return columnName(
58957       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
58958 }
58959 #ifndef SQLITE_OMIT_UTF16
58960 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
58961   return columnName(
58962       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
58963 }
58964 #endif /* SQLITE_OMIT_UTF16 */
58965
58966 /*
58967 ** Return the name of the table from which a result column derives.
58968 ** NULL is returned if the result column is an expression or constant or
58969 ** anything else which is not an unabiguous reference to a database column.
58970 */
58971 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
58972   return columnName(
58973       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
58974 }
58975 #ifndef SQLITE_OMIT_UTF16
58976 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
58977   return columnName(
58978       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
58979 }
58980 #endif /* SQLITE_OMIT_UTF16 */
58981
58982 /*
58983 ** Return the name of the table column from which a result column derives.
58984 ** NULL is returned if the result column is an expression or constant or
58985 ** anything else which is not an unabiguous reference to a database column.
58986 */
58987 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
58988   return columnName(
58989       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
58990 }
58991 #ifndef SQLITE_OMIT_UTF16
58992 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
58993   return columnName(
58994       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
58995 }
58996 #endif /* SQLITE_OMIT_UTF16 */
58997 #endif /* SQLITE_ENABLE_COLUMN_METADATA */
58998
58999
59000 /******************************* sqlite3_bind_  ***************************
59001 ** 
59002 ** Routines used to attach values to wildcards in a compiled SQL statement.
59003 */
59004 /*
59005 ** Unbind the value bound to variable i in virtual machine p. This is the 
59006 ** the same as binding a NULL value to the column. If the "i" parameter is
59007 ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
59008 **
59009 ** A successful evaluation of this routine acquires the mutex on p.
59010 ** the mutex is released if any kind of error occurs.
59011 **
59012 ** The error code stored in database p->db is overwritten with the return
59013 ** value in any case.
59014 */
59015 static int vdbeUnbind(Vdbe *p, int i){
59016   Mem *pVar;
59017   if( vdbeSafetyNotNull(p) ){
59018     return SQLITE_MISUSE_BKPT;
59019   }
59020   sqlite3_mutex_enter(p->db->mutex);
59021   if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
59022     sqlite3Error(p->db, SQLITE_MISUSE, 0);
59023     sqlite3_mutex_leave(p->db->mutex);
59024     sqlite3_log(SQLITE_MISUSE, 
59025         "bind on a busy prepared statement: [%s]", p->zSql);
59026     return SQLITE_MISUSE_BKPT;
59027   }
59028   if( i<1 || i>p->nVar ){
59029     sqlite3Error(p->db, SQLITE_RANGE, 0);
59030     sqlite3_mutex_leave(p->db->mutex);
59031     return SQLITE_RANGE;
59032   }
59033   i--;
59034   pVar = &p->aVar[i];
59035   sqlite3VdbeMemRelease(pVar);
59036   pVar->flags = MEM_Null;
59037   sqlite3Error(p->db, SQLITE_OK, 0);
59038
59039   /* If the bit corresponding to this variable in Vdbe.expmask is set, then 
59040   ** binding a new value to this variable invalidates the current query plan.
59041   **
59042   ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
59043   ** parameter in the WHERE clause might influence the choice of query plan
59044   ** for a statement, then the statement will be automatically recompiled,
59045   ** as if there had been a schema change, on the first sqlite3_step() call
59046   ** following any change to the bindings of that parameter.
59047   */
59048   if( p->isPrepareV2 &&
59049      ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
59050   ){
59051     p->expired = 1;
59052   }
59053   return SQLITE_OK;
59054 }
59055
59056 /*
59057 ** Bind a text or BLOB value.
59058 */
59059 static int bindText(
59060   sqlite3_stmt *pStmt,   /* The statement to bind against */
59061   int i,                 /* Index of the parameter to bind */
59062   const void *zData,     /* Pointer to the data to be bound */
59063   int nData,             /* Number of bytes of data to be bound */
59064   void (*xDel)(void*),   /* Destructor for the data */
59065   u8 encoding            /* Encoding for the data */
59066 ){
59067   Vdbe *p = (Vdbe *)pStmt;
59068   Mem *pVar;
59069   int rc;
59070
59071   rc = vdbeUnbind(p, i);
59072   if( rc==SQLITE_OK ){
59073     if( zData!=0 ){
59074       pVar = &p->aVar[i-1];
59075       rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
59076       if( rc==SQLITE_OK && encoding!=0 ){
59077         rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
59078       }
59079       sqlite3Error(p->db, rc, 0);
59080       rc = sqlite3ApiExit(p->db, rc);
59081     }
59082     sqlite3_mutex_leave(p->db->mutex);
59083   }
59084   return rc;
59085 }
59086
59087
59088 /*
59089 ** Bind a blob value to an SQL statement variable.
59090 */
59091 SQLITE_API int sqlite3_bind_blob(
59092   sqlite3_stmt *pStmt, 
59093   int i, 
59094   const void *zData, 
59095   int nData, 
59096   void (*xDel)(void*)
59097 ){
59098   return bindText(pStmt, i, zData, nData, xDel, 0);
59099 }
59100 SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
59101   int rc;
59102   Vdbe *p = (Vdbe *)pStmt;
59103   rc = vdbeUnbind(p, i);
59104   if( rc==SQLITE_OK ){
59105     sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
59106     sqlite3_mutex_leave(p->db->mutex);
59107   }
59108   return rc;
59109 }
59110 SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
59111   return sqlite3_bind_int64(p, i, (i64)iValue);
59112 }
59113 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
59114   int rc;
59115   Vdbe *p = (Vdbe *)pStmt;
59116   rc = vdbeUnbind(p, i);
59117   if( rc==SQLITE_OK ){
59118     sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
59119     sqlite3_mutex_leave(p->db->mutex);
59120   }
59121   return rc;
59122 }
59123 SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
59124   int rc;
59125   Vdbe *p = (Vdbe*)pStmt;
59126   rc = vdbeUnbind(p, i);
59127   if( rc==SQLITE_OK ){
59128     sqlite3_mutex_leave(p->db->mutex);
59129   }
59130   return rc;
59131 }
59132 SQLITE_API int sqlite3_bind_text( 
59133   sqlite3_stmt *pStmt, 
59134   int i, 
59135   const char *zData, 
59136   int nData, 
59137   void (*xDel)(void*)
59138 ){
59139   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
59140 }
59141 #ifndef SQLITE_OMIT_UTF16
59142 SQLITE_API int sqlite3_bind_text16(
59143   sqlite3_stmt *pStmt, 
59144   int i, 
59145   const void *zData, 
59146   int nData, 
59147   void (*xDel)(void*)
59148 ){
59149   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
59150 }
59151 #endif /* SQLITE_OMIT_UTF16 */
59152 SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
59153   int rc;
59154   switch( pValue->type ){
59155     case SQLITE_INTEGER: {
59156       rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
59157       break;
59158     }
59159     case SQLITE_FLOAT: {
59160       rc = sqlite3_bind_double(pStmt, i, pValue->r);
59161       break;
59162     }
59163     case SQLITE_BLOB: {
59164       if( pValue->flags & MEM_Zero ){
59165         rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
59166       }else{
59167         rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
59168       }
59169       break;
59170     }
59171     case SQLITE_TEXT: {
59172       rc = bindText(pStmt,i,  pValue->z, pValue->n, SQLITE_TRANSIENT,
59173                               pValue->enc);
59174       break;
59175     }
59176     default: {
59177       rc = sqlite3_bind_null(pStmt, i);
59178       break;
59179     }
59180   }
59181   return rc;
59182 }
59183 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
59184   int rc;
59185   Vdbe *p = (Vdbe *)pStmt;
59186   rc = vdbeUnbind(p, i);
59187   if( rc==SQLITE_OK ){
59188     sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
59189     sqlite3_mutex_leave(p->db->mutex);
59190   }
59191   return rc;
59192 }
59193
59194 /*
59195 ** Return the number of wildcards that can be potentially bound to.
59196 ** This routine is added to support DBD::SQLite.  
59197 */
59198 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
59199   Vdbe *p = (Vdbe*)pStmt;
59200   return p ? p->nVar : 0;
59201 }
59202
59203 /*
59204 ** Create a mapping from variable numbers to variable names
59205 ** in the Vdbe.azVar[] array, if such a mapping does not already
59206 ** exist.
59207 */
59208 static void createVarMap(Vdbe *p){
59209   if( !p->okVar ){
59210     int j;
59211     Op *pOp;
59212     sqlite3_mutex_enter(p->db->mutex);
59213     /* The race condition here is harmless.  If two threads call this
59214     ** routine on the same Vdbe at the same time, they both might end
59215     ** up initializing the Vdbe.azVar[] array.  That is a little extra
59216     ** work but it results in the same answer.
59217     */
59218     for(j=0, pOp=p->aOp; j<p->nOp; j++, pOp++){
59219       if( pOp->opcode==OP_Variable ){
59220         assert( pOp->p1>0 && pOp->p1<=p->nVar );
59221         p->azVar[pOp->p1-1] = pOp->p4.z;
59222       }
59223     }
59224     p->okVar = 1;
59225     sqlite3_mutex_leave(p->db->mutex);
59226   }
59227 }
59228
59229 /*
59230 ** Return the name of a wildcard parameter.  Return NULL if the index
59231 ** is out of range or if the wildcard is unnamed.
59232 **
59233 ** The result is always UTF-8.
59234 */
59235 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
59236   Vdbe *p = (Vdbe*)pStmt;
59237   if( p==0 || i<1 || i>p->nVar ){
59238     return 0;
59239   }
59240   createVarMap(p);
59241   return p->azVar[i-1];
59242 }
59243
59244 /*
59245 ** Given a wildcard parameter name, return the index of the variable
59246 ** with that name.  If there is no variable with the given name,
59247 ** return 0.
59248 */
59249 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
59250   int i;
59251   if( p==0 ){
59252     return 0;
59253   }
59254   createVarMap(p); 
59255   if( zName ){
59256     for(i=0; i<p->nVar; i++){
59257       const char *z = p->azVar[i];
59258       if( z && memcmp(z,zName,nName)==0 && z[nName]==0 ){
59259         return i+1;
59260       }
59261     }
59262   }
59263   return 0;
59264 }
59265 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
59266   return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
59267 }
59268
59269 /*
59270 ** Transfer all bindings from the first statement over to the second.
59271 */
59272 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
59273   Vdbe *pFrom = (Vdbe*)pFromStmt;
59274   Vdbe *pTo = (Vdbe*)pToStmt;
59275   int i;
59276   assert( pTo->db==pFrom->db );
59277   assert( pTo->nVar==pFrom->nVar );
59278   sqlite3_mutex_enter(pTo->db->mutex);
59279   for(i=0; i<pFrom->nVar; i++){
59280     sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
59281   }
59282   sqlite3_mutex_leave(pTo->db->mutex);
59283   return SQLITE_OK;
59284 }
59285
59286 #ifndef SQLITE_OMIT_DEPRECATED
59287 /*
59288 ** Deprecated external interface.  Internal/core SQLite code
59289 ** should call sqlite3TransferBindings.
59290 **
59291 ** Is is misuse to call this routine with statements from different
59292 ** database connections.  But as this is a deprecated interface, we
59293 ** will not bother to check for that condition.
59294 **
59295 ** If the two statements contain a different number of bindings, then
59296 ** an SQLITE_ERROR is returned.  Nothing else can go wrong, so otherwise
59297 ** SQLITE_OK is returned.
59298 */
59299 SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
59300   Vdbe *pFrom = (Vdbe*)pFromStmt;
59301   Vdbe *pTo = (Vdbe*)pToStmt;
59302   if( pFrom->nVar!=pTo->nVar ){
59303     return SQLITE_ERROR;
59304   }
59305   if( pTo->isPrepareV2 && pTo->expmask ){
59306     pTo->expired = 1;
59307   }
59308   if( pFrom->isPrepareV2 && pFrom->expmask ){
59309     pFrom->expired = 1;
59310   }
59311   return sqlite3TransferBindings(pFromStmt, pToStmt);
59312 }
59313 #endif
59314
59315 /*
59316 ** Return the sqlite3* database handle to which the prepared statement given
59317 ** in the argument belongs.  This is the same database handle that was
59318 ** the first argument to the sqlite3_prepare() that was used to create
59319 ** the statement in the first place.
59320 */
59321 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
59322   return pStmt ? ((Vdbe*)pStmt)->db : 0;
59323 }
59324
59325 /*
59326 ** Return a pointer to the next prepared statement after pStmt associated
59327 ** with database connection pDb.  If pStmt is NULL, return the first
59328 ** prepared statement for the database connection.  Return NULL if there
59329 ** are no more.
59330 */
59331 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
59332   sqlite3_stmt *pNext;
59333   sqlite3_mutex_enter(pDb->mutex);
59334   if( pStmt==0 ){
59335     pNext = (sqlite3_stmt*)pDb->pVdbe;
59336   }else{
59337     pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
59338   }
59339   sqlite3_mutex_leave(pDb->mutex);
59340   return pNext;
59341 }
59342
59343 /*
59344 ** Return the value of a status counter for a prepared statement
59345 */
59346 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
59347   Vdbe *pVdbe = (Vdbe*)pStmt;
59348   int v = pVdbe->aCounter[op-1];
59349   if( resetFlag ) pVdbe->aCounter[op-1] = 0;
59350   return v;
59351 }
59352
59353 /************** End of vdbeapi.c *********************************************/
59354 /************** Begin file vdbetrace.c ***************************************/
59355 /*
59356 ** 2009 November 25
59357 **
59358 ** The author disclaims copyright to this source code.  In place of
59359 ** a legal notice, here is a blessing:
59360 **
59361 **    May you do good and not evil.
59362 **    May you find forgiveness for yourself and forgive others.
59363 **    May you share freely, never taking more than you give.
59364 **
59365 *************************************************************************
59366 **
59367 ** This file contains code used to insert the values of host parameters
59368 ** (aka "wildcards") into the SQL text output by sqlite3_trace().
59369 */
59370
59371 #ifndef SQLITE_OMIT_TRACE
59372
59373 /*
59374 ** zSql is a zero-terminated string of UTF-8 SQL text.  Return the number of
59375 ** bytes in this text up to but excluding the first character in
59376 ** a host parameter.  If the text contains no host parameters, return
59377 ** the total number of bytes in the text.
59378 */
59379 static int findNextHostParameter(const char *zSql, int *pnToken){
59380   int tokenType;
59381   int nTotal = 0;
59382   int n;
59383
59384   *pnToken = 0;
59385   while( zSql[0] ){
59386     n = sqlite3GetToken((u8*)zSql, &tokenType);
59387     assert( n>0 && tokenType!=TK_ILLEGAL );
59388     if( tokenType==TK_VARIABLE ){
59389       *pnToken = n;
59390       break;
59391     }
59392     nTotal += n;
59393     zSql += n;
59394   }
59395   return nTotal;
59396 }
59397
59398 /*
59399 ** Return a pointer to a string in memory obtained form sqlite3DbMalloc() which
59400 ** holds a copy of zRawSql but with host parameters expanded to their
59401 ** current bindings.
59402 **
59403 ** The calling function is responsible for making sure the memory returned
59404 ** is eventually freed.
59405 **
59406 ** ALGORITHM:  Scan the input string looking for host parameters in any of
59407 ** these forms:  ?, ?N, $A, @A, :A.  Take care to avoid text within
59408 ** string literals, quoted identifier names, and comments.  For text forms,
59409 ** the host parameter index is found by scanning the perpared
59410 ** statement for the corresponding OP_Variable opcode.  Once the host
59411 ** parameter index is known, locate the value in p->aVar[].  Then render
59412 ** the value as a literal in place of the host parameter name.
59413 */
59414 SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
59415   Vdbe *p,                 /* The prepared statement being evaluated */
59416   const char *zRawSql      /* Raw text of the SQL statement */
59417 ){
59418   sqlite3 *db;             /* The database connection */
59419   int idx = 0;             /* Index of a host parameter */
59420   int nextIndex = 1;       /* Index of next ? host parameter */
59421   int n;                   /* Length of a token prefix */
59422   int nToken;              /* Length of the parameter token */
59423   int i;                   /* Loop counter */
59424   Mem *pVar;               /* Value of a host parameter */
59425   StrAccum out;            /* Accumulate the output here */
59426   char zBase[100];         /* Initial working space */
59427
59428   db = p->db;
59429   sqlite3StrAccumInit(&out, zBase, sizeof(zBase), 
59430                       db->aLimit[SQLITE_LIMIT_LENGTH]);
59431   out.db = db;
59432   while( zRawSql[0] ){
59433     n = findNextHostParameter(zRawSql, &nToken);
59434     assert( n>0 );
59435     sqlite3StrAccumAppend(&out, zRawSql, n);
59436     zRawSql += n;
59437     assert( zRawSql[0] || nToken==0 );
59438     if( nToken==0 ) break;
59439     if( zRawSql[0]=='?' ){
59440       if( nToken>1 ){
59441         assert( sqlite3Isdigit(zRawSql[1]) );
59442         sqlite3GetInt32(&zRawSql[1], &idx);
59443       }else{
59444         idx = nextIndex;
59445       }
59446     }else{
59447       assert( zRawSql[0]==':' || zRawSql[0]=='$' || zRawSql[0]=='@' );
59448       testcase( zRawSql[0]==':' );
59449       testcase( zRawSql[0]=='$' );
59450       testcase( zRawSql[0]=='@' );
59451       idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
59452       assert( idx>0 );
59453     }
59454     zRawSql += nToken;
59455     nextIndex = idx + 1;
59456     assert( idx>0 && idx<=p->nVar );
59457     pVar = &p->aVar[idx-1];
59458     if( pVar->flags & MEM_Null ){
59459       sqlite3StrAccumAppend(&out, "NULL", 4);
59460     }else if( pVar->flags & MEM_Int ){
59461       sqlite3XPrintf(&out, "%lld", pVar->u.i);
59462     }else if( pVar->flags & MEM_Real ){
59463       sqlite3XPrintf(&out, "%!.15g", pVar->r);
59464     }else if( pVar->flags & MEM_Str ){
59465 #ifndef SQLITE_OMIT_UTF16
59466       u8 enc = ENC(db);
59467       if( enc!=SQLITE_UTF8 ){
59468         Mem utf8;
59469         memset(&utf8, 0, sizeof(utf8));
59470         utf8.db = db;
59471         sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
59472         sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
59473         sqlite3XPrintf(&out, "'%.*q'", utf8.n, utf8.z);
59474         sqlite3VdbeMemRelease(&utf8);
59475       }else
59476 #endif
59477       {
59478         sqlite3XPrintf(&out, "'%.*q'", pVar->n, pVar->z);
59479       }
59480     }else if( pVar->flags & MEM_Zero ){
59481       sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero);
59482     }else{
59483       assert( pVar->flags & MEM_Blob );
59484       sqlite3StrAccumAppend(&out, "x'", 2);
59485       for(i=0; i<pVar->n; i++){
59486         sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
59487       }
59488       sqlite3StrAccumAppend(&out, "'", 1);
59489     }
59490   }
59491   return sqlite3StrAccumFinish(&out);
59492 }
59493
59494 #endif /* #ifndef SQLITE_OMIT_TRACE */
59495
59496 /************** End of vdbetrace.c *******************************************/
59497 /************** Begin file vdbe.c ********************************************/
59498 /*
59499 ** 2001 September 15
59500 **
59501 ** The author disclaims copyright to this source code.  In place of
59502 ** a legal notice, here is a blessing:
59503 **
59504 **    May you do good and not evil.
59505 **    May you find forgiveness for yourself and forgive others.
59506 **    May you share freely, never taking more than you give.
59507 **
59508 *************************************************************************
59509 ** The code in this file implements execution method of the 
59510 ** Virtual Database Engine (VDBE).  A separate file ("vdbeaux.c")
59511 ** handles housekeeping details such as creating and deleting
59512 ** VDBE instances.  This file is solely interested in executing
59513 ** the VDBE program.
59514 **
59515 ** In the external interface, an "sqlite3_stmt*" is an opaque pointer
59516 ** to a VDBE.
59517 **
59518 ** The SQL parser generates a program which is then executed by
59519 ** the VDBE to do the work of the SQL statement.  VDBE programs are 
59520 ** similar in form to assembly language.  The program consists of
59521 ** a linear sequence of operations.  Each operation has an opcode 
59522 ** and 5 operands.  Operands P1, P2, and P3 are integers.  Operand P4 
59523 ** is a null-terminated string.  Operand P5 is an unsigned character.
59524 ** Few opcodes use all 5 operands.
59525 **
59526 ** Computation results are stored on a set of registers numbered beginning
59527 ** with 1 and going up to Vdbe.nMem.  Each register can store
59528 ** either an integer, a null-terminated string, a floating point
59529 ** number, or the SQL "NULL" value.  An implicit conversion from one
59530 ** type to the other occurs as necessary.
59531 ** 
59532 ** Most of the code in this file is taken up by the sqlite3VdbeExec()
59533 ** function which does the work of interpreting a VDBE program.
59534 ** But other routines are also provided to help in building up
59535 ** a program instruction by instruction.
59536 **
59537 ** Various scripts scan this source file in order to generate HTML
59538 ** documentation, headers files, or other derived files.  The formatting
59539 ** of the code in this file is, therefore, important.  See other comments
59540 ** in this file for details.  If in doubt, do not deviate from existing
59541 ** commenting and indentation practices when changing or adding code.
59542 */
59543
59544 /*
59545 ** Invoke this macro on memory cells just prior to changing the
59546 ** value of the cell.  This macro verifies that shallow copies are
59547 ** not misused.
59548 */
59549 #ifdef SQLITE_DEBUG
59550 # define memAboutToChange(P,M) sqlite3VdbeMemPrepareToChange(P,M)
59551 #else
59552 # define memAboutToChange(P,M)
59553 #endif
59554
59555 /*
59556 ** The following global variable is incremented every time a cursor
59557 ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes.  The test
59558 ** procedures use this information to make sure that indices are
59559 ** working correctly.  This variable has no function other than to
59560 ** help verify the correct operation of the library.
59561 */
59562 #ifdef SQLITE_TEST
59563 SQLITE_API int sqlite3_search_count = 0;
59564 #endif
59565
59566 /*
59567 ** When this global variable is positive, it gets decremented once before
59568 ** each instruction in the VDBE.  When reaches zero, the u1.isInterrupted
59569 ** field of the sqlite3 structure is set in order to simulate and interrupt.
59570 **
59571 ** This facility is used for testing purposes only.  It does not function
59572 ** in an ordinary build.
59573 */
59574 #ifdef SQLITE_TEST
59575 SQLITE_API int sqlite3_interrupt_count = 0;
59576 #endif
59577
59578 /*
59579 ** The next global variable is incremented each type the OP_Sort opcode
59580 ** is executed.  The test procedures use this information to make sure that
59581 ** sorting is occurring or not occurring at appropriate times.   This variable
59582 ** has no function other than to help verify the correct operation of the
59583 ** library.
59584 */
59585 #ifdef SQLITE_TEST
59586 SQLITE_API int sqlite3_sort_count = 0;
59587 #endif
59588
59589 /*
59590 ** The next global variable records the size of the largest MEM_Blob
59591 ** or MEM_Str that has been used by a VDBE opcode.  The test procedures
59592 ** use this information to make sure that the zero-blob functionality
59593 ** is working correctly.   This variable has no function other than to
59594 ** help verify the correct operation of the library.
59595 */
59596 #ifdef SQLITE_TEST
59597 SQLITE_API int sqlite3_max_blobsize = 0;
59598 static void updateMaxBlobsize(Mem *p){
59599   if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
59600     sqlite3_max_blobsize = p->n;
59601   }
59602 }
59603 #endif
59604
59605 /*
59606 ** The next global variable is incremented each type the OP_Found opcode
59607 ** is executed. This is used to test whether or not the foreign key
59608 ** operation implemented using OP_FkIsZero is working. This variable
59609 ** has no function other than to help verify the correct operation of the
59610 ** library.
59611 */
59612 #ifdef SQLITE_TEST
59613 SQLITE_API int sqlite3_found_count = 0;
59614 #endif
59615
59616 /*
59617 ** Test a register to see if it exceeds the current maximum blob size.
59618 ** If it does, record the new maximum blob size.
59619 */
59620 #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
59621 # define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)
59622 #else
59623 # define UPDATE_MAX_BLOBSIZE(P)
59624 #endif
59625
59626 /*
59627 ** Convert the given register into a string if it isn't one
59628 ** already. Return non-zero if a malloc() fails.
59629 */
59630 #define Stringify(P, enc) \
59631    if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
59632      { goto no_mem; }
59633
59634 /*
59635 ** An ephemeral string value (signified by the MEM_Ephem flag) contains
59636 ** a pointer to a dynamically allocated string where some other entity
59637 ** is responsible for deallocating that string.  Because the register
59638 ** does not control the string, it might be deleted without the register
59639 ** knowing it.
59640 **
59641 ** This routine converts an ephemeral string into a dynamically allocated
59642 ** string that the register itself controls.  In other words, it
59643 ** converts an MEM_Ephem string into an MEM_Dyn string.
59644 */
59645 #define Deephemeralize(P) \
59646    if( ((P)->flags&MEM_Ephem)!=0 \
59647        && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
59648
59649 /*
59650 ** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
59651 ** P if required.
59652 */
59653 #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
59654
59655 /*
59656 ** Argument pMem points at a register that will be passed to a
59657 ** user-defined function or returned to the user as the result of a query.
59658 ** This routine sets the pMem->type variable used by the sqlite3_value_*() 
59659 ** routines.
59660 */
59661 SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem){
59662   int flags = pMem->flags;
59663   if( flags & MEM_Null ){
59664     pMem->type = SQLITE_NULL;
59665   }
59666   else if( flags & MEM_Int ){
59667     pMem->type = SQLITE_INTEGER;
59668   }
59669   else if( flags & MEM_Real ){
59670     pMem->type = SQLITE_FLOAT;
59671   }
59672   else if( flags & MEM_Str ){
59673     pMem->type = SQLITE_TEXT;
59674   }else{
59675     pMem->type = SQLITE_BLOB;
59676   }
59677 }
59678
59679 /*
59680 ** Allocate VdbeCursor number iCur.  Return a pointer to it.  Return NULL
59681 ** if we run out of memory.
59682 */
59683 static VdbeCursor *allocateCursor(
59684   Vdbe *p,              /* The virtual machine */
59685   int iCur,             /* Index of the new VdbeCursor */
59686   int nField,           /* Number of fields in the table or index */
59687   int iDb,              /* When database the cursor belongs to, or -1 */
59688   int isBtreeCursor     /* True for B-Tree.  False for pseudo-table or vtab */
59689 ){
59690   /* Find the memory cell that will be used to store the blob of memory
59691   ** required for this VdbeCursor structure. It is convenient to use a 
59692   ** vdbe memory cell to manage the memory allocation required for a
59693   ** VdbeCursor structure for the following reasons:
59694   **
59695   **   * Sometimes cursor numbers are used for a couple of different
59696   **     purposes in a vdbe program. The different uses might require
59697   **     different sized allocations. Memory cells provide growable
59698   **     allocations.
59699   **
59700   **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
59701   **     be freed lazily via the sqlite3_release_memory() API. This
59702   **     minimizes the number of malloc calls made by the system.
59703   **
59704   ** Memory cells for cursors are allocated at the top of the address
59705   ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
59706   ** cursor 1 is managed by memory cell (p->nMem-1), etc.
59707   */
59708   Mem *pMem = &p->aMem[p->nMem-iCur];
59709
59710   int nByte;
59711   VdbeCursor *pCx = 0;
59712   nByte = 
59713       ROUND8(sizeof(VdbeCursor)) + 
59714       (isBtreeCursor?sqlite3BtreeCursorSize():0) + 
59715       2*nField*sizeof(u32);
59716
59717   assert( iCur<p->nCursor );
59718   if( p->apCsr[iCur] ){
59719     sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
59720     p->apCsr[iCur] = 0;
59721   }
59722   if( SQLITE_OK==sqlite3VdbeMemGrow(pMem, nByte, 0) ){
59723     p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
59724     memset(pCx, 0, sizeof(VdbeCursor));
59725     pCx->iDb = iDb;
59726     pCx->nField = nField;
59727     if( nField ){
59728       pCx->aType = (u32 *)&pMem->z[ROUND8(sizeof(VdbeCursor))];
59729     }
59730     if( isBtreeCursor ){
59731       pCx->pCursor = (BtCursor*)
59732           &pMem->z[ROUND8(sizeof(VdbeCursor))+2*nField*sizeof(u32)];
59733       sqlite3BtreeCursorZero(pCx->pCursor);
59734     }
59735   }
59736   return pCx;
59737 }
59738
59739 /*
59740 ** Try to convert a value into a numeric representation if we can
59741 ** do so without loss of information.  In other words, if the string
59742 ** looks like a number, convert it into a number.  If it does not
59743 ** look like a number, leave it alone.
59744 */
59745 static void applyNumericAffinity(Mem *pRec){
59746   if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
59747     double rValue;
59748     i64 iValue;
59749     u8 enc = pRec->enc;
59750     if( (pRec->flags&MEM_Str)==0 ) return;
59751     if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
59752     if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
59753       pRec->u.i = iValue;
59754       pRec->flags |= MEM_Int;
59755     }else{
59756       pRec->r = rValue;
59757       pRec->flags |= MEM_Real;
59758     }
59759   }
59760 }
59761
59762 /*
59763 ** Processing is determine by the affinity parameter:
59764 **
59765 ** SQLITE_AFF_INTEGER:
59766 ** SQLITE_AFF_REAL:
59767 ** SQLITE_AFF_NUMERIC:
59768 **    Try to convert pRec to an integer representation or a 
59769 **    floating-point representation if an integer representation
59770 **    is not possible.  Note that the integer representation is
59771 **    always preferred, even if the affinity is REAL, because
59772 **    an integer representation is more space efficient on disk.
59773 **
59774 ** SQLITE_AFF_TEXT:
59775 **    Convert pRec to a text representation.
59776 **
59777 ** SQLITE_AFF_NONE:
59778 **    No-op.  pRec is unchanged.
59779 */
59780 static void applyAffinity(
59781   Mem *pRec,          /* The value to apply affinity to */
59782   char affinity,      /* The affinity to be applied */
59783   u8 enc              /* Use this text encoding */
59784 ){
59785   if( affinity==SQLITE_AFF_TEXT ){
59786     /* Only attempt the conversion to TEXT if there is an integer or real
59787     ** representation (blob and NULL do not get converted) but no string
59788     ** representation.
59789     */
59790     if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
59791       sqlite3VdbeMemStringify(pRec, enc);
59792     }
59793     pRec->flags &= ~(MEM_Real|MEM_Int);
59794   }else if( affinity!=SQLITE_AFF_NONE ){
59795     assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
59796              || affinity==SQLITE_AFF_NUMERIC );
59797     applyNumericAffinity(pRec);
59798     if( pRec->flags & MEM_Real ){
59799       sqlite3VdbeIntegerAffinity(pRec);
59800     }
59801   }
59802 }
59803
59804 /*
59805 ** Try to convert the type of a function argument or a result column
59806 ** into a numeric representation.  Use either INTEGER or REAL whichever
59807 ** is appropriate.  But only do the conversion if it is possible without
59808 ** loss of information and return the revised type of the argument.
59809 **
59810 ** This is an EXPERIMENTAL api and is subject to change or removal.
59811 */
59812 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
59813   Mem *pMem = (Mem*)pVal;
59814   applyNumericAffinity(pMem);
59815   sqlite3VdbeMemStoreType(pMem);
59816   return pMem->type;
59817 }
59818
59819 /*
59820 ** Exported version of applyAffinity(). This one works on sqlite3_value*, 
59821 ** not the internal Mem* type.
59822 */
59823 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
59824   sqlite3_value *pVal, 
59825   u8 affinity, 
59826   u8 enc
59827 ){
59828   applyAffinity((Mem *)pVal, affinity, enc);
59829 }
59830
59831 #ifdef SQLITE_DEBUG
59832 /*
59833 ** Write a nice string representation of the contents of cell pMem
59834 ** into buffer zBuf, length nBuf.
59835 */
59836 SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
59837   char *zCsr = zBuf;
59838   int f = pMem->flags;
59839
59840   static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
59841
59842   if( f&MEM_Blob ){
59843     int i;
59844     char c;
59845     if( f & MEM_Dyn ){
59846       c = 'z';
59847       assert( (f & (MEM_Static|MEM_Ephem))==0 );
59848     }else if( f & MEM_Static ){
59849       c = 't';
59850       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
59851     }else if( f & MEM_Ephem ){
59852       c = 'e';
59853       assert( (f & (MEM_Static|MEM_Dyn))==0 );
59854     }else{
59855       c = 's';
59856     }
59857
59858     sqlite3_snprintf(100, zCsr, "%c", c);
59859     zCsr += sqlite3Strlen30(zCsr);
59860     sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
59861     zCsr += sqlite3Strlen30(zCsr);
59862     for(i=0; i<16 && i<pMem->n; i++){
59863       sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
59864       zCsr += sqlite3Strlen30(zCsr);
59865     }
59866     for(i=0; i<16 && i<pMem->n; i++){
59867       char z = pMem->z[i];
59868       if( z<32 || z>126 ) *zCsr++ = '.';
59869       else *zCsr++ = z;
59870     }
59871
59872     sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
59873     zCsr += sqlite3Strlen30(zCsr);
59874     if( f & MEM_Zero ){
59875       sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
59876       zCsr += sqlite3Strlen30(zCsr);
59877     }
59878     *zCsr = '\0';
59879   }else if( f & MEM_Str ){
59880     int j, k;
59881     zBuf[0] = ' ';
59882     if( f & MEM_Dyn ){
59883       zBuf[1] = 'z';
59884       assert( (f & (MEM_Static|MEM_Ephem))==0 );
59885     }else if( f & MEM_Static ){
59886       zBuf[1] = 't';
59887       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
59888     }else if( f & MEM_Ephem ){
59889       zBuf[1] = 'e';
59890       assert( (f & (MEM_Static|MEM_Dyn))==0 );
59891     }else{
59892       zBuf[1] = 's';
59893     }
59894     k = 2;
59895     sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
59896     k += sqlite3Strlen30(&zBuf[k]);
59897     zBuf[k++] = '[';
59898     for(j=0; j<15 && j<pMem->n; j++){
59899       u8 c = pMem->z[j];
59900       if( c>=0x20 && c<0x7f ){
59901         zBuf[k++] = c;
59902       }else{
59903         zBuf[k++] = '.';
59904       }
59905     }
59906     zBuf[k++] = ']';
59907     sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
59908     k += sqlite3Strlen30(&zBuf[k]);
59909     zBuf[k++] = 0;
59910   }
59911 }
59912 #endif
59913
59914 #ifdef SQLITE_DEBUG
59915 /*
59916 ** Print the value of a register for tracing purposes:
59917 */
59918 static void memTracePrint(FILE *out, Mem *p){
59919   if( p->flags & MEM_Null ){
59920     fprintf(out, " NULL");
59921   }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
59922     fprintf(out, " si:%lld", p->u.i);
59923   }else if( p->flags & MEM_Int ){
59924     fprintf(out, " i:%lld", p->u.i);
59925 #ifndef SQLITE_OMIT_FLOATING_POINT
59926   }else if( p->flags & MEM_Real ){
59927     fprintf(out, " r:%g", p->r);
59928 #endif
59929   }else if( p->flags & MEM_RowSet ){
59930     fprintf(out, " (rowset)");
59931   }else{
59932     char zBuf[200];
59933     sqlite3VdbeMemPrettyPrint(p, zBuf);
59934     fprintf(out, " ");
59935     fprintf(out, "%s", zBuf);
59936   }
59937 }
59938 static void registerTrace(FILE *out, int iReg, Mem *p){
59939   fprintf(out, "REG[%d] = ", iReg);
59940   memTracePrint(out, p);
59941   fprintf(out, "\n");
59942 }
59943 #endif
59944
59945 #ifdef SQLITE_DEBUG
59946 #  define REGISTER_TRACE(R,M) if(p->trace)registerTrace(p->trace,R,M)
59947 #else
59948 #  define REGISTER_TRACE(R,M)
59949 #endif
59950
59951
59952 #ifdef VDBE_PROFILE
59953
59954 /* 
59955 ** hwtime.h contains inline assembler code for implementing 
59956 ** high-performance timing routines.
59957 */
59958 /************** Include hwtime.h in the middle of vdbe.c *********************/
59959 /************** Begin file hwtime.h ******************************************/
59960 /*
59961 ** 2008 May 27
59962 **
59963 ** The author disclaims copyright to this source code.  In place of
59964 ** a legal notice, here is a blessing:
59965 **
59966 **    May you do good and not evil.
59967 **    May you find forgiveness for yourself and forgive others.
59968 **    May you share freely, never taking more than you give.
59969 **
59970 ******************************************************************************
59971 **
59972 ** This file contains inline asm code for retrieving "high-performance"
59973 ** counters for x86 class CPUs.
59974 */
59975 #ifndef _HWTIME_H_
59976 #define _HWTIME_H_
59977
59978 /*
59979 ** The following routine only works on pentium-class (or newer) processors.
59980 ** It uses the RDTSC opcode to read the cycle count value out of the
59981 ** processor and returns that value.  This can be used for high-res
59982 ** profiling.
59983 */
59984 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
59985       (defined(i386) || defined(__i386__) || defined(_M_IX86))
59986
59987   #if defined(__GNUC__)
59988
59989   __inline__ sqlite_uint64 sqlite3Hwtime(void){
59990      unsigned int lo, hi;
59991      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
59992      return (sqlite_uint64)hi << 32 | lo;
59993   }
59994
59995   #elif defined(_MSC_VER)
59996
59997   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
59998      __asm {
59999         rdtsc
60000         ret       ; return value at EDX:EAX
60001      }
60002   }
60003
60004   #endif
60005
60006 #elif (defined(__GNUC__) && defined(__x86_64__))
60007
60008   __inline__ sqlite_uint64 sqlite3Hwtime(void){
60009       unsigned long val;
60010       __asm__ __volatile__ ("rdtsc" : "=A" (val));
60011       return val;
60012   }
60013  
60014 #elif (defined(__GNUC__) && defined(__ppc__))
60015
60016   __inline__ sqlite_uint64 sqlite3Hwtime(void){
60017       unsigned long long retval;
60018       unsigned long junk;
60019       __asm__ __volatile__ ("\n\
60020           1:      mftbu   %1\n\
60021                   mftb    %L0\n\
60022                   mftbu   %0\n\
60023                   cmpw    %0,%1\n\
60024                   bne     1b"
60025                   : "=r" (retval), "=r" (junk));
60026       return retval;
60027   }
60028
60029 #else
60030
60031   #error Need implementation of sqlite3Hwtime() for your platform.
60032
60033   /*
60034   ** To compile without implementing sqlite3Hwtime() for your platform,
60035   ** you can remove the above #error and use the following
60036   ** stub function.  You will lose timing support for many
60037   ** of the debugging and testing utilities, but it should at
60038   ** least compile and run.
60039   */
60040 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
60041
60042 #endif
60043
60044 #endif /* !defined(_HWTIME_H_) */
60045
60046 /************** End of hwtime.h **********************************************/
60047 /************** Continuing where we left off in vdbe.c ***********************/
60048
60049 #endif
60050
60051 /*
60052 ** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
60053 ** sqlite3_interrupt() routine has been called.  If it has been, then
60054 ** processing of the VDBE program is interrupted.
60055 **
60056 ** This macro added to every instruction that does a jump in order to
60057 ** implement a loop.  This test used to be on every single instruction,
60058 ** but that meant we more testing that we needed.  By only testing the
60059 ** flag on jump instructions, we get a (small) speed improvement.
60060 */
60061 #define CHECK_FOR_INTERRUPT \
60062    if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
60063
60064
60065 #ifndef NDEBUG
60066 /*
60067 ** This function is only called from within an assert() expression. It
60068 ** checks that the sqlite3.nTransaction variable is correctly set to
60069 ** the number of non-transaction savepoints currently in the 
60070 ** linked list starting at sqlite3.pSavepoint.
60071 ** 
60072 ** Usage:
60073 **
60074 **     assert( checkSavepointCount(db) );
60075 */
60076 static int checkSavepointCount(sqlite3 *db){
60077   int n = 0;
60078   Savepoint *p;
60079   for(p=db->pSavepoint; p; p=p->pNext) n++;
60080   assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
60081   return 1;
60082 }
60083 #endif
60084
60085 /*
60086 ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
60087 ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
60088 ** in memory obtained from sqlite3DbMalloc).
60089 */
60090 static void importVtabErrMsg(Vdbe *p, sqlite3_vtab *pVtab){
60091   sqlite3 *db = p->db;
60092   sqlite3DbFree(db, p->zErrMsg);
60093   p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
60094   sqlite3_free(pVtab->zErrMsg);
60095   pVtab->zErrMsg = 0;
60096 }
60097
60098
60099 /*
60100 ** Execute as much of a VDBE program as we can then return.
60101 **
60102 ** sqlite3VdbeMakeReady() must be called before this routine in order to
60103 ** close the program with a final OP_Halt and to set up the callbacks
60104 ** and the error message pointer.
60105 **
60106 ** Whenever a row or result data is available, this routine will either
60107 ** invoke the result callback (if there is one) or return with
60108 ** SQLITE_ROW.
60109 **
60110 ** If an attempt is made to open a locked database, then this routine
60111 ** will either invoke the busy callback (if there is one) or it will
60112 ** return SQLITE_BUSY.
60113 **
60114 ** If an error occurs, an error message is written to memory obtained
60115 ** from sqlite3_malloc() and p->zErrMsg is made to point to that memory.
60116 ** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
60117 **
60118 ** If the callback ever returns non-zero, then the program exits
60119 ** immediately.  There will be no error message but the p->rc field is
60120 ** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
60121 **
60122 ** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
60123 ** routine to return SQLITE_ERROR.
60124 **
60125 ** Other fatal errors return SQLITE_ERROR.
60126 **
60127 ** After this routine has finished, sqlite3VdbeFinalize() should be
60128 ** used to clean up the mess that was left behind.
60129 */
60130 SQLITE_PRIVATE int sqlite3VdbeExec(
60131   Vdbe *p                    /* The VDBE */
60132 ){
60133   int pc=0;                  /* The program counter */
60134   Op *aOp = p->aOp;          /* Copy of p->aOp */
60135   Op *pOp;                   /* Current operation */
60136   int rc = SQLITE_OK;        /* Value to return */
60137   sqlite3 *db = p->db;       /* The database */
60138   u8 resetSchemaOnFault = 0; /* Reset schema after an error if true */
60139   u8 encoding = ENC(db);     /* The database encoding */
60140 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
60141   int checkProgress;         /* True if progress callbacks are enabled */
60142   int nProgressOps = 0;      /* Opcodes executed since progress callback. */
60143 #endif
60144   Mem *aMem = p->aMem;       /* Copy of p->aMem */
60145   Mem *pIn1 = 0;             /* 1st input operand */
60146   Mem *pIn2 = 0;             /* 2nd input operand */
60147   Mem *pIn3 = 0;             /* 3rd input operand */
60148   Mem *pOut = 0;             /* Output operand */
60149   int iCompare = 0;          /* Result of last OP_Compare operation */
60150   int *aPermute = 0;         /* Permutation of columns for OP_Compare */
60151 #ifdef VDBE_PROFILE
60152   u64 start;                 /* CPU clock count at start of opcode */
60153   int origPc;                /* Program counter at start of opcode */
60154 #endif
60155   /********************************************************************
60156   ** Automatically generated code
60157   **
60158   ** The following union is automatically generated by the
60159   ** vdbe-compress.tcl script.  The purpose of this union is to
60160   ** reduce the amount of stack space required by this function.
60161   ** See comments in the vdbe-compress.tcl script for details.
60162   */
60163   union vdbeExecUnion {
60164     struct OP_Yield_stack_vars {
60165       int pcDest;
60166     } aa;
60167     struct OP_Variable_stack_vars {
60168       Mem *pVar;       /* Value being transferred */
60169     } ab;
60170     struct OP_Move_stack_vars {
60171       char *zMalloc;   /* Holding variable for allocated memory */
60172       int n;           /* Number of registers left to copy */
60173       int p1;          /* Register to copy from */
60174       int p2;          /* Register to copy to */
60175     } ac;
60176     struct OP_ResultRow_stack_vars {
60177       Mem *pMem;
60178       int i;
60179     } ad;
60180     struct OP_Concat_stack_vars {
60181       i64 nByte;
60182     } ae;
60183     struct OP_Remainder_stack_vars {
60184       int flags;      /* Combined MEM_* flags from both inputs */
60185       i64 iA;         /* Integer value of left operand */
60186       i64 iB;         /* Integer value of right operand */
60187       double rA;      /* Real value of left operand */
60188       double rB;      /* Real value of right operand */
60189     } af;
60190     struct OP_Function_stack_vars {
60191       int i;
60192       Mem *pArg;
60193       sqlite3_context ctx;
60194       sqlite3_value **apVal;
60195       int n;
60196     } ag;
60197     struct OP_ShiftRight_stack_vars {
60198       i64 a;
60199       i64 b;
60200     } ah;
60201     struct OP_Ge_stack_vars {
60202       int res;            /* Result of the comparison of pIn1 against pIn3 */
60203       char affinity;      /* Affinity to use for comparison */
60204       u16 flags1;         /* Copy of initial value of pIn1->flags */
60205       u16 flags3;         /* Copy of initial value of pIn3->flags */
60206     } ai;
60207     struct OP_Compare_stack_vars {
60208       int n;
60209       int i;
60210       int p1;
60211       int p2;
60212       const KeyInfo *pKeyInfo;
60213       int idx;
60214       CollSeq *pColl;    /* Collating sequence to use on this term */
60215       int bRev;          /* True for DESCENDING sort order */
60216     } aj;
60217     struct OP_Or_stack_vars {
60218       int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
60219       int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
60220     } ak;
60221     struct OP_IfNot_stack_vars {
60222       int c;
60223     } al;
60224     struct OP_Column_stack_vars {
60225       u32 payloadSize;   /* Number of bytes in the record */
60226       i64 payloadSize64; /* Number of bytes in the record */
60227       int p1;            /* P1 value of the opcode */
60228       int p2;            /* column number to retrieve */
60229       VdbeCursor *pC;    /* The VDBE cursor */
60230       char *zRec;        /* Pointer to complete record-data */
60231       BtCursor *pCrsr;   /* The BTree cursor */
60232       u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
60233       u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
60234       int nField;        /* number of fields in the record */
60235       int len;           /* The length of the serialized data for the column */
60236       int i;             /* Loop counter */
60237       char *zData;       /* Part of the record being decoded */
60238       Mem *pDest;        /* Where to write the extracted value */
60239       Mem sMem;          /* For storing the record being decoded */
60240       u8 *zIdx;          /* Index into header */
60241       u8 *zEndHdr;       /* Pointer to first byte after the header */
60242       u32 offset;        /* Offset into the data */
60243       u32 szField;       /* Number of bytes in the content of a field */
60244       int szHdr;         /* Size of the header size field at start of record */
60245       int avail;         /* Number of bytes of available data */
60246       Mem *pReg;         /* PseudoTable input register */
60247     } am;
60248     struct OP_Affinity_stack_vars {
60249       const char *zAffinity;   /* The affinity to be applied */
60250       char cAff;               /* A single character of affinity */
60251     } an;
60252     struct OP_MakeRecord_stack_vars {
60253       u8 *zNewRecord;        /* A buffer to hold the data for the new record */
60254       Mem *pRec;             /* The new record */
60255       u64 nData;             /* Number of bytes of data space */
60256       int nHdr;              /* Number of bytes of header space */
60257       i64 nByte;             /* Data space required for this record */
60258       int nZero;             /* Number of zero bytes at the end of the record */
60259       int nVarint;           /* Number of bytes in a varint */
60260       u32 serial_type;       /* Type field */
60261       Mem *pData0;           /* First field to be combined into the record */
60262       Mem *pLast;            /* Last field of the record */
60263       int nField;            /* Number of fields in the record */
60264       char *zAffinity;       /* The affinity string for the record */
60265       int file_format;       /* File format to use for encoding */
60266       int i;                 /* Space used in zNewRecord[] */
60267       int len;               /* Length of a field */
60268     } ao;
60269     struct OP_Count_stack_vars {
60270       i64 nEntry;
60271       BtCursor *pCrsr;
60272     } ap;
60273     struct OP_Savepoint_stack_vars {
60274       int p1;                         /* Value of P1 operand */
60275       char *zName;                    /* Name of savepoint */
60276       int nName;
60277       Savepoint *pNew;
60278       Savepoint *pSavepoint;
60279       Savepoint *pTmp;
60280       int iSavepoint;
60281       int ii;
60282     } aq;
60283     struct OP_AutoCommit_stack_vars {
60284       int desiredAutoCommit;
60285       int iRollback;
60286       int turnOnAC;
60287     } ar;
60288     struct OP_Transaction_stack_vars {
60289       Btree *pBt;
60290     } as;
60291     struct OP_ReadCookie_stack_vars {
60292       int iMeta;
60293       int iDb;
60294       int iCookie;
60295     } at;
60296     struct OP_SetCookie_stack_vars {
60297       Db *pDb;
60298     } au;
60299     struct OP_VerifyCookie_stack_vars {
60300       int iMeta;
60301       Btree *pBt;
60302     } av;
60303     struct OP_OpenWrite_stack_vars {
60304       int nField;
60305       KeyInfo *pKeyInfo;
60306       int p2;
60307       int iDb;
60308       int wrFlag;
60309       Btree *pX;
60310       VdbeCursor *pCur;
60311       Db *pDb;
60312     } aw;
60313     struct OP_OpenEphemeral_stack_vars {
60314       VdbeCursor *pCx;
60315     } ax;
60316     struct OP_OpenPseudo_stack_vars {
60317       VdbeCursor *pCx;
60318     } ay;
60319     struct OP_SeekGt_stack_vars {
60320       int res;
60321       int oc;
60322       VdbeCursor *pC;
60323       UnpackedRecord r;
60324       int nField;
60325       i64 iKey;      /* The rowid we are to seek to */
60326     } az;
60327     struct OP_Seek_stack_vars {
60328       VdbeCursor *pC;
60329     } ba;
60330     struct OP_Found_stack_vars {
60331       int alreadyExists;
60332       VdbeCursor *pC;
60333       int res;
60334       UnpackedRecord *pIdxKey;
60335       UnpackedRecord r;
60336       char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
60337     } bb;
60338     struct OP_IsUnique_stack_vars {
60339       u16 ii;
60340       VdbeCursor *pCx;
60341       BtCursor *pCrsr;
60342       u16 nField;
60343       Mem *aMx;
60344       UnpackedRecord r;                  /* B-Tree index search key */
60345       i64 R;                             /* Rowid stored in register P3 */
60346     } bc;
60347     struct OP_NotExists_stack_vars {
60348       VdbeCursor *pC;
60349       BtCursor *pCrsr;
60350       int res;
60351       u64 iKey;
60352     } bd;
60353     struct OP_NewRowid_stack_vars {
60354       i64 v;                 /* The new rowid */
60355       VdbeCursor *pC;        /* Cursor of table to get the new rowid */
60356       int res;               /* Result of an sqlite3BtreeLast() */
60357       int cnt;               /* Counter to limit the number of searches */
60358       Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
60359       VdbeFrame *pFrame;     /* Root frame of VDBE */
60360     } be;
60361     struct OP_InsertInt_stack_vars {
60362       Mem *pData;       /* MEM cell holding data for the record to be inserted */
60363       Mem *pKey;        /* MEM cell holding key  for the record */
60364       i64 iKey;         /* The integer ROWID or key for the record to be inserted */
60365       VdbeCursor *pC;   /* Cursor to table into which insert is written */
60366       int nZero;        /* Number of zero-bytes to append */
60367       int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
60368       const char *zDb;  /* database name - used by the update hook */
60369       const char *zTbl; /* Table name - used by the opdate hook */
60370       int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
60371     } bf;
60372     struct OP_Delete_stack_vars {
60373       i64 iKey;
60374       VdbeCursor *pC;
60375     } bg;
60376     struct OP_RowData_stack_vars {
60377       VdbeCursor *pC;
60378       BtCursor *pCrsr;
60379       u32 n;
60380       i64 n64;
60381     } bh;
60382     struct OP_Rowid_stack_vars {
60383       VdbeCursor *pC;
60384       i64 v;
60385       sqlite3_vtab *pVtab;
60386       const sqlite3_module *pModule;
60387     } bi;
60388     struct OP_NullRow_stack_vars {
60389       VdbeCursor *pC;
60390     } bj;
60391     struct OP_Last_stack_vars {
60392       VdbeCursor *pC;
60393       BtCursor *pCrsr;
60394       int res;
60395     } bk;
60396     struct OP_Rewind_stack_vars {
60397       VdbeCursor *pC;
60398       BtCursor *pCrsr;
60399       int res;
60400     } bl;
60401     struct OP_Next_stack_vars {
60402       VdbeCursor *pC;
60403       BtCursor *pCrsr;
60404       int res;
60405     } bm;
60406     struct OP_IdxInsert_stack_vars {
60407       VdbeCursor *pC;
60408       BtCursor *pCrsr;
60409       int nKey;
60410       const char *zKey;
60411     } bn;
60412     struct OP_IdxDelete_stack_vars {
60413       VdbeCursor *pC;
60414       BtCursor *pCrsr;
60415       int res;
60416       UnpackedRecord r;
60417     } bo;
60418     struct OP_IdxRowid_stack_vars {
60419       BtCursor *pCrsr;
60420       VdbeCursor *pC;
60421       i64 rowid;
60422     } bp;
60423     struct OP_IdxGE_stack_vars {
60424       VdbeCursor *pC;
60425       int res;
60426       UnpackedRecord r;
60427     } bq;
60428     struct OP_Destroy_stack_vars {
60429       int iMoved;
60430       int iCnt;
60431       Vdbe *pVdbe;
60432       int iDb;
60433     } br;
60434     struct OP_Clear_stack_vars {
60435       int nChange;
60436     } bs;
60437     struct OP_CreateTable_stack_vars {
60438       int pgno;
60439       int flags;
60440       Db *pDb;
60441     } bt;
60442     struct OP_ParseSchema_stack_vars {
60443       int iDb;
60444       const char *zMaster;
60445       char *zSql;
60446       InitData initData;
60447     } bu;
60448     struct OP_IntegrityCk_stack_vars {
60449       int nRoot;      /* Number of tables to check.  (Number of root pages.) */
60450       int *aRoot;     /* Array of rootpage numbers for tables to be checked */
60451       int j;          /* Loop counter */
60452       int nErr;       /* Number of errors reported */
60453       char *z;        /* Text of the error report */
60454       Mem *pnErr;     /* Register keeping track of errors remaining */
60455     } bv;
60456     struct OP_RowSetRead_stack_vars {
60457       i64 val;
60458     } bw;
60459     struct OP_RowSetTest_stack_vars {
60460       int iSet;
60461       int exists;
60462     } bx;
60463     struct OP_Program_stack_vars {
60464       int nMem;               /* Number of memory registers for sub-program */
60465       int nByte;              /* Bytes of runtime space required for sub-program */
60466       Mem *pRt;               /* Register to allocate runtime space */
60467       Mem *pMem;              /* Used to iterate through memory cells */
60468       Mem *pEnd;              /* Last memory cell in new array */
60469       VdbeFrame *pFrame;      /* New vdbe frame to execute in */
60470       SubProgram *pProgram;   /* Sub-program to execute */
60471       void *t;                /* Token identifying trigger */
60472     } by;
60473     struct OP_Param_stack_vars {
60474       VdbeFrame *pFrame;
60475       Mem *pIn;
60476     } bz;
60477     struct OP_MemMax_stack_vars {
60478       Mem *pIn1;
60479       VdbeFrame *pFrame;
60480     } ca;
60481     struct OP_AggStep_stack_vars {
60482       int n;
60483       int i;
60484       Mem *pMem;
60485       Mem *pRec;
60486       sqlite3_context ctx;
60487       sqlite3_value **apVal;
60488     } cb;
60489     struct OP_AggFinal_stack_vars {
60490       Mem *pMem;
60491     } cc;
60492     struct OP_JournalMode_stack_vars {
60493       Btree *pBt;                     /* Btree to change journal mode of */
60494       Pager *pPager;                  /* Pager associated with pBt */
60495       int eNew;                       /* New journal mode */
60496       int eOld;                       /* The old journal mode */
60497       const char *zFilename;          /* Name of database file for pPager */
60498     } cd;
60499     struct OP_IncrVacuum_stack_vars {
60500       Btree *pBt;
60501     } ce;
60502     struct OP_VBegin_stack_vars {
60503       VTable *pVTab;
60504     } cf;
60505     struct OP_VOpen_stack_vars {
60506       VdbeCursor *pCur;
60507       sqlite3_vtab_cursor *pVtabCursor;
60508       sqlite3_vtab *pVtab;
60509       sqlite3_module *pModule;
60510     } cg;
60511     struct OP_VFilter_stack_vars {
60512       int nArg;
60513       int iQuery;
60514       const sqlite3_module *pModule;
60515       Mem *pQuery;
60516       Mem *pArgc;
60517       sqlite3_vtab_cursor *pVtabCursor;
60518       sqlite3_vtab *pVtab;
60519       VdbeCursor *pCur;
60520       int res;
60521       int i;
60522       Mem **apArg;
60523     } ch;
60524     struct OP_VColumn_stack_vars {
60525       sqlite3_vtab *pVtab;
60526       const sqlite3_module *pModule;
60527       Mem *pDest;
60528       sqlite3_context sContext;
60529     } ci;
60530     struct OP_VNext_stack_vars {
60531       sqlite3_vtab *pVtab;
60532       const sqlite3_module *pModule;
60533       int res;
60534       VdbeCursor *pCur;
60535     } cj;
60536     struct OP_VRename_stack_vars {
60537       sqlite3_vtab *pVtab;
60538       Mem *pName;
60539     } ck;
60540     struct OP_VUpdate_stack_vars {
60541       sqlite3_vtab *pVtab;
60542       sqlite3_module *pModule;
60543       int nArg;
60544       int i;
60545       sqlite_int64 rowid;
60546       Mem **apArg;
60547       Mem *pX;
60548     } cl;
60549     struct OP_Trace_stack_vars {
60550       char *zTrace;
60551     } cm;
60552   } u;
60553   /* End automatically generated code
60554   ********************************************************************/
60555
60556   assert( p->magic==VDBE_MAGIC_RUN );  /* sqlite3_step() verifies this */
60557   sqlite3VdbeMutexArrayEnter(p);
60558   if( p->rc==SQLITE_NOMEM ){
60559     /* This happens if a malloc() inside a call to sqlite3_column_text() or
60560     ** sqlite3_column_text16() failed.  */
60561     goto no_mem;
60562   }
60563   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
60564   p->rc = SQLITE_OK;
60565   assert( p->explain==0 );
60566   p->pResultSet = 0;
60567   db->busyHandler.nBusy = 0;
60568   CHECK_FOR_INTERRUPT;
60569   sqlite3VdbeIOTraceSql(p);
60570 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
60571   checkProgress = db->xProgress!=0;
60572 #endif
60573 #ifdef SQLITE_DEBUG
60574   sqlite3BeginBenignMalloc();
60575   if( p->pc==0  && (p->db->flags & SQLITE_VdbeListing)!=0 ){
60576     int i;
60577     printf("VDBE Program Listing:\n");
60578     sqlite3VdbePrintSql(p);
60579     for(i=0; i<p->nOp; i++){
60580       sqlite3VdbePrintOp(stdout, i, &aOp[i]);
60581     }
60582   }
60583   sqlite3EndBenignMalloc();
60584 #endif
60585   for(pc=p->pc; rc==SQLITE_OK; pc++){
60586     assert( pc>=0 && pc<p->nOp );
60587     if( db->mallocFailed ) goto no_mem;
60588 #ifdef VDBE_PROFILE
60589     origPc = pc;
60590     start = sqlite3Hwtime();
60591 #endif
60592     pOp = &aOp[pc];
60593
60594     /* Only allow tracing if SQLITE_DEBUG is defined.
60595     */
60596 #ifdef SQLITE_DEBUG
60597     if( p->trace ){
60598       if( pc==0 ){
60599         printf("VDBE Execution Trace:\n");
60600         sqlite3VdbePrintSql(p);
60601       }
60602       sqlite3VdbePrintOp(p->trace, pc, pOp);
60603     }
60604 #endif
60605       
60606
60607     /* Check to see if we need to simulate an interrupt.  This only happens
60608     ** if we have a special test build.
60609     */
60610 #ifdef SQLITE_TEST
60611     if( sqlite3_interrupt_count>0 ){
60612       sqlite3_interrupt_count--;
60613       if( sqlite3_interrupt_count==0 ){
60614         sqlite3_interrupt(db);
60615       }
60616     }
60617 #endif
60618
60619 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
60620     /* Call the progress callback if it is configured and the required number
60621     ** of VDBE ops have been executed (either since this invocation of
60622     ** sqlite3VdbeExec() or since last time the progress callback was called).
60623     ** If the progress callback returns non-zero, exit the virtual machine with
60624     ** a return code SQLITE_ABORT.
60625     */
60626     if( checkProgress ){
60627       if( db->nProgressOps==nProgressOps ){
60628         int prc;
60629         prc = db->xProgress(db->pProgressArg);
60630         if( prc!=0 ){
60631           rc = SQLITE_INTERRUPT;
60632           goto vdbe_error_halt;
60633         }
60634         nProgressOps = 0;
60635       }
60636       nProgressOps++;
60637     }
60638 #endif
60639
60640     /* On any opcode with the "out2-prerelase" tag, free any
60641     ** external allocations out of mem[p2] and set mem[p2] to be
60642     ** an undefined integer.  Opcodes will either fill in the integer
60643     ** value or convert mem[p2] to a different type.
60644     */
60645     assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
60646     if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){
60647       assert( pOp->p2>0 );
60648       assert( pOp->p2<=p->nMem );
60649       pOut = &aMem[pOp->p2];
60650       memAboutToChange(p, pOut);
60651       sqlite3VdbeMemReleaseExternal(pOut);
60652       pOut->flags = MEM_Int;
60653     }
60654
60655     /* Sanity checking on other operands */
60656 #ifdef SQLITE_DEBUG
60657     if( (pOp->opflags & OPFLG_IN1)!=0 ){
60658       assert( pOp->p1>0 );
60659       assert( pOp->p1<=p->nMem );
60660       assert( memIsValid(&aMem[pOp->p1]) );
60661       REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
60662     }
60663     if( (pOp->opflags & OPFLG_IN2)!=0 ){
60664       assert( pOp->p2>0 );
60665       assert( pOp->p2<=p->nMem );
60666       assert( memIsValid(&aMem[pOp->p2]) );
60667       REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
60668     }
60669     if( (pOp->opflags & OPFLG_IN3)!=0 ){
60670       assert( pOp->p3>0 );
60671       assert( pOp->p3<=p->nMem );
60672       assert( memIsValid(&aMem[pOp->p3]) );
60673       REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
60674     }
60675     if( (pOp->opflags & OPFLG_OUT2)!=0 ){
60676       assert( pOp->p2>0 );
60677       assert( pOp->p2<=p->nMem );
60678       memAboutToChange(p, &aMem[pOp->p2]);
60679     }
60680     if( (pOp->opflags & OPFLG_OUT3)!=0 ){
60681       assert( pOp->p3>0 );
60682       assert( pOp->p3<=p->nMem );
60683       memAboutToChange(p, &aMem[pOp->p3]);
60684     }
60685 #endif
60686   
60687     switch( pOp->opcode ){
60688
60689 /*****************************************************************************
60690 ** What follows is a massive switch statement where each case implements a
60691 ** separate instruction in the virtual machine.  If we follow the usual
60692 ** indentation conventions, each case should be indented by 6 spaces.  But
60693 ** that is a lot of wasted space on the left margin.  So the code within
60694 ** the switch statement will break with convention and be flush-left. Another
60695 ** big comment (similar to this one) will mark the point in the code where
60696 ** we transition back to normal indentation.
60697 **
60698 ** The formatting of each case is important.  The makefile for SQLite
60699 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
60700 ** file looking for lines that begin with "case OP_".  The opcodes.h files
60701 ** will be filled with #defines that give unique integer values to each
60702 ** opcode and the opcodes.c file is filled with an array of strings where
60703 ** each string is the symbolic name for the corresponding opcode.  If the
60704 ** case statement is followed by a comment of the form "/# same as ... #/"
60705 ** that comment is used to determine the particular value of the opcode.
60706 **
60707 ** Other keywords in the comment that follows each case are used to
60708 ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
60709 ** Keywords include: in1, in2, in3, out2_prerelease, out2, out3.  See
60710 ** the mkopcodeh.awk script for additional information.
60711 **
60712 ** Documentation about VDBE opcodes is generated by scanning this file
60713 ** for lines of that contain "Opcode:".  That line and all subsequent
60714 ** comment lines are used in the generation of the opcode.html documentation
60715 ** file.
60716 **
60717 ** SUMMARY:
60718 **
60719 **     Formatting is important to scripts that scan this file.
60720 **     Do not deviate from the formatting style currently in use.
60721 **
60722 *****************************************************************************/
60723
60724 /* Opcode:  Goto * P2 * * *
60725 **
60726 ** An unconditional jump to address P2.
60727 ** The next instruction executed will be 
60728 ** the one at index P2 from the beginning of
60729 ** the program.
60730 */
60731 case OP_Goto: {             /* jump */
60732   CHECK_FOR_INTERRUPT;
60733   pc = pOp->p2 - 1;
60734   break;
60735 }
60736
60737 /* Opcode:  Gosub P1 P2 * * *
60738 **
60739 ** Write the current address onto register P1
60740 ** and then jump to address P2.
60741 */
60742 case OP_Gosub: {            /* jump, in1 */
60743   pIn1 = &aMem[pOp->p1];
60744   assert( (pIn1->flags & MEM_Dyn)==0 );
60745   memAboutToChange(p, pIn1);
60746   pIn1->flags = MEM_Int;
60747   pIn1->u.i = pc;
60748   REGISTER_TRACE(pOp->p1, pIn1);
60749   pc = pOp->p2 - 1;
60750   break;
60751 }
60752
60753 /* Opcode:  Return P1 * * * *
60754 **
60755 ** Jump to the next instruction after the address in register P1.
60756 */
60757 case OP_Return: {           /* in1 */
60758   pIn1 = &aMem[pOp->p1];
60759   assert( pIn1->flags & MEM_Int );
60760   pc = (int)pIn1->u.i;
60761   break;
60762 }
60763
60764 /* Opcode:  Yield P1 * * * *
60765 **
60766 ** Swap the program counter with the value in register P1.
60767 */
60768 case OP_Yield: {            /* in1 */
60769 #if 0  /* local variables moved into u.aa */
60770   int pcDest;
60771 #endif /* local variables moved into u.aa */
60772   pIn1 = &aMem[pOp->p1];
60773   assert( (pIn1->flags & MEM_Dyn)==0 );
60774   pIn1->flags = MEM_Int;
60775   u.aa.pcDest = (int)pIn1->u.i;
60776   pIn1->u.i = pc;
60777   REGISTER_TRACE(pOp->p1, pIn1);
60778   pc = u.aa.pcDest;
60779   break;
60780 }
60781
60782 /* Opcode:  HaltIfNull  P1 P2 P3 P4 *
60783 **
60784 ** Check the value in register P3.  If is is NULL then Halt using
60785 ** parameter P1, P2, and P4 as if this were a Halt instruction.  If the
60786 ** value in register P3 is not NULL, then this routine is a no-op.
60787 */
60788 case OP_HaltIfNull: {      /* in3 */
60789   pIn3 = &aMem[pOp->p3];
60790   if( (pIn3->flags & MEM_Null)==0 ) break;
60791   /* Fall through into OP_Halt */
60792 }
60793
60794 /* Opcode:  Halt P1 P2 * P4 *
60795 **
60796 ** Exit immediately.  All open cursors, etc are closed
60797 ** automatically.
60798 **
60799 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
60800 ** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
60801 ** For errors, it can be some other value.  If P1!=0 then P2 will determine
60802 ** whether or not to rollback the current transaction.  Do not rollback
60803 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
60804 ** then back out all changes that have occurred during this execution of the
60805 ** VDBE, but do not rollback the transaction. 
60806 **
60807 ** If P4 is not null then it is an error message string.
60808 **
60809 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
60810 ** every program.  So a jump past the last instruction of the program
60811 ** is the same as executing Halt.
60812 */
60813 case OP_Halt: {
60814   if( pOp->p1==SQLITE_OK && p->pFrame ){
60815     /* Halt the sub-program. Return control to the parent frame. */
60816     VdbeFrame *pFrame = p->pFrame;
60817     p->pFrame = pFrame->pParent;
60818     p->nFrame--;
60819     sqlite3VdbeSetChanges(db, p->nChange);
60820     pc = sqlite3VdbeFrameRestore(pFrame);
60821     if( pOp->p2==OE_Ignore ){
60822       /* Instruction pc is the OP_Program that invoked the sub-program 
60823       ** currently being halted. If the p2 instruction of this OP_Halt
60824       ** instruction is set to OE_Ignore, then the sub-program is throwing
60825       ** an IGNORE exception. In this case jump to the address specified
60826       ** as the p2 of the calling OP_Program.  */
60827       pc = p->aOp[pc].p2-1;
60828     }
60829     aOp = p->aOp;
60830     aMem = p->aMem;
60831     break;
60832   }
60833
60834   p->rc = pOp->p1;
60835   p->errorAction = (u8)pOp->p2;
60836   p->pc = pc;
60837   if( pOp->p4.z ){
60838     assert( p->rc!=SQLITE_OK );
60839     sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
60840     testcase( sqlite3GlobalConfig.xLog!=0 );
60841     sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pc, p->zSql, pOp->p4.z);
60842   }else if( p->rc ){
60843     testcase( sqlite3GlobalConfig.xLog!=0 );
60844     sqlite3_log(pOp->p1, "constraint failed at %d in [%s]", pc, p->zSql);
60845   }
60846   rc = sqlite3VdbeHalt(p);
60847   assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
60848   if( rc==SQLITE_BUSY ){
60849     p->rc = rc = SQLITE_BUSY;
60850   }else{
60851     assert( rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT );
60852     assert( rc==SQLITE_OK || db->nDeferredCons>0 );
60853     rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
60854   }
60855   goto vdbe_return;
60856 }
60857
60858 /* Opcode: Integer P1 P2 * * *
60859 **
60860 ** The 32-bit integer value P1 is written into register P2.
60861 */
60862 case OP_Integer: {         /* out2-prerelease */
60863   pOut->u.i = pOp->p1;
60864   break;
60865 }
60866
60867 /* Opcode: Int64 * P2 * P4 *
60868 **
60869 ** P4 is a pointer to a 64-bit integer value.
60870 ** Write that value into register P2.
60871 */
60872 case OP_Int64: {           /* out2-prerelease */
60873   assert( pOp->p4.pI64!=0 );
60874   pOut->u.i = *pOp->p4.pI64;
60875   break;
60876 }
60877
60878 #ifndef SQLITE_OMIT_FLOATING_POINT
60879 /* Opcode: Real * P2 * P4 *
60880 **
60881 ** P4 is a pointer to a 64-bit floating point value.
60882 ** Write that value into register P2.
60883 */
60884 case OP_Real: {            /* same as TK_FLOAT, out2-prerelease */
60885   pOut->flags = MEM_Real;
60886   assert( !sqlite3IsNaN(*pOp->p4.pReal) );
60887   pOut->r = *pOp->p4.pReal;
60888   break;
60889 }
60890 #endif
60891
60892 /* Opcode: String8 * P2 * P4 *
60893 **
60894 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed 
60895 ** into an OP_String before it is executed for the first time.
60896 */
60897 case OP_String8: {         /* same as TK_STRING, out2-prerelease */
60898   assert( pOp->p4.z!=0 );
60899   pOp->opcode = OP_String;
60900   pOp->p1 = sqlite3Strlen30(pOp->p4.z);
60901
60902 #ifndef SQLITE_OMIT_UTF16
60903   if( encoding!=SQLITE_UTF8 ){
60904     rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
60905     if( rc==SQLITE_TOOBIG ) goto too_big;
60906     if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
60907     assert( pOut->zMalloc==pOut->z );
60908     assert( pOut->flags & MEM_Dyn );
60909     pOut->zMalloc = 0;
60910     pOut->flags |= MEM_Static;
60911     pOut->flags &= ~MEM_Dyn;
60912     if( pOp->p4type==P4_DYNAMIC ){
60913       sqlite3DbFree(db, pOp->p4.z);
60914     }
60915     pOp->p4type = P4_DYNAMIC;
60916     pOp->p4.z = pOut->z;
60917     pOp->p1 = pOut->n;
60918   }
60919 #endif
60920   if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
60921     goto too_big;
60922   }
60923   /* Fall through to the next case, OP_String */
60924 }
60925   
60926 /* Opcode: String P1 P2 * P4 *
60927 **
60928 ** The string value P4 of length P1 (bytes) is stored in register P2.
60929 */
60930 case OP_String: {          /* out2-prerelease */
60931   assert( pOp->p4.z!=0 );
60932   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
60933   pOut->z = pOp->p4.z;
60934   pOut->n = pOp->p1;
60935   pOut->enc = encoding;
60936   UPDATE_MAX_BLOBSIZE(pOut);
60937   break;
60938 }
60939
60940 /* Opcode: Null * P2 * * *
60941 **
60942 ** Write a NULL into register P2.
60943 */
60944 case OP_Null: {           /* out2-prerelease */
60945   pOut->flags = MEM_Null;
60946   break;
60947 }
60948
60949
60950 /* Opcode: Blob P1 P2 * P4
60951 **
60952 ** P4 points to a blob of data P1 bytes long.  Store this
60953 ** blob in register P2.
60954 */
60955 case OP_Blob: {                /* out2-prerelease */
60956   assert( pOp->p1 <= SQLITE_MAX_LENGTH );
60957   sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
60958   pOut->enc = encoding;
60959   UPDATE_MAX_BLOBSIZE(pOut);
60960   break;
60961 }
60962
60963 /* Opcode: Variable P1 P2 * P4 *
60964 **
60965 ** Transfer the values of bound parameter P1 into register P2
60966 **
60967 ** If the parameter is named, then its name appears in P4 and P3==1.
60968 ** The P4 value is used by sqlite3_bind_parameter_name().
60969 */
60970 case OP_Variable: {            /* out2-prerelease */
60971 #if 0  /* local variables moved into u.ab */
60972   Mem *pVar;       /* Value being transferred */
60973 #endif /* local variables moved into u.ab */
60974
60975   assert( pOp->p1>0 && pOp->p1<=p->nVar );
60976   u.ab.pVar = &p->aVar[pOp->p1 - 1];
60977   if( sqlite3VdbeMemTooBig(u.ab.pVar) ){
60978     goto too_big;
60979   }
60980   sqlite3VdbeMemShallowCopy(pOut, u.ab.pVar, MEM_Static);
60981   UPDATE_MAX_BLOBSIZE(pOut);
60982   break;
60983 }
60984
60985 /* Opcode: Move P1 P2 P3 * *
60986 **
60987 ** Move the values in register P1..P1+P3-1 over into
60988 ** registers P2..P2+P3-1.  Registers P1..P1+P1-1 are
60989 ** left holding a NULL.  It is an error for register ranges
60990 ** P1..P1+P3-1 and P2..P2+P3-1 to overlap.
60991 */
60992 case OP_Move: {
60993 #if 0  /* local variables moved into u.ac */
60994   char *zMalloc;   /* Holding variable for allocated memory */
60995   int n;           /* Number of registers left to copy */
60996   int p1;          /* Register to copy from */
60997   int p2;          /* Register to copy to */
60998 #endif /* local variables moved into u.ac */
60999
61000   u.ac.n = pOp->p3;
61001   u.ac.p1 = pOp->p1;
61002   u.ac.p2 = pOp->p2;
61003   assert( u.ac.n>0 && u.ac.p1>0 && u.ac.p2>0 );
61004   assert( u.ac.p1+u.ac.n<=u.ac.p2 || u.ac.p2+u.ac.n<=u.ac.p1 );
61005
61006   pIn1 = &aMem[u.ac.p1];
61007   pOut = &aMem[u.ac.p2];
61008   while( u.ac.n-- ){
61009     assert( pOut<=&aMem[p->nMem] );
61010     assert( pIn1<=&aMem[p->nMem] );
61011     assert( memIsValid(pIn1) );
61012     memAboutToChange(p, pOut);
61013     u.ac.zMalloc = pOut->zMalloc;
61014     pOut->zMalloc = 0;
61015     sqlite3VdbeMemMove(pOut, pIn1);
61016     pIn1->zMalloc = u.ac.zMalloc;
61017     REGISTER_TRACE(u.ac.p2++, pOut);
61018     pIn1++;
61019     pOut++;
61020   }
61021   break;
61022 }
61023
61024 /* Opcode: Copy P1 P2 * * *
61025 **
61026 ** Make a copy of register P1 into register P2.
61027 **
61028 ** This instruction makes a deep copy of the value.  A duplicate
61029 ** is made of any string or blob constant.  See also OP_SCopy.
61030 */
61031 case OP_Copy: {             /* in1, out2 */
61032   pIn1 = &aMem[pOp->p1];
61033   pOut = &aMem[pOp->p2];
61034   assert( pOut!=pIn1 );
61035   sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
61036   Deephemeralize(pOut);
61037   REGISTER_TRACE(pOp->p2, pOut);
61038   break;
61039 }
61040
61041 /* Opcode: SCopy P1 P2 * * *
61042 **
61043 ** Make a shallow copy of register P1 into register P2.
61044 **
61045 ** This instruction makes a shallow copy of the value.  If the value
61046 ** is a string or blob, then the copy is only a pointer to the
61047 ** original and hence if the original changes so will the copy.
61048 ** Worse, if the original is deallocated, the copy becomes invalid.
61049 ** Thus the program must guarantee that the original will not change
61050 ** during the lifetime of the copy.  Use OP_Copy to make a complete
61051 ** copy.
61052 */
61053 case OP_SCopy: {            /* in1, out2 */
61054   pIn1 = &aMem[pOp->p1];
61055   pOut = &aMem[pOp->p2];
61056   assert( pOut!=pIn1 );
61057   sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
61058 #ifdef SQLITE_DEBUG
61059   if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
61060 #endif
61061   REGISTER_TRACE(pOp->p2, pOut);
61062   break;
61063 }
61064
61065 /* Opcode: ResultRow P1 P2 * * *
61066 **
61067 ** The registers P1 through P1+P2-1 contain a single row of
61068 ** results. This opcode causes the sqlite3_step() call to terminate
61069 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
61070 ** structure to provide access to the top P1 values as the result
61071 ** row.
61072 */
61073 case OP_ResultRow: {
61074 #if 0  /* local variables moved into u.ad */
61075   Mem *pMem;
61076   int i;
61077 #endif /* local variables moved into u.ad */
61078   assert( p->nResColumn==pOp->p2 );
61079   assert( pOp->p1>0 );
61080   assert( pOp->p1+pOp->p2<=p->nMem+1 );
61081
61082   /* If this statement has violated immediate foreign key constraints, do
61083   ** not return the number of rows modified. And do not RELEASE the statement
61084   ** transaction. It needs to be rolled back.  */
61085   if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
61086     assert( db->flags&SQLITE_CountRows );
61087     assert( p->usesStmtJournal );
61088     break;
61089   }
61090
61091   /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
61092   ** DML statements invoke this opcode to return the number of rows
61093   ** modified to the user. This is the only way that a VM that
61094   ** opens a statement transaction may invoke this opcode.
61095   **
61096   ** In case this is such a statement, close any statement transaction
61097   ** opened by this VM before returning control to the user. This is to
61098   ** ensure that statement-transactions are always nested, not overlapping.
61099   ** If the open statement-transaction is not closed here, then the user
61100   ** may step another VM that opens its own statement transaction. This
61101   ** may lead to overlapping statement transactions.
61102   **
61103   ** The statement transaction is never a top-level transaction.  Hence
61104   ** the RELEASE call below can never fail.
61105   */
61106   assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
61107   rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
61108   if( NEVER(rc!=SQLITE_OK) ){
61109     break;
61110   }
61111
61112   /* Invalidate all ephemeral cursor row caches */
61113   p->cacheCtr = (p->cacheCtr + 2)|1;
61114
61115   /* Make sure the results of the current row are \000 terminated
61116   ** and have an assigned type.  The results are de-ephemeralized as
61117   ** as side effect.
61118   */
61119   u.ad.pMem = p->pResultSet = &aMem[pOp->p1];
61120   for(u.ad.i=0; u.ad.i<pOp->p2; u.ad.i++){
61121     assert( memIsValid(&u.ad.pMem[u.ad.i]) );
61122     Deephemeralize(&u.ad.pMem[u.ad.i]);
61123     assert( (u.ad.pMem[u.ad.i].flags & MEM_Ephem)==0
61124             || (u.ad.pMem[u.ad.i].flags & (MEM_Str|MEM_Blob))==0 );
61125     sqlite3VdbeMemNulTerminate(&u.ad.pMem[u.ad.i]);
61126     sqlite3VdbeMemStoreType(&u.ad.pMem[u.ad.i]);
61127     REGISTER_TRACE(pOp->p1+u.ad.i, &u.ad.pMem[u.ad.i]);
61128   }
61129   if( db->mallocFailed ) goto no_mem;
61130
61131   /* Return SQLITE_ROW
61132   */
61133   p->pc = pc + 1;
61134   rc = SQLITE_ROW;
61135   goto vdbe_return;
61136 }
61137
61138 /* Opcode: Concat P1 P2 P3 * *
61139 **
61140 ** Add the text in register P1 onto the end of the text in
61141 ** register P2 and store the result in register P3.
61142 ** If either the P1 or P2 text are NULL then store NULL in P3.
61143 **
61144 **   P3 = P2 || P1
61145 **
61146 ** It is illegal for P1 and P3 to be the same register. Sometimes,
61147 ** if P3 is the same register as P2, the implementation is able
61148 ** to avoid a memcpy().
61149 */
61150 case OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */
61151 #if 0  /* local variables moved into u.ae */
61152   i64 nByte;
61153 #endif /* local variables moved into u.ae */
61154
61155   pIn1 = &aMem[pOp->p1];
61156   pIn2 = &aMem[pOp->p2];
61157   pOut = &aMem[pOp->p3];
61158   assert( pIn1!=pOut );
61159   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
61160     sqlite3VdbeMemSetNull(pOut);
61161     break;
61162   }
61163   if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
61164   Stringify(pIn1, encoding);
61165   Stringify(pIn2, encoding);
61166   u.ae.nByte = pIn1->n + pIn2->n;
61167   if( u.ae.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
61168     goto too_big;
61169   }
61170   MemSetTypeFlag(pOut, MEM_Str);
61171   if( sqlite3VdbeMemGrow(pOut, (int)u.ae.nByte+2, pOut==pIn2) ){
61172     goto no_mem;
61173   }
61174   if( pOut!=pIn2 ){
61175     memcpy(pOut->z, pIn2->z, pIn2->n);
61176   }
61177   memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
61178   pOut->z[u.ae.nByte] = 0;
61179   pOut->z[u.ae.nByte+1] = 0;
61180   pOut->flags |= MEM_Term;
61181   pOut->n = (int)u.ae.nByte;
61182   pOut->enc = encoding;
61183   UPDATE_MAX_BLOBSIZE(pOut);
61184   break;
61185 }
61186
61187 /* Opcode: Add P1 P2 P3 * *
61188 **
61189 ** Add the value in register P1 to the value in register P2
61190 ** and store the result in register P3.
61191 ** If either input is NULL, the result is NULL.
61192 */
61193 /* Opcode: Multiply P1 P2 P3 * *
61194 **
61195 **
61196 ** Multiply the value in register P1 by the value in register P2
61197 ** and store the result in register P3.
61198 ** If either input is NULL, the result is NULL.
61199 */
61200 /* Opcode: Subtract P1 P2 P3 * *
61201 **
61202 ** Subtract the value in register P1 from the value in register P2
61203 ** and store the result in register P3.
61204 ** If either input is NULL, the result is NULL.
61205 */
61206 /* Opcode: Divide P1 P2 P3 * *
61207 **
61208 ** Divide the value in register P1 by the value in register P2
61209 ** and store the result in register P3 (P3=P2/P1). If the value in 
61210 ** register P1 is zero, then the result is NULL. If either input is 
61211 ** NULL, the result is NULL.
61212 */
61213 /* Opcode: Remainder P1 P2 P3 * *
61214 **
61215 ** Compute the remainder after integer division of the value in
61216 ** register P1 by the value in register P2 and store the result in P3. 
61217 ** If the value in register P2 is zero the result is NULL.
61218 ** If either operand is NULL, the result is NULL.
61219 */
61220 case OP_Add:                   /* same as TK_PLUS, in1, in2, out3 */
61221 case OP_Subtract:              /* same as TK_MINUS, in1, in2, out3 */
61222 case OP_Multiply:              /* same as TK_STAR, in1, in2, out3 */
61223 case OP_Divide:                /* same as TK_SLASH, in1, in2, out3 */
61224 case OP_Remainder: {           /* same as TK_REM, in1, in2, out3 */
61225 #if 0  /* local variables moved into u.af */
61226   int flags;      /* Combined MEM_* flags from both inputs */
61227   i64 iA;         /* Integer value of left operand */
61228   i64 iB;         /* Integer value of right operand */
61229   double rA;      /* Real value of left operand */
61230   double rB;      /* Real value of right operand */
61231 #endif /* local variables moved into u.af */
61232
61233   pIn1 = &aMem[pOp->p1];
61234   applyNumericAffinity(pIn1);
61235   pIn2 = &aMem[pOp->p2];
61236   applyNumericAffinity(pIn2);
61237   pOut = &aMem[pOp->p3];
61238   u.af.flags = pIn1->flags | pIn2->flags;
61239   if( (u.af.flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
61240   if( (pIn1->flags & pIn2->flags & MEM_Int)==MEM_Int ){
61241     u.af.iA = pIn1->u.i;
61242     u.af.iB = pIn2->u.i;
61243     switch( pOp->opcode ){
61244       case OP_Add:         u.af.iB += u.af.iA;       break;
61245       case OP_Subtract:    u.af.iB -= u.af.iA;       break;
61246       case OP_Multiply:    u.af.iB *= u.af.iA;       break;
61247       case OP_Divide: {
61248         if( u.af.iA==0 ) goto arithmetic_result_is_null;
61249         /* Dividing the largest possible negative 64-bit integer (1<<63) by
61250         ** -1 returns an integer too large to store in a 64-bit data-type. On
61251         ** some architectures, the value overflows to (1<<63). On others,
61252         ** a SIGFPE is issued. The following statement normalizes this
61253         ** behavior so that all architectures behave as if integer
61254         ** overflow occurred.
61255         */
61256         if( u.af.iA==-1 && u.af.iB==SMALLEST_INT64 ) u.af.iA = 1;
61257         u.af.iB /= u.af.iA;
61258         break;
61259       }
61260       default: {
61261         if( u.af.iA==0 ) goto arithmetic_result_is_null;
61262         if( u.af.iA==-1 ) u.af.iA = 1;
61263         u.af.iB %= u.af.iA;
61264         break;
61265       }
61266     }
61267     pOut->u.i = u.af.iB;
61268     MemSetTypeFlag(pOut, MEM_Int);
61269   }else{
61270     u.af.rA = sqlite3VdbeRealValue(pIn1);
61271     u.af.rB = sqlite3VdbeRealValue(pIn2);
61272     switch( pOp->opcode ){
61273       case OP_Add:         u.af.rB += u.af.rA;       break;
61274       case OP_Subtract:    u.af.rB -= u.af.rA;       break;
61275       case OP_Multiply:    u.af.rB *= u.af.rA;       break;
61276       case OP_Divide: {
61277         /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
61278         if( u.af.rA==(double)0 ) goto arithmetic_result_is_null;
61279         u.af.rB /= u.af.rA;
61280         break;
61281       }
61282       default: {
61283         u.af.iA = (i64)u.af.rA;
61284         u.af.iB = (i64)u.af.rB;
61285         if( u.af.iA==0 ) goto arithmetic_result_is_null;
61286         if( u.af.iA==-1 ) u.af.iA = 1;
61287         u.af.rB = (double)(u.af.iB % u.af.iA);
61288         break;
61289       }
61290     }
61291 #ifdef SQLITE_OMIT_FLOATING_POINT
61292     pOut->u.i = u.af.rB;
61293     MemSetTypeFlag(pOut, MEM_Int);
61294 #else
61295     if( sqlite3IsNaN(u.af.rB) ){
61296       goto arithmetic_result_is_null;
61297     }
61298     pOut->r = u.af.rB;
61299     MemSetTypeFlag(pOut, MEM_Real);
61300     if( (u.af.flags & MEM_Real)==0 ){
61301       sqlite3VdbeIntegerAffinity(pOut);
61302     }
61303 #endif
61304   }
61305   break;
61306
61307 arithmetic_result_is_null:
61308   sqlite3VdbeMemSetNull(pOut);
61309   break;
61310 }
61311
61312 /* Opcode: CollSeq * * P4
61313 **
61314 ** P4 is a pointer to a CollSeq struct. If the next call to a user function
61315 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
61316 ** be returned. This is used by the built-in min(), max() and nullif()
61317 ** functions.
61318 **
61319 ** The interface used by the implementation of the aforementioned functions
61320 ** to retrieve the collation sequence set by this opcode is not available
61321 ** publicly, only to user functions defined in func.c.
61322 */
61323 case OP_CollSeq: {
61324   assert( pOp->p4type==P4_COLLSEQ );
61325   break;
61326 }
61327
61328 /* Opcode: Function P1 P2 P3 P4 P5
61329 **
61330 ** Invoke a user function (P4 is a pointer to a Function structure that
61331 ** defines the function) with P5 arguments taken from register P2 and
61332 ** successors.  The result of the function is stored in register P3.
61333 ** Register P3 must not be one of the function inputs.
61334 **
61335 ** P1 is a 32-bit bitmask indicating whether or not each argument to the 
61336 ** function was determined to be constant at compile time. If the first
61337 ** argument was constant then bit 0 of P1 is set. This is used to determine
61338 ** whether meta data associated with a user function argument using the
61339 ** sqlite3_set_auxdata() API may be safely retained until the next
61340 ** invocation of this opcode.
61341 **
61342 ** See also: AggStep and AggFinal
61343 */
61344 case OP_Function: {
61345 #if 0  /* local variables moved into u.ag */
61346   int i;
61347   Mem *pArg;
61348   sqlite3_context ctx;
61349   sqlite3_value **apVal;
61350   int n;
61351 #endif /* local variables moved into u.ag */
61352
61353   u.ag.n = pOp->p5;
61354   u.ag.apVal = p->apArg;
61355   assert( u.ag.apVal || u.ag.n==0 );
61356   assert( pOp->p3>0 && pOp->p3<=p->nMem );
61357   pOut = &aMem[pOp->p3];
61358   memAboutToChange(p, pOut);
61359
61360   assert( u.ag.n==0 || (pOp->p2>0 && pOp->p2+u.ag.n<=p->nMem+1) );
61361   assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+u.ag.n );
61362   u.ag.pArg = &aMem[pOp->p2];
61363   for(u.ag.i=0; u.ag.i<u.ag.n; u.ag.i++, u.ag.pArg++){
61364     assert( memIsValid(u.ag.pArg) );
61365     u.ag.apVal[u.ag.i] = u.ag.pArg;
61366     Deephemeralize(u.ag.pArg);
61367     sqlite3VdbeMemStoreType(u.ag.pArg);
61368     REGISTER_TRACE(pOp->p2+u.ag.i, u.ag.pArg);
61369   }
61370
61371   assert( pOp->p4type==P4_FUNCDEF || pOp->p4type==P4_VDBEFUNC );
61372   if( pOp->p4type==P4_FUNCDEF ){
61373     u.ag.ctx.pFunc = pOp->p4.pFunc;
61374     u.ag.ctx.pVdbeFunc = 0;
61375   }else{
61376     u.ag.ctx.pVdbeFunc = (VdbeFunc*)pOp->p4.pVdbeFunc;
61377     u.ag.ctx.pFunc = u.ag.ctx.pVdbeFunc->pFunc;
61378   }
61379
61380   u.ag.ctx.s.flags = MEM_Null;
61381   u.ag.ctx.s.db = db;
61382   u.ag.ctx.s.xDel = 0;
61383   u.ag.ctx.s.zMalloc = 0;
61384
61385   /* The output cell may already have a buffer allocated. Move
61386   ** the pointer to u.ag.ctx.s so in case the user-function can use
61387   ** the already allocated buffer instead of allocating a new one.
61388   */
61389   sqlite3VdbeMemMove(&u.ag.ctx.s, pOut);
61390   MemSetTypeFlag(&u.ag.ctx.s, MEM_Null);
61391
61392   u.ag.ctx.isError = 0;
61393   if( u.ag.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
61394     assert( pOp>aOp );
61395     assert( pOp[-1].p4type==P4_COLLSEQ );
61396     assert( pOp[-1].opcode==OP_CollSeq );
61397     u.ag.ctx.pColl = pOp[-1].p4.pColl;
61398   }
61399   (*u.ag.ctx.pFunc->xFunc)(&u.ag.ctx, u.ag.n, u.ag.apVal); /* IMP: R-24505-23230 */
61400   if( db->mallocFailed ){
61401     /* Even though a malloc() has failed, the implementation of the
61402     ** user function may have called an sqlite3_result_XXX() function
61403     ** to return a value. The following call releases any resources
61404     ** associated with such a value.
61405     */
61406     sqlite3VdbeMemRelease(&u.ag.ctx.s);
61407     goto no_mem;
61408   }
61409
61410   /* If any auxiliary data functions have been called by this user function,
61411   ** immediately call the destructor for any non-static values.
61412   */
61413   if( u.ag.ctx.pVdbeFunc ){
61414     sqlite3VdbeDeleteAuxData(u.ag.ctx.pVdbeFunc, pOp->p1);
61415     pOp->p4.pVdbeFunc = u.ag.ctx.pVdbeFunc;
61416     pOp->p4type = P4_VDBEFUNC;
61417   }
61418
61419   /* If the function returned an error, throw an exception */
61420   if( u.ag.ctx.isError ){
61421     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.ag.ctx.s));
61422     rc = u.ag.ctx.isError;
61423   }
61424
61425   /* Copy the result of the function into register P3 */
61426   sqlite3VdbeChangeEncoding(&u.ag.ctx.s, encoding);
61427   sqlite3VdbeMemMove(pOut, &u.ag.ctx.s);
61428   if( sqlite3VdbeMemTooBig(pOut) ){
61429     goto too_big;
61430   }
61431   REGISTER_TRACE(pOp->p3, pOut);
61432   UPDATE_MAX_BLOBSIZE(pOut);
61433   break;
61434 }
61435
61436 /* Opcode: BitAnd P1 P2 P3 * *
61437 **
61438 ** Take the bit-wise AND of the values in register P1 and P2 and
61439 ** store the result in register P3.
61440 ** If either input is NULL, the result is NULL.
61441 */
61442 /* Opcode: BitOr P1 P2 P3 * *
61443 **
61444 ** Take the bit-wise OR of the values in register P1 and P2 and
61445 ** store the result in register P3.
61446 ** If either input is NULL, the result is NULL.
61447 */
61448 /* Opcode: ShiftLeft P1 P2 P3 * *
61449 **
61450 ** Shift the integer value in register P2 to the left by the
61451 ** number of bits specified by the integer in register P1.
61452 ** Store the result in register P3.
61453 ** If either input is NULL, the result is NULL.
61454 */
61455 /* Opcode: ShiftRight P1 P2 P3 * *
61456 **
61457 ** Shift the integer value in register P2 to the right by the
61458 ** number of bits specified by the integer in register P1.
61459 ** Store the result in register P3.
61460 ** If either input is NULL, the result is NULL.
61461 */
61462 case OP_BitAnd:                 /* same as TK_BITAND, in1, in2, out3 */
61463 case OP_BitOr:                  /* same as TK_BITOR, in1, in2, out3 */
61464 case OP_ShiftLeft:              /* same as TK_LSHIFT, in1, in2, out3 */
61465 case OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */
61466 #if 0  /* local variables moved into u.ah */
61467   i64 a;
61468   i64 b;
61469 #endif /* local variables moved into u.ah */
61470
61471   pIn1 = &aMem[pOp->p1];
61472   pIn2 = &aMem[pOp->p2];
61473   pOut = &aMem[pOp->p3];
61474   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
61475     sqlite3VdbeMemSetNull(pOut);
61476     break;
61477   }
61478   u.ah.a = sqlite3VdbeIntValue(pIn2);
61479   u.ah.b = sqlite3VdbeIntValue(pIn1);
61480   switch( pOp->opcode ){
61481     case OP_BitAnd:      u.ah.a &= u.ah.b;     break;
61482     case OP_BitOr:       u.ah.a |= u.ah.b;     break;
61483     case OP_ShiftLeft:   u.ah.a <<= u.ah.b;    break;
61484     default:  assert( pOp->opcode==OP_ShiftRight );
61485                          u.ah.a >>= u.ah.b;    break;
61486   }
61487   pOut->u.i = u.ah.a;
61488   MemSetTypeFlag(pOut, MEM_Int);
61489   break;
61490 }
61491
61492 /* Opcode: AddImm  P1 P2 * * *
61493 ** 
61494 ** Add the constant P2 to the value in register P1.
61495 ** The result is always an integer.
61496 **
61497 ** To force any register to be an integer, just add 0.
61498 */
61499 case OP_AddImm: {            /* in1 */
61500   pIn1 = &aMem[pOp->p1];
61501   memAboutToChange(p, pIn1);
61502   sqlite3VdbeMemIntegerify(pIn1);
61503   pIn1->u.i += pOp->p2;
61504   break;
61505 }
61506
61507 /* Opcode: MustBeInt P1 P2 * * *
61508 ** 
61509 ** Force the value in register P1 to be an integer.  If the value
61510 ** in P1 is not an integer and cannot be converted into an integer
61511 ** without data loss, then jump immediately to P2, or if P2==0
61512 ** raise an SQLITE_MISMATCH exception.
61513 */
61514 case OP_MustBeInt: {            /* jump, in1 */
61515   pIn1 = &aMem[pOp->p1];
61516   memAboutToChange(p, pIn1);
61517   applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
61518   if( (pIn1->flags & MEM_Int)==0 ){
61519     if( pOp->p2==0 ){
61520       rc = SQLITE_MISMATCH;
61521       goto abort_due_to_error;
61522     }else{
61523       pc = pOp->p2 - 1;
61524     }
61525   }else{
61526     MemSetTypeFlag(pIn1, MEM_Int);
61527   }
61528   break;
61529 }
61530
61531 #ifndef SQLITE_OMIT_FLOATING_POINT
61532 /* Opcode: RealAffinity P1 * * * *
61533 **
61534 ** If register P1 holds an integer convert it to a real value.
61535 **
61536 ** This opcode is used when extracting information from a column that
61537 ** has REAL affinity.  Such column values may still be stored as
61538 ** integers, for space efficiency, but after extraction we want them
61539 ** to have only a real value.
61540 */
61541 case OP_RealAffinity: {                  /* in1 */
61542   pIn1 = &aMem[pOp->p1];
61543   if( pIn1->flags & MEM_Int ){
61544     sqlite3VdbeMemRealify(pIn1);
61545   }
61546   break;
61547 }
61548 #endif
61549
61550 #ifndef SQLITE_OMIT_CAST
61551 /* Opcode: ToText P1 * * * *
61552 **
61553 ** Force the value in register P1 to be text.
61554 ** If the value is numeric, convert it to a string using the
61555 ** equivalent of printf().  Blob values are unchanged and
61556 ** are afterwards simply interpreted as text.
61557 **
61558 ** A NULL value is not changed by this routine.  It remains NULL.
61559 */
61560 case OP_ToText: {                  /* same as TK_TO_TEXT, in1 */
61561   pIn1 = &aMem[pOp->p1];
61562   memAboutToChange(p, pIn1);
61563   if( pIn1->flags & MEM_Null ) break;
61564   assert( MEM_Str==(MEM_Blob>>3) );
61565   pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
61566   applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
61567   rc = ExpandBlob(pIn1);
61568   assert( pIn1->flags & MEM_Str || db->mallocFailed );
61569   pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
61570   UPDATE_MAX_BLOBSIZE(pIn1);
61571   break;
61572 }
61573
61574 /* Opcode: ToBlob P1 * * * *
61575 **
61576 ** Force the value in register P1 to be a BLOB.
61577 ** If the value is numeric, convert it to a string first.
61578 ** Strings are simply reinterpreted as blobs with no change
61579 ** to the underlying data.
61580 **
61581 ** A NULL value is not changed by this routine.  It remains NULL.
61582 */
61583 case OP_ToBlob: {                  /* same as TK_TO_BLOB, in1 */
61584   pIn1 = &aMem[pOp->p1];
61585   if( pIn1->flags & MEM_Null ) break;
61586   if( (pIn1->flags & MEM_Blob)==0 ){
61587     applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
61588     assert( pIn1->flags & MEM_Str || db->mallocFailed );
61589     MemSetTypeFlag(pIn1, MEM_Blob);
61590   }else{
61591     pIn1->flags &= ~(MEM_TypeMask&~MEM_Blob);
61592   }
61593   UPDATE_MAX_BLOBSIZE(pIn1);
61594   break;
61595 }
61596
61597 /* Opcode: ToNumeric P1 * * * *
61598 **
61599 ** Force the value in register P1 to be numeric (either an
61600 ** integer or a floating-point number.)
61601 ** If the value is text or blob, try to convert it to an using the
61602 ** equivalent of atoi() or atof() and store 0 if no such conversion 
61603 ** is possible.
61604 **
61605 ** A NULL value is not changed by this routine.  It remains NULL.
61606 */
61607 case OP_ToNumeric: {                  /* same as TK_TO_NUMERIC, in1 */
61608   pIn1 = &aMem[pOp->p1];
61609   sqlite3VdbeMemNumerify(pIn1);
61610   break;
61611 }
61612 #endif /* SQLITE_OMIT_CAST */
61613
61614 /* Opcode: ToInt P1 * * * *
61615 **
61616 ** Force the value in register P1 to be an integer.  If
61617 ** The value is currently a real number, drop its fractional part.
61618 ** If the value is text or blob, try to convert it to an integer using the
61619 ** equivalent of atoi() and store 0 if no such conversion is possible.
61620 **
61621 ** A NULL value is not changed by this routine.  It remains NULL.
61622 */
61623 case OP_ToInt: {                  /* same as TK_TO_INT, in1 */
61624   pIn1 = &aMem[pOp->p1];
61625   if( (pIn1->flags & MEM_Null)==0 ){
61626     sqlite3VdbeMemIntegerify(pIn1);
61627   }
61628   break;
61629 }
61630
61631 #if !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT)
61632 /* Opcode: ToReal P1 * * * *
61633 **
61634 ** Force the value in register P1 to be a floating point number.
61635 ** If The value is currently an integer, convert it.
61636 ** If the value is text or blob, try to convert it to an integer using the
61637 ** equivalent of atoi() and store 0.0 if no such conversion is possible.
61638 **
61639 ** A NULL value is not changed by this routine.  It remains NULL.
61640 */
61641 case OP_ToReal: {                  /* same as TK_TO_REAL, in1 */
61642   pIn1 = &aMem[pOp->p1];
61643   memAboutToChange(p, pIn1);
61644   if( (pIn1->flags & MEM_Null)==0 ){
61645     sqlite3VdbeMemRealify(pIn1);
61646   }
61647   break;
61648 }
61649 #endif /* !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT) */
61650
61651 /* Opcode: Lt P1 P2 P3 P4 P5
61652 **
61653 ** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then
61654 ** jump to address P2.  
61655 **
61656 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
61657 ** reg(P3) is NULL then take the jump.  If the SQLITE_JUMPIFNULL 
61658 ** bit is clear then fall through if either operand is NULL.
61659 **
61660 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
61661 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made 
61662 ** to coerce both inputs according to this affinity before the
61663 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
61664 ** affinity is used. Note that the affinity conversions are stored
61665 ** back into the input registers P1 and P3.  So this opcode can cause
61666 ** persistent changes to registers P1 and P3.
61667 **
61668 ** Once any conversions have taken place, and neither value is NULL, 
61669 ** the values are compared. If both values are blobs then memcmp() is
61670 ** used to determine the results of the comparison.  If both values
61671 ** are text, then the appropriate collating function specified in
61672 ** P4 is  used to do the comparison.  If P4 is not specified then
61673 ** memcmp() is used to compare text string.  If both values are
61674 ** numeric, then a numeric comparison is used. If the two values
61675 ** are of different types, then numbers are considered less than
61676 ** strings and strings are considered less than blobs.
61677 **
61678 ** If the SQLITE_STOREP2 bit of P5 is set, then do not jump.  Instead,
61679 ** store a boolean result (either 0, or 1, or NULL) in register P2.
61680 */
61681 /* Opcode: Ne P1 P2 P3 P4 P5
61682 **
61683 ** This works just like the Lt opcode except that the jump is taken if
61684 ** the operands in registers P1 and P3 are not equal.  See the Lt opcode for
61685 ** additional information.
61686 **
61687 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
61688 ** true or false and is never NULL.  If both operands are NULL then the result
61689 ** of comparison is false.  If either operand is NULL then the result is true.
61690 ** If neither operand is NULL the the result is the same as it would be if
61691 ** the SQLITE_NULLEQ flag were omitted from P5.
61692 */
61693 /* Opcode: Eq P1 P2 P3 P4 P5
61694 **
61695 ** This works just like the Lt opcode except that the jump is taken if
61696 ** the operands in registers P1 and P3 are equal.
61697 ** See the Lt opcode for additional information.
61698 **
61699 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
61700 ** true or false and is never NULL.  If both operands are NULL then the result
61701 ** of comparison is true.  If either operand is NULL then the result is false.
61702 ** If neither operand is NULL the the result is the same as it would be if
61703 ** the SQLITE_NULLEQ flag were omitted from P5.
61704 */
61705 /* Opcode: Le P1 P2 P3 P4 P5
61706 **
61707 ** This works just like the Lt opcode except that the jump is taken if
61708 ** the content of register P3 is less than or equal to the content of
61709 ** register P1.  See the Lt opcode for additional information.
61710 */
61711 /* Opcode: Gt P1 P2 P3 P4 P5
61712 **
61713 ** This works just like the Lt opcode except that the jump is taken if
61714 ** the content of register P3 is greater than the content of
61715 ** register P1.  See the Lt opcode for additional information.
61716 */
61717 /* Opcode: Ge P1 P2 P3 P4 P5
61718 **
61719 ** This works just like the Lt opcode except that the jump is taken if
61720 ** the content of register P3 is greater than or equal to the content of
61721 ** register P1.  See the Lt opcode for additional information.
61722 */
61723 case OP_Eq:               /* same as TK_EQ, jump, in1, in3 */
61724 case OP_Ne:               /* same as TK_NE, jump, in1, in3 */
61725 case OP_Lt:               /* same as TK_LT, jump, in1, in3 */
61726 case OP_Le:               /* same as TK_LE, jump, in1, in3 */
61727 case OP_Gt:               /* same as TK_GT, jump, in1, in3 */
61728 case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
61729 #if 0  /* local variables moved into u.ai */
61730   int res;            /* Result of the comparison of pIn1 against pIn3 */
61731   char affinity;      /* Affinity to use for comparison */
61732   u16 flags1;         /* Copy of initial value of pIn1->flags */
61733   u16 flags3;         /* Copy of initial value of pIn3->flags */
61734 #endif /* local variables moved into u.ai */
61735
61736   pIn1 = &aMem[pOp->p1];
61737   pIn3 = &aMem[pOp->p3];
61738   u.ai.flags1 = pIn1->flags;
61739   u.ai.flags3 = pIn3->flags;
61740   if( (pIn1->flags | pIn3->flags)&MEM_Null ){
61741     /* One or both operands are NULL */
61742     if( pOp->p5 & SQLITE_NULLEQ ){
61743       /* If SQLITE_NULLEQ is set (which will only happen if the operator is
61744       ** OP_Eq or OP_Ne) then take the jump or not depending on whether
61745       ** or not both operands are null.
61746       */
61747       assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
61748       u.ai.res = (pIn1->flags & pIn3->flags & MEM_Null)==0;
61749     }else{
61750       /* SQLITE_NULLEQ is clear and at least one operand is NULL,
61751       ** then the result is always NULL.
61752       ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
61753       */
61754       if( pOp->p5 & SQLITE_STOREP2 ){
61755         pOut = &aMem[pOp->p2];
61756         MemSetTypeFlag(pOut, MEM_Null);
61757         REGISTER_TRACE(pOp->p2, pOut);
61758       }else if( pOp->p5 & SQLITE_JUMPIFNULL ){
61759         pc = pOp->p2-1;
61760       }
61761       break;
61762     }
61763   }else{
61764     /* Neither operand is NULL.  Do a comparison. */
61765     u.ai.affinity = pOp->p5 & SQLITE_AFF_MASK;
61766     if( u.ai.affinity ){
61767       applyAffinity(pIn1, u.ai.affinity, encoding);
61768       applyAffinity(pIn3, u.ai.affinity, encoding);
61769       if( db->mallocFailed ) goto no_mem;
61770     }
61771
61772     assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
61773     ExpandBlob(pIn1);
61774     ExpandBlob(pIn3);
61775     u.ai.res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
61776   }
61777   switch( pOp->opcode ){
61778     case OP_Eq:    u.ai.res = u.ai.res==0;     break;
61779     case OP_Ne:    u.ai.res = u.ai.res!=0;     break;
61780     case OP_Lt:    u.ai.res = u.ai.res<0;      break;
61781     case OP_Le:    u.ai.res = u.ai.res<=0;     break;
61782     case OP_Gt:    u.ai.res = u.ai.res>0;      break;
61783     default:       u.ai.res = u.ai.res>=0;     break;
61784   }
61785
61786   if( pOp->p5 & SQLITE_STOREP2 ){
61787     pOut = &aMem[pOp->p2];
61788     memAboutToChange(p, pOut);
61789     MemSetTypeFlag(pOut, MEM_Int);
61790     pOut->u.i = u.ai.res;
61791     REGISTER_TRACE(pOp->p2, pOut);
61792   }else if( u.ai.res ){
61793     pc = pOp->p2-1;
61794   }
61795
61796   /* Undo any changes made by applyAffinity() to the input registers. */
61797   pIn1->flags = (pIn1->flags&~MEM_TypeMask) | (u.ai.flags1&MEM_TypeMask);
61798   pIn3->flags = (pIn3->flags&~MEM_TypeMask) | (u.ai.flags3&MEM_TypeMask);
61799   break;
61800 }
61801
61802 /* Opcode: Permutation * * * P4 *
61803 **
61804 ** Set the permutation used by the OP_Compare operator to be the array
61805 ** of integers in P4.
61806 **
61807 ** The permutation is only valid until the next OP_Permutation, OP_Compare,
61808 ** OP_Halt, or OP_ResultRow.  Typically the OP_Permutation should occur
61809 ** immediately prior to the OP_Compare.
61810 */
61811 case OP_Permutation: {
61812   assert( pOp->p4type==P4_INTARRAY );
61813   assert( pOp->p4.ai );
61814   aPermute = pOp->p4.ai;
61815   break;
61816 }
61817
61818 /* Opcode: Compare P1 P2 P3 P4 *
61819 **
61820 ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
61821 ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B").  Save the result of
61822 ** the comparison for use by the next OP_Jump instruct.
61823 **
61824 ** P4 is a KeyInfo structure that defines collating sequences and sort
61825 ** orders for the comparison.  The permutation applies to registers
61826 ** only.  The KeyInfo elements are used sequentially.
61827 **
61828 ** The comparison is a sort comparison, so NULLs compare equal,
61829 ** NULLs are less than numbers, numbers are less than strings,
61830 ** and strings are less than blobs.
61831 */
61832 case OP_Compare: {
61833 #if 0  /* local variables moved into u.aj */
61834   int n;
61835   int i;
61836   int p1;
61837   int p2;
61838   const KeyInfo *pKeyInfo;
61839   int idx;
61840   CollSeq *pColl;    /* Collating sequence to use on this term */
61841   int bRev;          /* True for DESCENDING sort order */
61842 #endif /* local variables moved into u.aj */
61843
61844   u.aj.n = pOp->p3;
61845   u.aj.pKeyInfo = pOp->p4.pKeyInfo;
61846   assert( u.aj.n>0 );
61847   assert( u.aj.pKeyInfo!=0 );
61848   u.aj.p1 = pOp->p1;
61849   u.aj.p2 = pOp->p2;
61850 #if SQLITE_DEBUG
61851   if( aPermute ){
61852     int k, mx = 0;
61853     for(k=0; k<u.aj.n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
61854     assert( u.aj.p1>0 && u.aj.p1+mx<=p->nMem+1 );
61855     assert( u.aj.p2>0 && u.aj.p2+mx<=p->nMem+1 );
61856   }else{
61857     assert( u.aj.p1>0 && u.aj.p1+u.aj.n<=p->nMem+1 );
61858     assert( u.aj.p2>0 && u.aj.p2+u.aj.n<=p->nMem+1 );
61859   }
61860 #endif /* SQLITE_DEBUG */
61861   for(u.aj.i=0; u.aj.i<u.aj.n; u.aj.i++){
61862     u.aj.idx = aPermute ? aPermute[u.aj.i] : u.aj.i;
61863     assert( memIsValid(&aMem[u.aj.p1+u.aj.idx]) );
61864     assert( memIsValid(&aMem[u.aj.p2+u.aj.idx]) );
61865     REGISTER_TRACE(u.aj.p1+u.aj.idx, &aMem[u.aj.p1+u.aj.idx]);
61866     REGISTER_TRACE(u.aj.p2+u.aj.idx, &aMem[u.aj.p2+u.aj.idx]);
61867     assert( u.aj.i<u.aj.pKeyInfo->nField );
61868     u.aj.pColl = u.aj.pKeyInfo->aColl[u.aj.i];
61869     u.aj.bRev = u.aj.pKeyInfo->aSortOrder[u.aj.i];
61870     iCompare = sqlite3MemCompare(&aMem[u.aj.p1+u.aj.idx], &aMem[u.aj.p2+u.aj.idx], u.aj.pColl);
61871     if( iCompare ){
61872       if( u.aj.bRev ) iCompare = -iCompare;
61873       break;
61874     }
61875   }
61876   aPermute = 0;
61877   break;
61878 }
61879
61880 /* Opcode: Jump P1 P2 P3 * *
61881 **
61882 ** Jump to the instruction at address P1, P2, or P3 depending on whether
61883 ** in the most recent OP_Compare instruction the P1 vector was less than
61884 ** equal to, or greater than the P2 vector, respectively.
61885 */
61886 case OP_Jump: {             /* jump */
61887   if( iCompare<0 ){
61888     pc = pOp->p1 - 1;
61889   }else if( iCompare==0 ){
61890     pc = pOp->p2 - 1;
61891   }else{
61892     pc = pOp->p3 - 1;
61893   }
61894   break;
61895 }
61896
61897 /* Opcode: And P1 P2 P3 * *
61898 **
61899 ** Take the logical AND of the values in registers P1 and P2 and
61900 ** write the result into register P3.
61901 **
61902 ** If either P1 or P2 is 0 (false) then the result is 0 even if
61903 ** the other input is NULL.  A NULL and true or two NULLs give
61904 ** a NULL output.
61905 */
61906 /* Opcode: Or P1 P2 P3 * *
61907 **
61908 ** Take the logical OR of the values in register P1 and P2 and
61909 ** store the answer in register P3.
61910 **
61911 ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
61912 ** even if the other input is NULL.  A NULL and false or two NULLs
61913 ** give a NULL output.
61914 */
61915 case OP_And:              /* same as TK_AND, in1, in2, out3 */
61916 case OP_Or: {             /* same as TK_OR, in1, in2, out3 */
61917 #if 0  /* local variables moved into u.ak */
61918   int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
61919   int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
61920 #endif /* local variables moved into u.ak */
61921
61922   pIn1 = &aMem[pOp->p1];
61923   if( pIn1->flags & MEM_Null ){
61924     u.ak.v1 = 2;
61925   }else{
61926     u.ak.v1 = sqlite3VdbeIntValue(pIn1)!=0;
61927   }
61928   pIn2 = &aMem[pOp->p2];
61929   if( pIn2->flags & MEM_Null ){
61930     u.ak.v2 = 2;
61931   }else{
61932     u.ak.v2 = sqlite3VdbeIntValue(pIn2)!=0;
61933   }
61934   if( pOp->opcode==OP_And ){
61935     static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
61936     u.ak.v1 = and_logic[u.ak.v1*3+u.ak.v2];
61937   }else{
61938     static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
61939     u.ak.v1 = or_logic[u.ak.v1*3+u.ak.v2];
61940   }
61941   pOut = &aMem[pOp->p3];
61942   if( u.ak.v1==2 ){
61943     MemSetTypeFlag(pOut, MEM_Null);
61944   }else{
61945     pOut->u.i = u.ak.v1;
61946     MemSetTypeFlag(pOut, MEM_Int);
61947   }
61948   break;
61949 }
61950
61951 /* Opcode: Not P1 P2 * * *
61952 **
61953 ** Interpret the value in register P1 as a boolean value.  Store the
61954 ** boolean complement in register P2.  If the value in register P1 is 
61955 ** NULL, then a NULL is stored in P2.
61956 */
61957 case OP_Not: {                /* same as TK_NOT, in1, out2 */
61958   pIn1 = &aMem[pOp->p1];
61959   pOut = &aMem[pOp->p2];
61960   if( pIn1->flags & MEM_Null ){
61961     sqlite3VdbeMemSetNull(pOut);
61962   }else{
61963     sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeIntValue(pIn1));
61964   }
61965   break;
61966 }
61967
61968 /* Opcode: BitNot P1 P2 * * *
61969 **
61970 ** Interpret the content of register P1 as an integer.  Store the
61971 ** ones-complement of the P1 value into register P2.  If P1 holds
61972 ** a NULL then store a NULL in P2.
61973 */
61974 case OP_BitNot: {             /* same as TK_BITNOT, in1, out2 */
61975   pIn1 = &aMem[pOp->p1];
61976   pOut = &aMem[pOp->p2];
61977   if( pIn1->flags & MEM_Null ){
61978     sqlite3VdbeMemSetNull(pOut);
61979   }else{
61980     sqlite3VdbeMemSetInt64(pOut, ~sqlite3VdbeIntValue(pIn1));
61981   }
61982   break;
61983 }
61984
61985 /* Opcode: If P1 P2 P3 * *
61986 **
61987 ** Jump to P2 if the value in register P1 is true.  The value is
61988 ** is considered true if it is numeric and non-zero.  If the value
61989 ** in P1 is NULL then take the jump if P3 is true.
61990 */
61991 /* Opcode: IfNot P1 P2 P3 * *
61992 **
61993 ** Jump to P2 if the value in register P1 is False.  The value is
61994 ** is considered true if it has a numeric value of zero.  If the value
61995 ** in P1 is NULL then take the jump if P3 is true.
61996 */
61997 case OP_If:                 /* jump, in1 */
61998 case OP_IfNot: {            /* jump, in1 */
61999 #if 0  /* local variables moved into u.al */
62000   int c;
62001 #endif /* local variables moved into u.al */
62002   pIn1 = &aMem[pOp->p1];
62003   if( pIn1->flags & MEM_Null ){
62004     u.al.c = pOp->p3;
62005   }else{
62006 #ifdef SQLITE_OMIT_FLOATING_POINT
62007     u.al.c = sqlite3VdbeIntValue(pIn1)!=0;
62008 #else
62009     u.al.c = sqlite3VdbeRealValue(pIn1)!=0.0;
62010 #endif
62011     if( pOp->opcode==OP_IfNot ) u.al.c = !u.al.c;
62012   }
62013   if( u.al.c ){
62014     pc = pOp->p2-1;
62015   }
62016   break;
62017 }
62018
62019 /* Opcode: IsNull P1 P2 * * *
62020 **
62021 ** Jump to P2 if the value in register P1 is NULL.
62022 */
62023 case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
62024   pIn1 = &aMem[pOp->p1];
62025   if( (pIn1->flags & MEM_Null)!=0 ){
62026     pc = pOp->p2 - 1;
62027   }
62028   break;
62029 }
62030
62031 /* Opcode: NotNull P1 P2 * * *
62032 **
62033 ** Jump to P2 if the value in register P1 is not NULL.  
62034 */
62035 case OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */
62036   pIn1 = &aMem[pOp->p1];
62037   if( (pIn1->flags & MEM_Null)==0 ){
62038     pc = pOp->p2 - 1;
62039   }
62040   break;
62041 }
62042
62043 /* Opcode: Column P1 P2 P3 P4 P5
62044 **
62045 ** Interpret the data that cursor P1 points to as a structure built using
62046 ** the MakeRecord instruction.  (See the MakeRecord opcode for additional
62047 ** information about the format of the data.)  Extract the P2-th column
62048 ** from this record.  If there are less that (P2+1) 
62049 ** values in the record, extract a NULL.
62050 **
62051 ** The value extracted is stored in register P3.
62052 **
62053 ** If the column contains fewer than P2 fields, then extract a NULL.  Or,
62054 ** if the P4 argument is a P4_MEM use the value of the P4 argument as
62055 ** the result.
62056 **
62057 ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
62058 ** then the cache of the cursor is reset prior to extracting the column.
62059 ** The first OP_Column against a pseudo-table after the value of the content
62060 ** register has changed should have this bit set.
62061 */
62062 case OP_Column: {
62063 #if 0  /* local variables moved into u.am */
62064   u32 payloadSize;   /* Number of bytes in the record */
62065   i64 payloadSize64; /* Number of bytes in the record */
62066   int p1;            /* P1 value of the opcode */
62067   int p2;            /* column number to retrieve */
62068   VdbeCursor *pC;    /* The VDBE cursor */
62069   char *zRec;        /* Pointer to complete record-data */
62070   BtCursor *pCrsr;   /* The BTree cursor */
62071   u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
62072   u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
62073   int nField;        /* number of fields in the record */
62074   int len;           /* The length of the serialized data for the column */
62075   int i;             /* Loop counter */
62076   char *zData;       /* Part of the record being decoded */
62077   Mem *pDest;        /* Where to write the extracted value */
62078   Mem sMem;          /* For storing the record being decoded */
62079   u8 *zIdx;          /* Index into header */
62080   u8 *zEndHdr;       /* Pointer to first byte after the header */
62081   u32 offset;        /* Offset into the data */
62082   u32 szField;       /* Number of bytes in the content of a field */
62083   int szHdr;         /* Size of the header size field at start of record */
62084   int avail;         /* Number of bytes of available data */
62085   Mem *pReg;         /* PseudoTable input register */
62086 #endif /* local variables moved into u.am */
62087
62088
62089   u.am.p1 = pOp->p1;
62090   u.am.p2 = pOp->p2;
62091   u.am.pC = 0;
62092   memset(&u.am.sMem, 0, sizeof(u.am.sMem));
62093   assert( u.am.p1<p->nCursor );
62094   assert( pOp->p3>0 && pOp->p3<=p->nMem );
62095   u.am.pDest = &aMem[pOp->p3];
62096   memAboutToChange(p, u.am.pDest);
62097   MemSetTypeFlag(u.am.pDest, MEM_Null);
62098   u.am.zRec = 0;
62099
62100   /* This block sets the variable u.am.payloadSize to be the total number of
62101   ** bytes in the record.
62102   **
62103   ** u.am.zRec is set to be the complete text of the record if it is available.
62104   ** The complete record text is always available for pseudo-tables
62105   ** If the record is stored in a cursor, the complete record text
62106   ** might be available in the  u.am.pC->aRow cache.  Or it might not be.
62107   ** If the data is unavailable,  u.am.zRec is set to NULL.
62108   **
62109   ** We also compute the number of columns in the record.  For cursors,
62110   ** the number of columns is stored in the VdbeCursor.nField element.
62111   */
62112   u.am.pC = p->apCsr[u.am.p1];
62113   assert( u.am.pC!=0 );
62114 #ifndef SQLITE_OMIT_VIRTUALTABLE
62115   assert( u.am.pC->pVtabCursor==0 );
62116 #endif
62117   u.am.pCrsr = u.am.pC->pCursor;
62118   if( u.am.pCrsr!=0 ){
62119     /* The record is stored in a B-Tree */
62120     rc = sqlite3VdbeCursorMoveto(u.am.pC);
62121     if( rc ) goto abort_due_to_error;
62122     if( u.am.pC->nullRow ){
62123       u.am.payloadSize = 0;
62124     }else if( u.am.pC->cacheStatus==p->cacheCtr ){
62125       u.am.payloadSize = u.am.pC->payloadSize;
62126       u.am.zRec = (char*)u.am.pC->aRow;
62127     }else if( u.am.pC->isIndex ){
62128       assert( sqlite3BtreeCursorIsValid(u.am.pCrsr) );
62129       rc = sqlite3BtreeKeySize(u.am.pCrsr, &u.am.payloadSize64);
62130       assert( rc==SQLITE_OK );   /* True because of CursorMoveto() call above */
62131       /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
62132       ** payload size, so it is impossible for u.am.payloadSize64 to be
62133       ** larger than 32 bits. */
62134       assert( (u.am.payloadSize64 & SQLITE_MAX_U32)==(u64)u.am.payloadSize64 );
62135       u.am.payloadSize = (u32)u.am.payloadSize64;
62136     }else{
62137       assert( sqlite3BtreeCursorIsValid(u.am.pCrsr) );
62138       rc = sqlite3BtreeDataSize(u.am.pCrsr, &u.am.payloadSize);
62139       assert( rc==SQLITE_OK );   /* DataSize() cannot fail */
62140     }
62141   }else if( u.am.pC->pseudoTableReg>0 ){
62142     u.am.pReg = &aMem[u.am.pC->pseudoTableReg];
62143     assert( u.am.pReg->flags & MEM_Blob );
62144     assert( memIsValid(u.am.pReg) );
62145     u.am.payloadSize = u.am.pReg->n;
62146     u.am.zRec = u.am.pReg->z;
62147     u.am.pC->cacheStatus = (pOp->p5&OPFLAG_CLEARCACHE) ? CACHE_STALE : p->cacheCtr;
62148     assert( u.am.payloadSize==0 || u.am.zRec!=0 );
62149   }else{
62150     /* Consider the row to be NULL */
62151     u.am.payloadSize = 0;
62152   }
62153
62154   /* If u.am.payloadSize is 0, then just store a NULL */
62155   if( u.am.payloadSize==0 ){
62156     assert( u.am.pDest->flags&MEM_Null );
62157     goto op_column_out;
62158   }
62159   assert( db->aLimit[SQLITE_LIMIT_LENGTH]>=0 );
62160   if( u.am.payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
62161     goto too_big;
62162   }
62163
62164   u.am.nField = u.am.pC->nField;
62165   assert( u.am.p2<u.am.nField );
62166
62167   /* Read and parse the table header.  Store the results of the parse
62168   ** into the record header cache fields of the cursor.
62169   */
62170   u.am.aType = u.am.pC->aType;
62171   if( u.am.pC->cacheStatus==p->cacheCtr ){
62172     u.am.aOffset = u.am.pC->aOffset;
62173   }else{
62174     assert(u.am.aType);
62175     u.am.avail = 0;
62176     u.am.pC->aOffset = u.am.aOffset = &u.am.aType[u.am.nField];
62177     u.am.pC->payloadSize = u.am.payloadSize;
62178     u.am.pC->cacheStatus = p->cacheCtr;
62179
62180     /* Figure out how many bytes are in the header */
62181     if( u.am.zRec ){
62182       u.am.zData = u.am.zRec;
62183     }else{
62184       if( u.am.pC->isIndex ){
62185         u.am.zData = (char*)sqlite3BtreeKeyFetch(u.am.pCrsr, &u.am.avail);
62186       }else{
62187         u.am.zData = (char*)sqlite3BtreeDataFetch(u.am.pCrsr, &u.am.avail);
62188       }
62189       /* If KeyFetch()/DataFetch() managed to get the entire payload,
62190       ** save the payload in the u.am.pC->aRow cache.  That will save us from
62191       ** having to make additional calls to fetch the content portion of
62192       ** the record.
62193       */
62194       assert( u.am.avail>=0 );
62195       if( u.am.payloadSize <= (u32)u.am.avail ){
62196         u.am.zRec = u.am.zData;
62197         u.am.pC->aRow = (u8*)u.am.zData;
62198       }else{
62199         u.am.pC->aRow = 0;
62200       }
62201     }
62202     /* The following assert is true in all cases accept when
62203     ** the database file has been corrupted externally.
62204     **    assert( u.am.zRec!=0 || u.am.avail>=u.am.payloadSize || u.am.avail>=9 ); */
62205     u.am.szHdr = getVarint32((u8*)u.am.zData, u.am.offset);
62206
62207     /* Make sure a corrupt database has not given us an oversize header.
62208     ** Do this now to avoid an oversize memory allocation.
62209     **
62210     ** Type entries can be between 1 and 5 bytes each.  But 4 and 5 byte
62211     ** types use so much data space that there can only be 4096 and 32 of
62212     ** them, respectively.  So the maximum header length results from a
62213     ** 3-byte type for each of the maximum of 32768 columns plus three
62214     ** extra bytes for the header length itself.  32768*3 + 3 = 98307.
62215     */
62216     if( u.am.offset > 98307 ){
62217       rc = SQLITE_CORRUPT_BKPT;
62218       goto op_column_out;
62219     }
62220
62221     /* Compute in u.am.len the number of bytes of data we need to read in order
62222     ** to get u.am.nField type values.  u.am.offset is an upper bound on this.  But
62223     ** u.am.nField might be significantly less than the true number of columns
62224     ** in the table, and in that case, 5*u.am.nField+3 might be smaller than u.am.offset.
62225     ** We want to minimize u.am.len in order to limit the size of the memory
62226     ** allocation, especially if a corrupt database file has caused u.am.offset
62227     ** to be oversized. Offset is limited to 98307 above.  But 98307 might
62228     ** still exceed Robson memory allocation limits on some configurations.
62229     ** On systems that cannot tolerate large memory allocations, u.am.nField*5+3
62230     ** will likely be much smaller since u.am.nField will likely be less than
62231     ** 20 or so.  This insures that Robson memory allocation limits are
62232     ** not exceeded even for corrupt database files.
62233     */
62234     u.am.len = u.am.nField*5 + 3;
62235     if( u.am.len > (int)u.am.offset ) u.am.len = (int)u.am.offset;
62236
62237     /* The KeyFetch() or DataFetch() above are fast and will get the entire
62238     ** record header in most cases.  But they will fail to get the complete
62239     ** record header if the record header does not fit on a single page
62240     ** in the B-Tree.  When that happens, use sqlite3VdbeMemFromBtree() to
62241     ** acquire the complete header text.
62242     */
62243     if( !u.am.zRec && u.am.avail<u.am.len ){
62244       u.am.sMem.flags = 0;
62245       u.am.sMem.db = 0;
62246       rc = sqlite3VdbeMemFromBtree(u.am.pCrsr, 0, u.am.len, u.am.pC->isIndex, &u.am.sMem);
62247       if( rc!=SQLITE_OK ){
62248         goto op_column_out;
62249       }
62250       u.am.zData = u.am.sMem.z;
62251     }
62252     u.am.zEndHdr = (u8 *)&u.am.zData[u.am.len];
62253     u.am.zIdx = (u8 *)&u.am.zData[u.am.szHdr];
62254
62255     /* Scan the header and use it to fill in the u.am.aType[] and u.am.aOffset[]
62256     ** arrays.  u.am.aType[u.am.i] will contain the type integer for the u.am.i-th
62257     ** column and u.am.aOffset[u.am.i] will contain the u.am.offset from the beginning
62258     ** of the record to the start of the data for the u.am.i-th column
62259     */
62260     for(u.am.i=0; u.am.i<u.am.nField; u.am.i++){
62261       if( u.am.zIdx<u.am.zEndHdr ){
62262         u.am.aOffset[u.am.i] = u.am.offset;
62263         u.am.zIdx += getVarint32(u.am.zIdx, u.am.aType[u.am.i]);
62264         u.am.szField = sqlite3VdbeSerialTypeLen(u.am.aType[u.am.i]);
62265         u.am.offset += u.am.szField;
62266         if( u.am.offset<u.am.szField ){  /* True if u.am.offset overflows */
62267           u.am.zIdx = &u.am.zEndHdr[1];  /* Forces SQLITE_CORRUPT return below */
62268           break;
62269         }
62270       }else{
62271         /* If u.am.i is less that u.am.nField, then there are less fields in this
62272         ** record than SetNumColumns indicated there are columns in the
62273         ** table. Set the u.am.offset for any extra columns not present in
62274         ** the record to 0. This tells code below to store a NULL
62275         ** instead of deserializing a value from the record.
62276         */
62277         u.am.aOffset[u.am.i] = 0;
62278       }
62279     }
62280     sqlite3VdbeMemRelease(&u.am.sMem);
62281     u.am.sMem.flags = MEM_Null;
62282
62283     /* If we have read more header data than was contained in the header,
62284     ** or if the end of the last field appears to be past the end of the
62285     ** record, or if the end of the last field appears to be before the end
62286     ** of the record (when all fields present), then we must be dealing
62287     ** with a corrupt database.
62288     */
62289     if( (u.am.zIdx > u.am.zEndHdr) || (u.am.offset > u.am.payloadSize)
62290          || (u.am.zIdx==u.am.zEndHdr && u.am.offset!=u.am.payloadSize) ){
62291       rc = SQLITE_CORRUPT_BKPT;
62292       goto op_column_out;
62293     }
62294   }
62295
62296   /* Get the column information. If u.am.aOffset[u.am.p2] is non-zero, then
62297   ** deserialize the value from the record. If u.am.aOffset[u.am.p2] is zero,
62298   ** then there are not enough fields in the record to satisfy the
62299   ** request.  In this case, set the value NULL or to P4 if P4 is
62300   ** a pointer to a Mem object.
62301   */
62302   if( u.am.aOffset[u.am.p2] ){
62303     assert( rc==SQLITE_OK );
62304     if( u.am.zRec ){
62305       sqlite3VdbeMemReleaseExternal(u.am.pDest);
62306       sqlite3VdbeSerialGet((u8 *)&u.am.zRec[u.am.aOffset[u.am.p2]], u.am.aType[u.am.p2], u.am.pDest);
62307     }else{
62308       u.am.len = sqlite3VdbeSerialTypeLen(u.am.aType[u.am.p2]);
62309       sqlite3VdbeMemMove(&u.am.sMem, u.am.pDest);
62310       rc = sqlite3VdbeMemFromBtree(u.am.pCrsr, u.am.aOffset[u.am.p2], u.am.len, u.am.pC->isIndex, &u.am.sMem);
62311       if( rc!=SQLITE_OK ){
62312         goto op_column_out;
62313       }
62314       u.am.zData = u.am.sMem.z;
62315       sqlite3VdbeSerialGet((u8*)u.am.zData, u.am.aType[u.am.p2], u.am.pDest);
62316     }
62317     u.am.pDest->enc = encoding;
62318   }else{
62319     if( pOp->p4type==P4_MEM ){
62320       sqlite3VdbeMemShallowCopy(u.am.pDest, pOp->p4.pMem, MEM_Static);
62321     }else{
62322       assert( u.am.pDest->flags&MEM_Null );
62323     }
62324   }
62325
62326   /* If we dynamically allocated space to hold the data (in the
62327   ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
62328   ** dynamically allocated space over to the u.am.pDest structure.
62329   ** This prevents a memory copy.
62330   */
62331   if( u.am.sMem.zMalloc ){
62332     assert( u.am.sMem.z==u.am.sMem.zMalloc );
62333     assert( !(u.am.pDest->flags & MEM_Dyn) );
62334     assert( !(u.am.pDest->flags & (MEM_Blob|MEM_Str)) || u.am.pDest->z==u.am.sMem.z );
62335     u.am.pDest->flags &= ~(MEM_Ephem|MEM_Static);
62336     u.am.pDest->flags |= MEM_Term;
62337     u.am.pDest->z = u.am.sMem.z;
62338     u.am.pDest->zMalloc = u.am.sMem.zMalloc;
62339   }
62340
62341   rc = sqlite3VdbeMemMakeWriteable(u.am.pDest);
62342
62343 op_column_out:
62344   UPDATE_MAX_BLOBSIZE(u.am.pDest);
62345   REGISTER_TRACE(pOp->p3, u.am.pDest);
62346   break;
62347 }
62348
62349 /* Opcode: Affinity P1 P2 * P4 *
62350 **
62351 ** Apply affinities to a range of P2 registers starting with P1.
62352 **
62353 ** P4 is a string that is P2 characters long. The nth character of the
62354 ** string indicates the column affinity that should be used for the nth
62355 ** memory cell in the range.
62356 */
62357 case OP_Affinity: {
62358 #if 0  /* local variables moved into u.an */
62359   const char *zAffinity;   /* The affinity to be applied */
62360   char cAff;               /* A single character of affinity */
62361 #endif /* local variables moved into u.an */
62362
62363   u.an.zAffinity = pOp->p4.z;
62364   assert( u.an.zAffinity!=0 );
62365   assert( u.an.zAffinity[pOp->p2]==0 );
62366   pIn1 = &aMem[pOp->p1];
62367   while( (u.an.cAff = *(u.an.zAffinity++))!=0 ){
62368     assert( pIn1 <= &p->aMem[p->nMem] );
62369     assert( memIsValid(pIn1) );
62370     ExpandBlob(pIn1);
62371     applyAffinity(pIn1, u.an.cAff, encoding);
62372     pIn1++;
62373   }
62374   break;
62375 }
62376
62377 /* Opcode: MakeRecord P1 P2 P3 P4 *
62378 **
62379 ** Convert P2 registers beginning with P1 into the [record format]
62380 ** use as a data record in a database table or as a key
62381 ** in an index.  The OP_Column opcode can decode the record later.
62382 **
62383 ** P4 may be a string that is P2 characters long.  The nth character of the
62384 ** string indicates the column affinity that should be used for the nth
62385 ** field of the index key.
62386 **
62387 ** The mapping from character to affinity is given by the SQLITE_AFF_
62388 ** macros defined in sqliteInt.h.
62389 **
62390 ** If P4 is NULL then all index fields have the affinity NONE.
62391 */
62392 case OP_MakeRecord: {
62393 #if 0  /* local variables moved into u.ao */
62394   u8 *zNewRecord;        /* A buffer to hold the data for the new record */
62395   Mem *pRec;             /* The new record */
62396   u64 nData;             /* Number of bytes of data space */
62397   int nHdr;              /* Number of bytes of header space */
62398   i64 nByte;             /* Data space required for this record */
62399   int nZero;             /* Number of zero bytes at the end of the record */
62400   int nVarint;           /* Number of bytes in a varint */
62401   u32 serial_type;       /* Type field */
62402   Mem *pData0;           /* First field to be combined into the record */
62403   Mem *pLast;            /* Last field of the record */
62404   int nField;            /* Number of fields in the record */
62405   char *zAffinity;       /* The affinity string for the record */
62406   int file_format;       /* File format to use for encoding */
62407   int i;                 /* Space used in zNewRecord[] */
62408   int len;               /* Length of a field */
62409 #endif /* local variables moved into u.ao */
62410
62411   /* Assuming the record contains N fields, the record format looks
62412   ** like this:
62413   **
62414   ** ------------------------------------------------------------------------
62415   ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
62416   ** ------------------------------------------------------------------------
62417   **
62418   ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
62419   ** and so froth.
62420   **
62421   ** Each type field is a varint representing the serial type of the
62422   ** corresponding data element (see sqlite3VdbeSerialType()). The
62423   ** hdr-size field is also a varint which is the offset from the beginning
62424   ** of the record to data0.
62425   */
62426   u.ao.nData = 0;         /* Number of bytes of data space */
62427   u.ao.nHdr = 0;          /* Number of bytes of header space */
62428   u.ao.nByte = 0;         /* Data space required for this record */
62429   u.ao.nZero = 0;         /* Number of zero bytes at the end of the record */
62430   u.ao.nField = pOp->p1;
62431   u.ao.zAffinity = pOp->p4.z;
62432   assert( u.ao.nField>0 && pOp->p2>0 && pOp->p2+u.ao.nField<=p->nMem+1 );
62433   u.ao.pData0 = &aMem[u.ao.nField];
62434   u.ao.nField = pOp->p2;
62435   u.ao.pLast = &u.ao.pData0[u.ao.nField-1];
62436   u.ao.file_format = p->minWriteFileFormat;
62437
62438   /* Identify the output register */
62439   assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
62440   pOut = &aMem[pOp->p3];
62441   memAboutToChange(p, pOut);
62442
62443   /* Loop through the elements that will make up the record to figure
62444   ** out how much space is required for the new record.
62445   */
62446   for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){
62447     assert( memIsValid(u.ao.pRec) );
62448     if( u.ao.zAffinity ){
62449       applyAffinity(u.ao.pRec, u.ao.zAffinity[u.ao.pRec-u.ao.pData0], encoding);
62450     }
62451     if( u.ao.pRec->flags&MEM_Zero && u.ao.pRec->n>0 ){
62452       sqlite3VdbeMemExpandBlob(u.ao.pRec);
62453     }
62454     u.ao.serial_type = sqlite3VdbeSerialType(u.ao.pRec, u.ao.file_format);
62455     u.ao.len = sqlite3VdbeSerialTypeLen(u.ao.serial_type);
62456     u.ao.nData += u.ao.len;
62457     u.ao.nHdr += sqlite3VarintLen(u.ao.serial_type);
62458     if( u.ao.pRec->flags & MEM_Zero ){
62459       /* Only pure zero-filled BLOBs can be input to this Opcode.
62460       ** We do not allow blobs with a prefix and a zero-filled tail. */
62461       u.ao.nZero += u.ao.pRec->u.nZero;
62462     }else if( u.ao.len ){
62463       u.ao.nZero = 0;
62464     }
62465   }
62466
62467   /* Add the initial header varint and total the size */
62468   u.ao.nHdr += u.ao.nVarint = sqlite3VarintLen(u.ao.nHdr);
62469   if( u.ao.nVarint<sqlite3VarintLen(u.ao.nHdr) ){
62470     u.ao.nHdr++;
62471   }
62472   u.ao.nByte = u.ao.nHdr+u.ao.nData-u.ao.nZero;
62473   if( u.ao.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
62474     goto too_big;
62475   }
62476
62477   /* Make sure the output register has a buffer large enough to store
62478   ** the new record. The output register (pOp->p3) is not allowed to
62479   ** be one of the input registers (because the following call to
62480   ** sqlite3VdbeMemGrow() could clobber the value before it is used).
62481   */
62482   if( sqlite3VdbeMemGrow(pOut, (int)u.ao.nByte, 0) ){
62483     goto no_mem;
62484   }
62485   u.ao.zNewRecord = (u8 *)pOut->z;
62486
62487   /* Write the record */
62488   u.ao.i = putVarint32(u.ao.zNewRecord, u.ao.nHdr);
62489   for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){
62490     u.ao.serial_type = sqlite3VdbeSerialType(u.ao.pRec, u.ao.file_format);
62491     u.ao.i += putVarint32(&u.ao.zNewRecord[u.ao.i], u.ao.serial_type);      /* serial type */
62492   }
62493   for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){  /* serial data */
62494     u.ao.i += sqlite3VdbeSerialPut(&u.ao.zNewRecord[u.ao.i], (int)(u.ao.nByte-u.ao.i), u.ao.pRec,u.ao.file_format);
62495   }
62496   assert( u.ao.i==u.ao.nByte );
62497
62498   assert( pOp->p3>0 && pOp->p3<=p->nMem );
62499   pOut->n = (int)u.ao.nByte;
62500   pOut->flags = MEM_Blob | MEM_Dyn;
62501   pOut->xDel = 0;
62502   if( u.ao.nZero ){
62503     pOut->u.nZero = u.ao.nZero;
62504     pOut->flags |= MEM_Zero;
62505   }
62506   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever converted to text */
62507   REGISTER_TRACE(pOp->p3, pOut);
62508   UPDATE_MAX_BLOBSIZE(pOut);
62509   break;
62510 }
62511
62512 /* Opcode: Count P1 P2 * * *
62513 **
62514 ** Store the number of entries (an integer value) in the table or index 
62515 ** opened by cursor P1 in register P2
62516 */
62517 #ifndef SQLITE_OMIT_BTREECOUNT
62518 case OP_Count: {         /* out2-prerelease */
62519 #if 0  /* local variables moved into u.ap */
62520   i64 nEntry;
62521   BtCursor *pCrsr;
62522 #endif /* local variables moved into u.ap */
62523
62524   u.ap.pCrsr = p->apCsr[pOp->p1]->pCursor;
62525   if( u.ap.pCrsr ){
62526     rc = sqlite3BtreeCount(u.ap.pCrsr, &u.ap.nEntry);
62527   }else{
62528     u.ap.nEntry = 0;
62529   }
62530   pOut->u.i = u.ap.nEntry;
62531   break;
62532 }
62533 #endif
62534
62535 /* Opcode: Savepoint P1 * * P4 *
62536 **
62537 ** Open, release or rollback the savepoint named by parameter P4, depending
62538 ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
62539 ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
62540 */
62541 case OP_Savepoint: {
62542 #if 0  /* local variables moved into u.aq */
62543   int p1;                         /* Value of P1 operand */
62544   char *zName;                    /* Name of savepoint */
62545   int nName;
62546   Savepoint *pNew;
62547   Savepoint *pSavepoint;
62548   Savepoint *pTmp;
62549   int iSavepoint;
62550   int ii;
62551 #endif /* local variables moved into u.aq */
62552
62553   u.aq.p1 = pOp->p1;
62554   u.aq.zName = pOp->p4.z;
62555
62556   /* Assert that the u.aq.p1 parameter is valid. Also that if there is no open
62557   ** transaction, then there cannot be any savepoints.
62558   */
62559   assert( db->pSavepoint==0 || db->autoCommit==0 );
62560   assert( u.aq.p1==SAVEPOINT_BEGIN||u.aq.p1==SAVEPOINT_RELEASE||u.aq.p1==SAVEPOINT_ROLLBACK );
62561   assert( db->pSavepoint || db->isTransactionSavepoint==0 );
62562   assert( checkSavepointCount(db) );
62563
62564   if( u.aq.p1==SAVEPOINT_BEGIN ){
62565     if( db->writeVdbeCnt>0 ){
62566       /* A new savepoint cannot be created if there are active write
62567       ** statements (i.e. open read/write incremental blob handles).
62568       */
62569       sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - "
62570         "SQL statements in progress");
62571       rc = SQLITE_BUSY;
62572     }else{
62573       u.aq.nName = sqlite3Strlen30(u.aq.zName);
62574
62575       /* Create a new savepoint structure. */
62576       u.aq.pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+u.aq.nName+1);
62577       if( u.aq.pNew ){
62578         u.aq.pNew->zName = (char *)&u.aq.pNew[1];
62579         memcpy(u.aq.pNew->zName, u.aq.zName, u.aq.nName+1);
62580
62581         /* If there is no open transaction, then mark this as a special
62582         ** "transaction savepoint". */
62583         if( db->autoCommit ){
62584           db->autoCommit = 0;
62585           db->isTransactionSavepoint = 1;
62586         }else{
62587           db->nSavepoint++;
62588         }
62589
62590         /* Link the new savepoint into the database handle's list. */
62591         u.aq.pNew->pNext = db->pSavepoint;
62592         db->pSavepoint = u.aq.pNew;
62593         u.aq.pNew->nDeferredCons = db->nDeferredCons;
62594       }
62595     }
62596   }else{
62597     u.aq.iSavepoint = 0;
62598
62599     /* Find the named savepoint. If there is no such savepoint, then an
62600     ** an error is returned to the user.  */
62601     for(
62602       u.aq.pSavepoint = db->pSavepoint;
62603       u.aq.pSavepoint && sqlite3StrICmp(u.aq.pSavepoint->zName, u.aq.zName);
62604       u.aq.pSavepoint = u.aq.pSavepoint->pNext
62605     ){
62606       u.aq.iSavepoint++;
62607     }
62608     if( !u.aq.pSavepoint ){
62609       sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", u.aq.zName);
62610       rc = SQLITE_ERROR;
62611     }else if(
62612         db->writeVdbeCnt>0 || (u.aq.p1==SAVEPOINT_ROLLBACK && db->activeVdbeCnt>1)
62613     ){
62614       /* It is not possible to release (commit) a savepoint if there are
62615       ** active write statements. It is not possible to rollback a savepoint
62616       ** if there are any active statements at all.
62617       */
62618       sqlite3SetString(&p->zErrMsg, db,
62619         "cannot %s savepoint - SQL statements in progress",
62620         (u.aq.p1==SAVEPOINT_ROLLBACK ? "rollback": "release")
62621       );
62622       rc = SQLITE_BUSY;
62623     }else{
62624
62625       /* Determine whether or not this is a transaction savepoint. If so,
62626       ** and this is a RELEASE command, then the current transaction
62627       ** is committed.
62628       */
62629       int isTransaction = u.aq.pSavepoint->pNext==0 && db->isTransactionSavepoint;
62630       if( isTransaction && u.aq.p1==SAVEPOINT_RELEASE ){
62631         if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
62632           goto vdbe_return;
62633         }
62634         db->autoCommit = 1;
62635         if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
62636           p->pc = pc;
62637           db->autoCommit = 0;
62638           p->rc = rc = SQLITE_BUSY;
62639           goto vdbe_return;
62640         }
62641         db->isTransactionSavepoint = 0;
62642         rc = p->rc;
62643       }else{
62644         u.aq.iSavepoint = db->nSavepoint - u.aq.iSavepoint - 1;
62645         for(u.aq.ii=0; u.aq.ii<db->nDb; u.aq.ii++){
62646           rc = sqlite3BtreeSavepoint(db->aDb[u.aq.ii].pBt, u.aq.p1, u.aq.iSavepoint);
62647           if( rc!=SQLITE_OK ){
62648             goto abort_due_to_error;
62649           }
62650         }
62651         if( u.aq.p1==SAVEPOINT_ROLLBACK && (db->flags&SQLITE_InternChanges)!=0 ){
62652           sqlite3ExpirePreparedStatements(db);
62653           sqlite3ResetInternalSchema(db, 0);
62654           db->flags = (db->flags | SQLITE_InternChanges);
62655         }
62656       }
62657
62658       /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
62659       ** savepoints nested inside of the savepoint being operated on. */
62660       while( db->pSavepoint!=u.aq.pSavepoint ){
62661         u.aq.pTmp = db->pSavepoint;
62662         db->pSavepoint = u.aq.pTmp->pNext;
62663         sqlite3DbFree(db, u.aq.pTmp);
62664         db->nSavepoint--;
62665       }
62666
62667       /* If it is a RELEASE, then destroy the savepoint being operated on
62668       ** too. If it is a ROLLBACK TO, then set the number of deferred
62669       ** constraint violations present in the database to the value stored
62670       ** when the savepoint was created.  */
62671       if( u.aq.p1==SAVEPOINT_RELEASE ){
62672         assert( u.aq.pSavepoint==db->pSavepoint );
62673         db->pSavepoint = u.aq.pSavepoint->pNext;
62674         sqlite3DbFree(db, u.aq.pSavepoint);
62675         if( !isTransaction ){
62676           db->nSavepoint--;
62677         }
62678       }else{
62679         db->nDeferredCons = u.aq.pSavepoint->nDeferredCons;
62680       }
62681     }
62682   }
62683
62684   break;
62685 }
62686
62687 /* Opcode: AutoCommit P1 P2 * * *
62688 **
62689 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
62690 ** back any currently active btree transactions. If there are any active
62691 ** VMs (apart from this one), then a ROLLBACK fails.  A COMMIT fails if
62692 ** there are active writing VMs or active VMs that use shared cache.
62693 **
62694 ** This instruction causes the VM to halt.
62695 */
62696 case OP_AutoCommit: {
62697 #if 0  /* local variables moved into u.ar */
62698   int desiredAutoCommit;
62699   int iRollback;
62700   int turnOnAC;
62701 #endif /* local variables moved into u.ar */
62702
62703   u.ar.desiredAutoCommit = pOp->p1;
62704   u.ar.iRollback = pOp->p2;
62705   u.ar.turnOnAC = u.ar.desiredAutoCommit && !db->autoCommit;
62706   assert( u.ar.desiredAutoCommit==1 || u.ar.desiredAutoCommit==0 );
62707   assert( u.ar.desiredAutoCommit==1 || u.ar.iRollback==0 );
62708   assert( db->activeVdbeCnt>0 );  /* At least this one VM is active */
62709
62710   if( u.ar.turnOnAC && u.ar.iRollback && db->activeVdbeCnt>1 ){
62711     /* If this instruction implements a ROLLBACK and other VMs are
62712     ** still running, and a transaction is active, return an error indicating
62713     ** that the other VMs must complete first.
62714     */
62715     sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
62716         "SQL statements in progress");
62717     rc = SQLITE_BUSY;
62718   }else if( u.ar.turnOnAC && !u.ar.iRollback && db->writeVdbeCnt>0 ){
62719     /* If this instruction implements a COMMIT and other VMs are writing
62720     ** return an error indicating that the other VMs must complete first.
62721     */
62722     sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - "
62723         "SQL statements in progress");
62724     rc = SQLITE_BUSY;
62725   }else if( u.ar.desiredAutoCommit!=db->autoCommit ){
62726     if( u.ar.iRollback ){
62727       assert( u.ar.desiredAutoCommit==1 );
62728       sqlite3RollbackAll(db);
62729       db->autoCommit = 1;
62730     }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
62731       goto vdbe_return;
62732     }else{
62733       db->autoCommit = (u8)u.ar.desiredAutoCommit;
62734       if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
62735         p->pc = pc;
62736         db->autoCommit = (u8)(1-u.ar.desiredAutoCommit);
62737         p->rc = rc = SQLITE_BUSY;
62738         goto vdbe_return;
62739       }
62740     }
62741     assert( db->nStatement==0 );
62742     sqlite3CloseSavepoints(db);
62743     if( p->rc==SQLITE_OK ){
62744       rc = SQLITE_DONE;
62745     }else{
62746       rc = SQLITE_ERROR;
62747     }
62748     goto vdbe_return;
62749   }else{
62750     sqlite3SetString(&p->zErrMsg, db,
62751         (!u.ar.desiredAutoCommit)?"cannot start a transaction within a transaction":(
62752         (u.ar.iRollback)?"cannot rollback - no transaction is active":
62753                    "cannot commit - no transaction is active"));
62754
62755     rc = SQLITE_ERROR;
62756   }
62757   break;
62758 }
62759
62760 /* Opcode: Transaction P1 P2 * * *
62761 **
62762 ** Begin a transaction.  The transaction ends when a Commit or Rollback
62763 ** opcode is encountered.  Depending on the ON CONFLICT setting, the
62764 ** transaction might also be rolled back if an error is encountered.
62765 **
62766 ** P1 is the index of the database file on which the transaction is
62767 ** started.  Index 0 is the main database file and index 1 is the
62768 ** file used for temporary tables.  Indices of 2 or more are used for
62769 ** attached databases.
62770 **
62771 ** If P2 is non-zero, then a write-transaction is started.  A RESERVED lock is
62772 ** obtained on the database file when a write-transaction is started.  No
62773 ** other process can start another write transaction while this transaction is
62774 ** underway.  Starting a write transaction also creates a rollback journal. A
62775 ** write transaction must be started before any changes can be made to the
62776 ** database.  If P2 is 2 or greater then an EXCLUSIVE lock is also obtained
62777 ** on the file.
62778 **
62779 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
62780 ** true (this flag is set if the Vdbe may modify more than one row and may
62781 ** throw an ABORT exception), a statement transaction may also be opened.
62782 ** More specifically, a statement transaction is opened iff the database
62783 ** connection is currently not in autocommit mode, or if there are other
62784 ** active statements. A statement transaction allows the affects of this
62785 ** VDBE to be rolled back after an error without having to roll back the
62786 ** entire transaction. If no error is encountered, the statement transaction
62787 ** will automatically commit when the VDBE halts.
62788 **
62789 ** If P2 is zero, then a read-lock is obtained on the database file.
62790 */
62791 case OP_Transaction: {
62792 #if 0  /* local variables moved into u.as */
62793   Btree *pBt;
62794 #endif /* local variables moved into u.as */
62795
62796   assert( pOp->p1>=0 && pOp->p1<db->nDb );
62797   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
62798   u.as.pBt = db->aDb[pOp->p1].pBt;
62799
62800   if( u.as.pBt ){
62801     rc = sqlite3BtreeBeginTrans(u.as.pBt, pOp->p2);
62802     if( rc==SQLITE_BUSY ){
62803       p->pc = pc;
62804       p->rc = rc = SQLITE_BUSY;
62805       goto vdbe_return;
62806     }
62807     if( rc!=SQLITE_OK ){
62808       goto abort_due_to_error;
62809     }
62810
62811     if( pOp->p2 && p->usesStmtJournal
62812      && (db->autoCommit==0 || db->activeVdbeCnt>1)
62813     ){
62814       assert( sqlite3BtreeIsInTrans(u.as.pBt) );
62815       if( p->iStatement==0 ){
62816         assert( db->nStatement>=0 && db->nSavepoint>=0 );
62817         db->nStatement++;
62818         p->iStatement = db->nSavepoint + db->nStatement;
62819       }
62820       rc = sqlite3BtreeBeginStmt(u.as.pBt, p->iStatement);
62821
62822       /* Store the current value of the database handles deferred constraint
62823       ** counter. If the statement transaction needs to be rolled back,
62824       ** the value of this counter needs to be restored too.  */
62825       p->nStmtDefCons = db->nDeferredCons;
62826     }
62827   }
62828   break;
62829 }
62830
62831 /* Opcode: ReadCookie P1 P2 P3 * *
62832 **
62833 ** Read cookie number P3 from database P1 and write it into register P2.
62834 ** P3==1 is the schema version.  P3==2 is the database format.
62835 ** P3==3 is the recommended pager cache size, and so forth.  P1==0 is
62836 ** the main database file and P1==1 is the database file used to store
62837 ** temporary tables.
62838 **
62839 ** There must be a read-lock on the database (either a transaction
62840 ** must be started or there must be an open cursor) before
62841 ** executing this instruction.
62842 */
62843 case OP_ReadCookie: {               /* out2-prerelease */
62844 #if 0  /* local variables moved into u.at */
62845   int iMeta;
62846   int iDb;
62847   int iCookie;
62848 #endif /* local variables moved into u.at */
62849
62850   u.at.iDb = pOp->p1;
62851   u.at.iCookie = pOp->p3;
62852   assert( pOp->p3<SQLITE_N_BTREE_META );
62853   assert( u.at.iDb>=0 && u.at.iDb<db->nDb );
62854   assert( db->aDb[u.at.iDb].pBt!=0 );
62855   assert( (p->btreeMask & (1<<u.at.iDb))!=0 );
62856
62857   sqlite3BtreeGetMeta(db->aDb[u.at.iDb].pBt, u.at.iCookie, (u32 *)&u.at.iMeta);
62858   pOut->u.i = u.at.iMeta;
62859   break;
62860 }
62861
62862 /* Opcode: SetCookie P1 P2 P3 * *
62863 **
62864 ** Write the content of register P3 (interpreted as an integer)
62865 ** into cookie number P2 of database P1.  P2==1 is the schema version.  
62866 ** P2==2 is the database format. P2==3 is the recommended pager cache 
62867 ** size, and so forth.  P1==0 is the main database file and P1==1 is the 
62868 ** database file used to store temporary tables.
62869 **
62870 ** A transaction must be started before executing this opcode.
62871 */
62872 case OP_SetCookie: {       /* in3 */
62873 #if 0  /* local variables moved into u.au */
62874   Db *pDb;
62875 #endif /* local variables moved into u.au */
62876   assert( pOp->p2<SQLITE_N_BTREE_META );
62877   assert( pOp->p1>=0 && pOp->p1<db->nDb );
62878   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
62879   u.au.pDb = &db->aDb[pOp->p1];
62880   assert( u.au.pDb->pBt!=0 );
62881   pIn3 = &aMem[pOp->p3];
62882   sqlite3VdbeMemIntegerify(pIn3);
62883   /* See note about index shifting on OP_ReadCookie */
62884   rc = sqlite3BtreeUpdateMeta(u.au.pDb->pBt, pOp->p2, (int)pIn3->u.i);
62885   if( pOp->p2==BTREE_SCHEMA_VERSION ){
62886     /* When the schema cookie changes, record the new cookie internally */
62887     u.au.pDb->pSchema->schema_cookie = (int)pIn3->u.i;
62888     db->flags |= SQLITE_InternChanges;
62889   }else if( pOp->p2==BTREE_FILE_FORMAT ){
62890     /* Record changes in the file format */
62891     u.au.pDb->pSchema->file_format = (u8)pIn3->u.i;
62892   }
62893   if( pOp->p1==1 ){
62894     /* Invalidate all prepared statements whenever the TEMP database
62895     ** schema is changed.  Ticket #1644 */
62896     sqlite3ExpirePreparedStatements(db);
62897     p->expired = 0;
62898   }
62899   break;
62900 }
62901
62902 /* Opcode: VerifyCookie P1 P2 *
62903 **
62904 ** Check the value of global database parameter number 0 (the
62905 ** schema version) and make sure it is equal to P2.  
62906 ** P1 is the database number which is 0 for the main database file
62907 ** and 1 for the file holding temporary tables and some higher number
62908 ** for auxiliary databases.
62909 **
62910 ** The cookie changes its value whenever the database schema changes.
62911 ** This operation is used to detect when that the cookie has changed
62912 ** and that the current process needs to reread the schema.
62913 **
62914 ** Either a transaction needs to have been started or an OP_Open needs
62915 ** to be executed (to establish a read lock) before this opcode is
62916 ** invoked.
62917 */
62918 case OP_VerifyCookie: {
62919 #if 0  /* local variables moved into u.av */
62920   int iMeta;
62921   Btree *pBt;
62922 #endif /* local variables moved into u.av */
62923   assert( pOp->p1>=0 && pOp->p1<db->nDb );
62924   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
62925   u.av.pBt = db->aDb[pOp->p1].pBt;
62926   if( u.av.pBt ){
62927     sqlite3BtreeGetMeta(u.av.pBt, BTREE_SCHEMA_VERSION, (u32 *)&u.av.iMeta);
62928   }else{
62929     u.av.iMeta = 0;
62930   }
62931   if( u.av.iMeta!=pOp->p2 ){
62932     sqlite3DbFree(db, p->zErrMsg);
62933     p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
62934     /* If the schema-cookie from the database file matches the cookie
62935     ** stored with the in-memory representation of the schema, do
62936     ** not reload the schema from the database file.
62937     **
62938     ** If virtual-tables are in use, this is not just an optimization.
62939     ** Often, v-tables store their data in other SQLite tables, which
62940     ** are queried from within xNext() and other v-table methods using
62941     ** prepared queries. If such a query is out-of-date, we do not want to
62942     ** discard the database schema, as the user code implementing the
62943     ** v-table would have to be ready for the sqlite3_vtab structure itself
62944     ** to be invalidated whenever sqlite3_step() is called from within
62945     ** a v-table method.
62946     */
62947     if( db->aDb[pOp->p1].pSchema->schema_cookie!=u.av.iMeta ){
62948       sqlite3ResetInternalSchema(db, pOp->p1);
62949     }
62950
62951     sqlite3ExpirePreparedStatements(db);
62952     rc = SQLITE_SCHEMA;
62953   }
62954   break;
62955 }
62956
62957 /* Opcode: OpenRead P1 P2 P3 P4 P5
62958 **
62959 ** Open a read-only cursor for the database table whose root page is
62960 ** P2 in a database file.  The database file is determined by P3. 
62961 ** P3==0 means the main database, P3==1 means the database used for 
62962 ** temporary tables, and P3>1 means used the corresponding attached
62963 ** database.  Give the new cursor an identifier of P1.  The P1
62964 ** values need not be contiguous but all P1 values should be small integers.
62965 ** It is an error for P1 to be negative.
62966 **
62967 ** If P5!=0 then use the content of register P2 as the root page, not
62968 ** the value of P2 itself.
62969 **
62970 ** There will be a read lock on the database whenever there is an
62971 ** open cursor.  If the database was unlocked prior to this instruction
62972 ** then a read lock is acquired as part of this instruction.  A read
62973 ** lock allows other processes to read the database but prohibits
62974 ** any other process from modifying the database.  The read lock is
62975 ** released when all cursors are closed.  If this instruction attempts
62976 ** to get a read lock but fails, the script terminates with an
62977 ** SQLITE_BUSY error code.
62978 **
62979 ** The P4 value may be either an integer (P4_INT32) or a pointer to
62980 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo 
62981 ** structure, then said structure defines the content and collating 
62982 ** sequence of the index being opened. Otherwise, if P4 is an integer 
62983 ** value, it is set to the number of columns in the table.
62984 **
62985 ** See also OpenWrite.
62986 */
62987 /* Opcode: OpenWrite P1 P2 P3 P4 P5
62988 **
62989 ** Open a read/write cursor named P1 on the table or index whose root
62990 ** page is P2.  Or if P5!=0 use the content of register P2 to find the
62991 ** root page.
62992 **
62993 ** The P4 value may be either an integer (P4_INT32) or a pointer to
62994 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo 
62995 ** structure, then said structure defines the content and collating 
62996 ** sequence of the index being opened. Otherwise, if P4 is an integer 
62997 ** value, it is set to the number of columns in the table, or to the
62998 ** largest index of any column of the table that is actually used.
62999 **
63000 ** This instruction works just like OpenRead except that it opens the cursor
63001 ** in read/write mode.  For a given table, there can be one or more read-only
63002 ** cursors or a single read/write cursor but not both.
63003 **
63004 ** See also OpenRead.
63005 */
63006 case OP_OpenRead:
63007 case OP_OpenWrite: {
63008 #if 0  /* local variables moved into u.aw */
63009   int nField;
63010   KeyInfo *pKeyInfo;
63011   int p2;
63012   int iDb;
63013   int wrFlag;
63014   Btree *pX;
63015   VdbeCursor *pCur;
63016   Db *pDb;
63017 #endif /* local variables moved into u.aw */
63018
63019   if( p->expired ){
63020     rc = SQLITE_ABORT;
63021     break;
63022   }
63023
63024   u.aw.nField = 0;
63025   u.aw.pKeyInfo = 0;
63026   u.aw.p2 = pOp->p2;
63027   u.aw.iDb = pOp->p3;
63028   assert( u.aw.iDb>=0 && u.aw.iDb<db->nDb );
63029   assert( (p->btreeMask & (1<<u.aw.iDb))!=0 );
63030   u.aw.pDb = &db->aDb[u.aw.iDb];
63031   u.aw.pX = u.aw.pDb->pBt;
63032   assert( u.aw.pX!=0 );
63033   if( pOp->opcode==OP_OpenWrite ){
63034     u.aw.wrFlag = 1;
63035     if( u.aw.pDb->pSchema->file_format < p->minWriteFileFormat ){
63036       p->minWriteFileFormat = u.aw.pDb->pSchema->file_format;
63037     }
63038   }else{
63039     u.aw.wrFlag = 0;
63040   }
63041   if( pOp->p5 ){
63042     assert( u.aw.p2>0 );
63043     assert( u.aw.p2<=p->nMem );
63044     pIn2 = &aMem[u.aw.p2];
63045     assert( memIsValid(pIn2) );
63046     assert( (pIn2->flags & MEM_Int)!=0 );
63047     sqlite3VdbeMemIntegerify(pIn2);
63048     u.aw.p2 = (int)pIn2->u.i;
63049     /* The u.aw.p2 value always comes from a prior OP_CreateTable opcode and
63050     ** that opcode will always set the u.aw.p2 value to 2 or more or else fail.
63051     ** If there were a failure, the prepared statement would have halted
63052     ** before reaching this instruction. */
63053     if( NEVER(u.aw.p2<2) ) {
63054       rc = SQLITE_CORRUPT_BKPT;
63055       goto abort_due_to_error;
63056     }
63057   }
63058   if( pOp->p4type==P4_KEYINFO ){
63059     u.aw.pKeyInfo = pOp->p4.pKeyInfo;
63060     u.aw.pKeyInfo->enc = ENC(p->db);
63061     u.aw.nField = u.aw.pKeyInfo->nField+1;
63062   }else if( pOp->p4type==P4_INT32 ){
63063     u.aw.nField = pOp->p4.i;
63064   }
63065   assert( pOp->p1>=0 );
63066   u.aw.pCur = allocateCursor(p, pOp->p1, u.aw.nField, u.aw.iDb, 1);
63067   if( u.aw.pCur==0 ) goto no_mem;
63068   u.aw.pCur->nullRow = 1;
63069   u.aw.pCur->isOrdered = 1;
63070   rc = sqlite3BtreeCursor(u.aw.pX, u.aw.p2, u.aw.wrFlag, u.aw.pKeyInfo, u.aw.pCur->pCursor);
63071   u.aw.pCur->pKeyInfo = u.aw.pKeyInfo;
63072
63073   /* Since it performs no memory allocation or IO, the only values that
63074   ** sqlite3BtreeCursor() may return are SQLITE_EMPTY and SQLITE_OK.
63075   ** SQLITE_EMPTY is only returned when attempting to open the table
63076   ** rooted at page 1 of a zero-byte database.  */
63077   assert( rc==SQLITE_EMPTY || rc==SQLITE_OK );
63078   if( rc==SQLITE_EMPTY ){
63079     u.aw.pCur->pCursor = 0;
63080     rc = SQLITE_OK;
63081   }
63082
63083   /* Set the VdbeCursor.isTable and isIndex variables. Previous versions of
63084   ** SQLite used to check if the root-page flags were sane at this point
63085   ** and report database corruption if they were not, but this check has
63086   ** since moved into the btree layer.  */
63087   u.aw.pCur->isTable = pOp->p4type!=P4_KEYINFO;
63088   u.aw.pCur->isIndex = !u.aw.pCur->isTable;
63089   break;
63090 }
63091
63092 /* Opcode: OpenEphemeral P1 P2 * P4 *
63093 **
63094 ** Open a new cursor P1 to a transient table.
63095 ** The cursor is always opened read/write even if 
63096 ** the main database is read-only.  The ephemeral
63097 ** table is deleted automatically when the cursor is closed.
63098 **
63099 ** P2 is the number of columns in the ephemeral table.
63100 ** The cursor points to a BTree table if P4==0 and to a BTree index
63101 ** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
63102 ** that defines the format of keys in the index.
63103 **
63104 ** This opcode was once called OpenTemp.  But that created
63105 ** confusion because the term "temp table", might refer either
63106 ** to a TEMP table at the SQL level, or to a table opened by
63107 ** this opcode.  Then this opcode was call OpenVirtual.  But
63108 ** that created confusion with the whole virtual-table idea.
63109 */
63110 /* Opcode: OpenAutoindex P1 P2 * P4 *
63111 **
63112 ** This opcode works the same as OP_OpenEphemeral.  It has a
63113 ** different name to distinguish its use.  Tables created using
63114 ** by this opcode will be used for automatically created transient
63115 ** indices in joins.
63116 */
63117 case OP_OpenAutoindex: 
63118 case OP_OpenEphemeral: {
63119 #if 0  /* local variables moved into u.ax */
63120   VdbeCursor *pCx;
63121 #endif /* local variables moved into u.ax */
63122   static const int vfsFlags =
63123       SQLITE_OPEN_READWRITE |
63124       SQLITE_OPEN_CREATE |
63125       SQLITE_OPEN_EXCLUSIVE |
63126       SQLITE_OPEN_DELETEONCLOSE |
63127       SQLITE_OPEN_TRANSIENT_DB;
63128
63129   assert( pOp->p1>=0 );
63130   u.ax.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
63131   if( u.ax.pCx==0 ) goto no_mem;
63132   u.ax.pCx->nullRow = 1;
63133   rc = sqlite3BtreeOpen(0, db, &u.ax.pCx->pBt,
63134                         BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
63135   if( rc==SQLITE_OK ){
63136     rc = sqlite3BtreeBeginTrans(u.ax.pCx->pBt, 1);
63137   }
63138   if( rc==SQLITE_OK ){
63139     /* If a transient index is required, create it by calling
63140     ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
63141     ** opening it. If a transient table is required, just use the
63142     ** automatically created table with root-page 1 (an BLOB_INTKEY table).
63143     */
63144     if( pOp->p4.pKeyInfo ){
63145       int pgno;
63146       assert( pOp->p4type==P4_KEYINFO );
63147       rc = sqlite3BtreeCreateTable(u.ax.pCx->pBt, &pgno, BTREE_BLOBKEY);
63148       if( rc==SQLITE_OK ){
63149         assert( pgno==MASTER_ROOT+1 );
63150         rc = sqlite3BtreeCursor(u.ax.pCx->pBt, pgno, 1,
63151                                 (KeyInfo*)pOp->p4.z, u.ax.pCx->pCursor);
63152         u.ax.pCx->pKeyInfo = pOp->p4.pKeyInfo;
63153         u.ax.pCx->pKeyInfo->enc = ENC(p->db);
63154       }
63155       u.ax.pCx->isTable = 0;
63156     }else{
63157       rc = sqlite3BtreeCursor(u.ax.pCx->pBt, MASTER_ROOT, 1, 0, u.ax.pCx->pCursor);
63158       u.ax.pCx->isTable = 1;
63159     }
63160   }
63161   u.ax.pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
63162   u.ax.pCx->isIndex = !u.ax.pCx->isTable;
63163   break;
63164 }
63165
63166 /* Opcode: OpenPseudo P1 P2 P3 * *
63167 **
63168 ** Open a new cursor that points to a fake table that contains a single
63169 ** row of data.  The content of that one row in the content of memory
63170 ** register P2.  In other words, cursor P1 becomes an alias for the 
63171 ** MEM_Blob content contained in register P2.
63172 **
63173 ** A pseudo-table created by this opcode is used to hold a single
63174 ** row output from the sorter so that the row can be decomposed into
63175 ** individual columns using the OP_Column opcode.  The OP_Column opcode
63176 ** is the only cursor opcode that works with a pseudo-table.
63177 **
63178 ** P3 is the number of fields in the records that will be stored by
63179 ** the pseudo-table.
63180 */
63181 case OP_OpenPseudo: {
63182 #if 0  /* local variables moved into u.ay */
63183   VdbeCursor *pCx;
63184 #endif /* local variables moved into u.ay */
63185
63186   assert( pOp->p1>=0 );
63187   u.ay.pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
63188   if( u.ay.pCx==0 ) goto no_mem;
63189   u.ay.pCx->nullRow = 1;
63190   u.ay.pCx->pseudoTableReg = pOp->p2;
63191   u.ay.pCx->isTable = 1;
63192   u.ay.pCx->isIndex = 0;
63193   break;
63194 }
63195
63196 /* Opcode: Close P1 * * * *
63197 **
63198 ** Close a cursor previously opened as P1.  If P1 is not
63199 ** currently open, this instruction is a no-op.
63200 */
63201 case OP_Close: {
63202   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
63203   sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
63204   p->apCsr[pOp->p1] = 0;
63205   break;
63206 }
63207
63208 /* Opcode: SeekGe P1 P2 P3 P4 *
63209 **
63210 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
63211 ** use the value in register P3 as the key.  If cursor P1 refers 
63212 ** to an SQL index, then P3 is the first in an array of P4 registers 
63213 ** that are used as an unpacked index key. 
63214 **
63215 ** Reposition cursor P1 so that  it points to the smallest entry that 
63216 ** is greater than or equal to the key value. If there are no records 
63217 ** greater than or equal to the key and P2 is not zero, then jump to P2.
63218 **
63219 ** See also: Found, NotFound, Distinct, SeekLt, SeekGt, SeekLe
63220 */
63221 /* Opcode: SeekGt P1 P2 P3 P4 *
63222 **
63223 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
63224 ** use the value in register P3 as a key. If cursor P1 refers 
63225 ** to an SQL index, then P3 is the first in an array of P4 registers 
63226 ** that are used as an unpacked index key. 
63227 **
63228 ** Reposition cursor P1 so that  it points to the smallest entry that 
63229 ** is greater than the key value. If there are no records greater than 
63230 ** the key and P2 is not zero, then jump to P2.
63231 **
63232 ** See also: Found, NotFound, Distinct, SeekLt, SeekGe, SeekLe
63233 */
63234 /* Opcode: SeekLt P1 P2 P3 P4 * 
63235 **
63236 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
63237 ** use the value in register P3 as a key. If cursor P1 refers 
63238 ** to an SQL index, then P3 is the first in an array of P4 registers 
63239 ** that are used as an unpacked index key. 
63240 **
63241 ** Reposition cursor P1 so that  it points to the largest entry that 
63242 ** is less than the key value. If there are no records less than 
63243 ** the key and P2 is not zero, then jump to P2.
63244 **
63245 ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLe
63246 */
63247 /* Opcode: SeekLe P1 P2 P3 P4 *
63248 **
63249 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
63250 ** use the value in register P3 as a key. If cursor P1 refers 
63251 ** to an SQL index, then P3 is the first in an array of P4 registers 
63252 ** that are used as an unpacked index key. 
63253 **
63254 ** Reposition cursor P1 so that it points to the largest entry that 
63255 ** is less than or equal to the key value. If there are no records 
63256 ** less than or equal to the key and P2 is not zero, then jump to P2.
63257 **
63258 ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLt
63259 */
63260 case OP_SeekLt:         /* jump, in3 */
63261 case OP_SeekLe:         /* jump, in3 */
63262 case OP_SeekGe:         /* jump, in3 */
63263 case OP_SeekGt: {       /* jump, in3 */
63264 #if 0  /* local variables moved into u.az */
63265   int res;
63266   int oc;
63267   VdbeCursor *pC;
63268   UnpackedRecord r;
63269   int nField;
63270   i64 iKey;      /* The rowid we are to seek to */
63271 #endif /* local variables moved into u.az */
63272
63273   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
63274   assert( pOp->p2!=0 );
63275   u.az.pC = p->apCsr[pOp->p1];
63276   assert( u.az.pC!=0 );
63277   assert( u.az.pC->pseudoTableReg==0 );
63278   assert( OP_SeekLe == OP_SeekLt+1 );
63279   assert( OP_SeekGe == OP_SeekLt+2 );
63280   assert( OP_SeekGt == OP_SeekLt+3 );
63281   assert( u.az.pC->isOrdered );
63282   if( u.az.pC->pCursor!=0 ){
63283     u.az.oc = pOp->opcode;
63284     u.az.pC->nullRow = 0;
63285     if( u.az.pC->isTable ){
63286       /* The input value in P3 might be of any type: integer, real, string,
63287       ** blob, or NULL.  But it needs to be an integer before we can do
63288       ** the seek, so covert it. */
63289       pIn3 = &aMem[pOp->p3];
63290       applyNumericAffinity(pIn3);
63291       u.az.iKey = sqlite3VdbeIntValue(pIn3);
63292       u.az.pC->rowidIsValid = 0;
63293
63294       /* If the P3 value could not be converted into an integer without
63295       ** loss of information, then special processing is required... */
63296       if( (pIn3->flags & MEM_Int)==0 ){
63297         if( (pIn3->flags & MEM_Real)==0 ){
63298           /* If the P3 value cannot be converted into any kind of a number,
63299           ** then the seek is not possible, so jump to P2 */
63300           pc = pOp->p2 - 1;
63301           break;
63302         }
63303         /* If we reach this point, then the P3 value must be a floating
63304         ** point number. */
63305         assert( (pIn3->flags & MEM_Real)!=0 );
63306
63307         if( u.az.iKey==SMALLEST_INT64 && (pIn3->r<(double)u.az.iKey || pIn3->r>0) ){
63308           /* The P3 value is too large in magnitude to be expressed as an
63309           ** integer. */
63310           u.az.res = 1;
63311           if( pIn3->r<0 ){
63312             if( u.az.oc>=OP_SeekGe ){  assert( u.az.oc==OP_SeekGe || u.az.oc==OP_SeekGt );
63313               rc = sqlite3BtreeFirst(u.az.pC->pCursor, &u.az.res);
63314               if( rc!=SQLITE_OK ) goto abort_due_to_error;
63315             }
63316           }else{
63317             if( u.az.oc<=OP_SeekLe ){  assert( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekLe );
63318               rc = sqlite3BtreeLast(u.az.pC->pCursor, &u.az.res);
63319               if( rc!=SQLITE_OK ) goto abort_due_to_error;
63320             }
63321           }
63322           if( u.az.res ){
63323             pc = pOp->p2 - 1;
63324           }
63325           break;
63326         }else if( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekGe ){
63327           /* Use the ceiling() function to convert real->int */
63328           if( pIn3->r > (double)u.az.iKey ) u.az.iKey++;
63329         }else{
63330           /* Use the floor() function to convert real->int */
63331           assert( u.az.oc==OP_SeekLe || u.az.oc==OP_SeekGt );
63332           if( pIn3->r < (double)u.az.iKey ) u.az.iKey--;
63333         }
63334       }
63335       rc = sqlite3BtreeMovetoUnpacked(u.az.pC->pCursor, 0, (u64)u.az.iKey, 0, &u.az.res);
63336       if( rc!=SQLITE_OK ){
63337         goto abort_due_to_error;
63338       }
63339       if( u.az.res==0 ){
63340         u.az.pC->rowidIsValid = 1;
63341         u.az.pC->lastRowid = u.az.iKey;
63342       }
63343     }else{
63344       u.az.nField = pOp->p4.i;
63345       assert( pOp->p4type==P4_INT32 );
63346       assert( u.az.nField>0 );
63347       u.az.r.pKeyInfo = u.az.pC->pKeyInfo;
63348       u.az.r.nField = (u16)u.az.nField;
63349
63350       /* The next line of code computes as follows, only faster:
63351       **   if( u.az.oc==OP_SeekGt || u.az.oc==OP_SeekLe ){
63352       **     u.az.r.flags = UNPACKED_INCRKEY;
63353       **   }else{
63354       **     u.az.r.flags = 0;
63355       **   }
63356       */
63357       u.az.r.flags = (u16)(UNPACKED_INCRKEY * (1 & (u.az.oc - OP_SeekLt)));
63358       assert( u.az.oc!=OP_SeekGt || u.az.r.flags==UNPACKED_INCRKEY );
63359       assert( u.az.oc!=OP_SeekLe || u.az.r.flags==UNPACKED_INCRKEY );
63360       assert( u.az.oc!=OP_SeekGe || u.az.r.flags==0 );
63361       assert( u.az.oc!=OP_SeekLt || u.az.r.flags==0 );
63362
63363       u.az.r.aMem = &aMem[pOp->p3];
63364 #ifdef SQLITE_DEBUG
63365       { int i; for(i=0; i<u.az.r.nField; i++) assert( memIsValid(&u.az.r.aMem[i]) ); }
63366 #endif
63367       ExpandBlob(u.az.r.aMem);
63368       rc = sqlite3BtreeMovetoUnpacked(u.az.pC->pCursor, &u.az.r, 0, 0, &u.az.res);
63369       if( rc!=SQLITE_OK ){
63370         goto abort_due_to_error;
63371       }
63372       u.az.pC->rowidIsValid = 0;
63373     }
63374     u.az.pC->deferredMoveto = 0;
63375     u.az.pC->cacheStatus = CACHE_STALE;
63376 #ifdef SQLITE_TEST
63377     sqlite3_search_count++;
63378 #endif
63379     if( u.az.oc>=OP_SeekGe ){  assert( u.az.oc==OP_SeekGe || u.az.oc==OP_SeekGt );
63380       if( u.az.res<0 || (u.az.res==0 && u.az.oc==OP_SeekGt) ){
63381         rc = sqlite3BtreeNext(u.az.pC->pCursor, &u.az.res);
63382         if( rc!=SQLITE_OK ) goto abort_due_to_error;
63383         u.az.pC->rowidIsValid = 0;
63384       }else{
63385         u.az.res = 0;
63386       }
63387     }else{
63388       assert( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekLe );
63389       if( u.az.res>0 || (u.az.res==0 && u.az.oc==OP_SeekLt) ){
63390         rc = sqlite3BtreePrevious(u.az.pC->pCursor, &u.az.res);
63391         if( rc!=SQLITE_OK ) goto abort_due_to_error;
63392         u.az.pC->rowidIsValid = 0;
63393       }else{
63394         /* u.az.res might be negative because the table is empty.  Check to
63395         ** see if this is the case.
63396         */
63397         u.az.res = sqlite3BtreeEof(u.az.pC->pCursor);
63398       }
63399     }
63400     assert( pOp->p2>0 );
63401     if( u.az.res ){
63402       pc = pOp->p2 - 1;
63403     }
63404   }else{
63405     /* This happens when attempting to open the sqlite3_master table
63406     ** for read access returns SQLITE_EMPTY. In this case always
63407     ** take the jump (since there are no records in the table).
63408     */
63409     pc = pOp->p2 - 1;
63410   }
63411   break;
63412 }
63413
63414 /* Opcode: Seek P1 P2 * * *
63415 **
63416 ** P1 is an open table cursor and P2 is a rowid integer.  Arrange
63417 ** for P1 to move so that it points to the rowid given by P2.
63418 **
63419 ** This is actually a deferred seek.  Nothing actually happens until
63420 ** the cursor is used to read a record.  That way, if no reads
63421 ** occur, no unnecessary I/O happens.
63422 */
63423 case OP_Seek: {    /* in2 */
63424 #if 0  /* local variables moved into u.ba */
63425   VdbeCursor *pC;
63426 #endif /* local variables moved into u.ba */
63427
63428   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
63429   u.ba.pC = p->apCsr[pOp->p1];
63430   assert( u.ba.pC!=0 );
63431   if( ALWAYS(u.ba.pC->pCursor!=0) ){
63432     assert( u.ba.pC->isTable );
63433     u.ba.pC->nullRow = 0;
63434     pIn2 = &aMem[pOp->p2];
63435     u.ba.pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
63436     u.ba.pC->rowidIsValid = 0;
63437     u.ba.pC->deferredMoveto = 1;
63438   }
63439   break;
63440 }
63441   
63442
63443 /* Opcode: Found P1 P2 P3 P4 *
63444 **
63445 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
63446 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
63447 ** record.
63448 **
63449 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
63450 ** is a prefix of any entry in P1 then a jump is made to P2 and
63451 ** P1 is left pointing at the matching entry.
63452 */
63453 /* Opcode: NotFound P1 P2 P3 P4 *
63454 **
63455 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
63456 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
63457 ** record.
63458 ** 
63459 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
63460 ** is not the prefix of any entry in P1 then a jump is made to P2.  If P1 
63461 ** does contain an entry whose prefix matches the P3/P4 record then control
63462 ** falls through to the next instruction and P1 is left pointing at the
63463 ** matching entry.
63464 **
63465 ** See also: Found, NotExists, IsUnique
63466 */
63467 case OP_NotFound:       /* jump, in3 */
63468 case OP_Found: {        /* jump, in3 */
63469 #if 0  /* local variables moved into u.bb */
63470   int alreadyExists;
63471   VdbeCursor *pC;
63472   int res;
63473   UnpackedRecord *pIdxKey;
63474   UnpackedRecord r;
63475   char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
63476 #endif /* local variables moved into u.bb */
63477
63478 #ifdef SQLITE_TEST
63479   sqlite3_found_count++;
63480 #endif
63481
63482   u.bb.alreadyExists = 0;
63483   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
63484   assert( pOp->p4type==P4_INT32 );
63485   u.bb.pC = p->apCsr[pOp->p1];
63486   assert( u.bb.pC!=0 );
63487   pIn3 = &aMem[pOp->p3];
63488   if( ALWAYS(u.bb.pC->pCursor!=0) ){
63489
63490     assert( u.bb.pC->isTable==0 );
63491     if( pOp->p4.i>0 ){
63492       u.bb.r.pKeyInfo = u.bb.pC->pKeyInfo;
63493       u.bb.r.nField = (u16)pOp->p4.i;
63494       u.bb.r.aMem = pIn3;
63495 #ifdef SQLITE_DEBUG
63496       { int i; for(i=0; i<u.bb.r.nField; i++) assert( memIsValid(&u.bb.r.aMem[i]) ); }
63497 #endif
63498       u.bb.r.flags = UNPACKED_PREFIX_MATCH;
63499       u.bb.pIdxKey = &u.bb.r;
63500     }else{
63501       assert( pIn3->flags & MEM_Blob );
63502       assert( (pIn3->flags & MEM_Zero)==0 );  /* zeroblobs already expanded */
63503       u.bb.pIdxKey = sqlite3VdbeRecordUnpack(u.bb.pC->pKeyInfo, pIn3->n, pIn3->z,
63504                                         u.bb.aTempRec, sizeof(u.bb.aTempRec));
63505       if( u.bb.pIdxKey==0 ){
63506         goto no_mem;
63507       }
63508       u.bb.pIdxKey->flags |= UNPACKED_PREFIX_MATCH;
63509     }
63510     rc = sqlite3BtreeMovetoUnpacked(u.bb.pC->pCursor, u.bb.pIdxKey, 0, 0, &u.bb.res);
63511     if( pOp->p4.i==0 ){
63512       sqlite3VdbeDeleteUnpackedRecord(u.bb.pIdxKey);
63513     }
63514     if( rc!=SQLITE_OK ){
63515       break;
63516     }
63517     u.bb.alreadyExists = (u.bb.res==0);
63518     u.bb.pC->deferredMoveto = 0;
63519     u.bb.pC->cacheStatus = CACHE_STALE;
63520   }
63521   if( pOp->opcode==OP_Found ){
63522     if( u.bb.alreadyExists ) pc = pOp->p2 - 1;
63523   }else{
63524     if( !u.bb.alreadyExists ) pc = pOp->p2 - 1;
63525   }
63526   break;
63527 }
63528
63529 /* Opcode: IsUnique P1 P2 P3 P4 *
63530 **
63531 ** Cursor P1 is open on an index b-tree - that is to say, a btree which
63532 ** no data and where the key are records generated by OP_MakeRecord with
63533 ** the list field being the integer ROWID of the entry that the index
63534 ** entry refers to.
63535 **
63536 ** The P3 register contains an integer record number. Call this record 
63537 ** number R. Register P4 is the first in a set of N contiguous registers
63538 ** that make up an unpacked index key that can be used with cursor P1.
63539 ** The value of N can be inferred from the cursor. N includes the rowid
63540 ** value appended to the end of the index record. This rowid value may
63541 ** or may not be the same as R.
63542 **
63543 ** If any of the N registers beginning with register P4 contains a NULL
63544 ** value, jump immediately to P2.
63545 **
63546 ** Otherwise, this instruction checks if cursor P1 contains an entry
63547 ** where the first (N-1) fields match but the rowid value at the end
63548 ** of the index entry is not R. If there is no such entry, control jumps
63549 ** to instruction P2. Otherwise, the rowid of the conflicting index
63550 ** entry is copied to register P3 and control falls through to the next
63551 ** instruction.
63552 **
63553 ** See also: NotFound, NotExists, Found
63554 */
63555 case OP_IsUnique: {        /* jump, in3 */
63556 #if 0  /* local variables moved into u.bc */
63557   u16 ii;
63558   VdbeCursor *pCx;
63559   BtCursor *pCrsr;
63560   u16 nField;
63561   Mem *aMx;
63562   UnpackedRecord r;                  /* B-Tree index search key */
63563   i64 R;                             /* Rowid stored in register P3 */
63564 #endif /* local variables moved into u.bc */
63565
63566   pIn3 = &aMem[pOp->p3];
63567   u.bc.aMx = &aMem[pOp->p4.i];
63568   /* Assert that the values of parameters P1 and P4 are in range. */
63569   assert( pOp->p4type==P4_INT32 );
63570   assert( pOp->p4.i>0 && pOp->p4.i<=p->nMem );
63571   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
63572
63573   /* Find the index cursor. */
63574   u.bc.pCx = p->apCsr[pOp->p1];
63575   assert( u.bc.pCx->deferredMoveto==0 );
63576   u.bc.pCx->seekResult = 0;
63577   u.bc.pCx->cacheStatus = CACHE_STALE;
63578   u.bc.pCrsr = u.bc.pCx->pCursor;
63579
63580   /* If any of the values are NULL, take the jump. */
63581   u.bc.nField = u.bc.pCx->pKeyInfo->nField;
63582   for(u.bc.ii=0; u.bc.ii<u.bc.nField; u.bc.ii++){
63583     if( u.bc.aMx[u.bc.ii].flags & MEM_Null ){
63584       pc = pOp->p2 - 1;
63585       u.bc.pCrsr = 0;
63586       break;
63587     }
63588   }
63589   assert( (u.bc.aMx[u.bc.nField].flags & MEM_Null)==0 );
63590
63591   if( u.bc.pCrsr!=0 ){
63592     /* Populate the index search key. */
63593     u.bc.r.pKeyInfo = u.bc.pCx->pKeyInfo;
63594     u.bc.r.nField = u.bc.nField + 1;
63595     u.bc.r.flags = UNPACKED_PREFIX_SEARCH;
63596     u.bc.r.aMem = u.bc.aMx;
63597 #ifdef SQLITE_DEBUG
63598     { int i; for(i=0; i<u.bc.r.nField; i++) assert( memIsValid(&u.bc.r.aMem[i]) ); }
63599 #endif
63600
63601     /* Extract the value of u.bc.R from register P3. */
63602     sqlite3VdbeMemIntegerify(pIn3);
63603     u.bc.R = pIn3->u.i;
63604
63605     /* Search the B-Tree index. If no conflicting record is found, jump
63606     ** to P2. Otherwise, copy the rowid of the conflicting record to
63607     ** register P3 and fall through to the next instruction.  */
63608     rc = sqlite3BtreeMovetoUnpacked(u.bc.pCrsr, &u.bc.r, 0, 0, &u.bc.pCx->seekResult);
63609     if( (u.bc.r.flags & UNPACKED_PREFIX_SEARCH) || u.bc.r.rowid==u.bc.R ){
63610       pc = pOp->p2 - 1;
63611     }else{
63612       pIn3->u.i = u.bc.r.rowid;
63613     }
63614   }
63615   break;
63616 }
63617
63618 /* Opcode: NotExists P1 P2 P3 * *
63619 **
63620 ** Use the content of register P3 as a integer key.  If a record 
63621 ** with that key does not exist in table of P1, then jump to P2. 
63622 ** If the record does exist, then fall through.  The cursor is left 
63623 ** pointing to the record if it exists.
63624 **
63625 ** The difference between this operation and NotFound is that this
63626 ** operation assumes the key is an integer and that P1 is a table whereas
63627 ** NotFound assumes key is a blob constructed from MakeRecord and
63628 ** P1 is an index.
63629 **
63630 ** See also: Found, NotFound, IsUnique
63631 */
63632 case OP_NotExists: {        /* jump, in3 */
63633 #if 0  /* local variables moved into u.bd */
63634   VdbeCursor *pC;
63635   BtCursor *pCrsr;
63636   int res;
63637   u64 iKey;
63638 #endif /* local variables moved into u.bd */
63639
63640   pIn3 = &aMem[pOp->p3];
63641   assert( pIn3->flags & MEM_Int );
63642   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
63643   u.bd.pC = p->apCsr[pOp->p1];
63644   assert( u.bd.pC!=0 );
63645   assert( u.bd.pC->isTable );
63646   assert( u.bd.pC->pseudoTableReg==0 );
63647   u.bd.pCrsr = u.bd.pC->pCursor;
63648   if( u.bd.pCrsr!=0 ){
63649     u.bd.res = 0;
63650     u.bd.iKey = pIn3->u.i;
63651     rc = sqlite3BtreeMovetoUnpacked(u.bd.pCrsr, 0, u.bd.iKey, 0, &u.bd.res);
63652     u.bd.pC->lastRowid = pIn3->u.i;
63653     u.bd.pC->rowidIsValid = u.bd.res==0 ?1:0;
63654     u.bd.pC->nullRow = 0;
63655     u.bd.pC->cacheStatus = CACHE_STALE;
63656     u.bd.pC->deferredMoveto = 0;
63657     if( u.bd.res!=0 ){
63658       pc = pOp->p2 - 1;
63659       assert( u.bd.pC->rowidIsValid==0 );
63660     }
63661     u.bd.pC->seekResult = u.bd.res;
63662   }else{
63663     /* This happens when an attempt to open a read cursor on the
63664     ** sqlite_master table returns SQLITE_EMPTY.
63665     */
63666     pc = pOp->p2 - 1;
63667     assert( u.bd.pC->rowidIsValid==0 );
63668     u.bd.pC->seekResult = 0;
63669   }
63670   break;
63671 }
63672
63673 /* Opcode: Sequence P1 P2 * * *
63674 **
63675 ** Find the next available sequence number for cursor P1.
63676 ** Write the sequence number into register P2.
63677 ** The sequence number on the cursor is incremented after this
63678 ** instruction.  
63679 */
63680 case OP_Sequence: {           /* out2-prerelease */
63681   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
63682   assert( p->apCsr[pOp->p1]!=0 );
63683   pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
63684   break;
63685 }
63686
63687
63688 /* Opcode: NewRowid P1 P2 P3 * *
63689 **
63690 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
63691 ** The record number is not previously used as a key in the database
63692 ** table that cursor P1 points to.  The new record number is written
63693 ** written to register P2.
63694 **
63695 ** If P3>0 then P3 is a register in the root frame of this VDBE that holds 
63696 ** the largest previously generated record number. No new record numbers are
63697 ** allowed to be less than this value. When this value reaches its maximum, 
63698 ** a SQLITE_FULL error is generated. The P3 register is updated with the '
63699 ** generated record number. This P3 mechanism is used to help implement the
63700 ** AUTOINCREMENT feature.
63701 */
63702 case OP_NewRowid: {           /* out2-prerelease */
63703 #if 0  /* local variables moved into u.be */
63704   i64 v;                 /* The new rowid */
63705   VdbeCursor *pC;        /* Cursor of table to get the new rowid */
63706   int res;               /* Result of an sqlite3BtreeLast() */
63707   int cnt;               /* Counter to limit the number of searches */
63708   Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
63709   VdbeFrame *pFrame;     /* Root frame of VDBE */
63710 #endif /* local variables moved into u.be */
63711
63712   u.be.v = 0;
63713   u.be.res = 0;
63714   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
63715   u.be.pC = p->apCsr[pOp->p1];
63716   assert( u.be.pC!=0 );
63717   if( NEVER(u.be.pC->pCursor==0) ){
63718     /* The zero initialization above is all that is needed */
63719   }else{
63720     /* The next rowid or record number (different terms for the same
63721     ** thing) is obtained in a two-step algorithm.
63722     **
63723     ** First we attempt to find the largest existing rowid and add one
63724     ** to that.  But if the largest existing rowid is already the maximum
63725     ** positive integer, we have to fall through to the second
63726     ** probabilistic algorithm
63727     **
63728     ** The second algorithm is to select a rowid at random and see if
63729     ** it already exists in the table.  If it does not exist, we have
63730     ** succeeded.  If the random rowid does exist, we select a new one
63731     ** and try again, up to 100 times.
63732     */
63733     assert( u.be.pC->isTable );
63734     u.be.cnt = 0;
63735
63736 #ifdef SQLITE_32BIT_ROWID
63737 #   define MAX_ROWID 0x7fffffff
63738 #else
63739     /* Some compilers complain about constants of the form 0x7fffffffffffffff.
63740     ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
63741     ** to provide the constant while making all compilers happy.
63742     */
63743 #   define MAX_ROWID  (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
63744 #endif
63745
63746     if( !u.be.pC->useRandomRowid ){
63747       u.be.v = sqlite3BtreeGetCachedRowid(u.be.pC->pCursor);
63748       if( u.be.v==0 ){
63749         rc = sqlite3BtreeLast(u.be.pC->pCursor, &u.be.res);
63750         if( rc!=SQLITE_OK ){
63751           goto abort_due_to_error;
63752         }
63753         if( u.be.res ){
63754           u.be.v = 1;   /* IMP: R-61914-48074 */
63755         }else{
63756           assert( sqlite3BtreeCursorIsValid(u.be.pC->pCursor) );
63757           rc = sqlite3BtreeKeySize(u.be.pC->pCursor, &u.be.v);
63758           assert( rc==SQLITE_OK );   /* Cannot fail following BtreeLast() */
63759           if( u.be.v==MAX_ROWID ){
63760             u.be.pC->useRandomRowid = 1;
63761           }else{
63762             u.be.v++;   /* IMP: R-29538-34987 */
63763           }
63764         }
63765       }
63766
63767 #ifndef SQLITE_OMIT_AUTOINCREMENT
63768       if( pOp->p3 ){
63769         /* Assert that P3 is a valid memory cell. */
63770         assert( pOp->p3>0 );
63771         if( p->pFrame ){
63772           for(u.be.pFrame=p->pFrame; u.be.pFrame->pParent; u.be.pFrame=u.be.pFrame->pParent);
63773           /* Assert that P3 is a valid memory cell. */
63774           assert( pOp->p3<=u.be.pFrame->nMem );
63775           u.be.pMem = &u.be.pFrame->aMem[pOp->p3];
63776         }else{
63777           /* Assert that P3 is a valid memory cell. */
63778           assert( pOp->p3<=p->nMem );
63779           u.be.pMem = &aMem[pOp->p3];
63780           memAboutToChange(p, u.be.pMem);
63781         }
63782         assert( memIsValid(u.be.pMem) );
63783
63784         REGISTER_TRACE(pOp->p3, u.be.pMem);
63785         sqlite3VdbeMemIntegerify(u.be.pMem);
63786         assert( (u.be.pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
63787         if( u.be.pMem->u.i==MAX_ROWID || u.be.pC->useRandomRowid ){
63788           rc = SQLITE_FULL;   /* IMP: R-12275-61338 */
63789           goto abort_due_to_error;
63790         }
63791         if( u.be.v<u.be.pMem->u.i+1 ){
63792           u.be.v = u.be.pMem->u.i + 1;
63793         }
63794         u.be.pMem->u.i = u.be.v;
63795       }
63796 #endif
63797
63798       sqlite3BtreeSetCachedRowid(u.be.pC->pCursor, u.be.v<MAX_ROWID ? u.be.v+1 : 0);
63799     }
63800     if( u.be.pC->useRandomRowid ){
63801       /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
63802       ** largest possible integer (9223372036854775807) then the database
63803       ** engine starts picking positive candidate ROWIDs at random until
63804       ** it finds one that is not previously used. */
63805       assert( pOp->p3==0 );  /* We cannot be in random rowid mode if this is
63806                              ** an AUTOINCREMENT table. */
63807       /* on the first attempt, simply do one more than previous */
63808       u.be.v = db->lastRowid;
63809       u.be.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
63810       u.be.v++; /* ensure non-zero */
63811       u.be.cnt = 0;
63812       while(   ((rc = sqlite3BtreeMovetoUnpacked(u.be.pC->pCursor, 0, (u64)u.be.v,
63813                                                  0, &u.be.res))==SQLITE_OK)
63814             && (u.be.res==0)
63815             && (++u.be.cnt<100)){
63816         /* collision - try another random rowid */
63817         sqlite3_randomness(sizeof(u.be.v), &u.be.v);
63818         if( u.be.cnt<5 ){
63819           /* try "small" random rowids for the initial attempts */
63820           u.be.v &= 0xffffff;
63821         }else{
63822           u.be.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
63823         }
63824         u.be.v++; /* ensure non-zero */
63825       }
63826       if( rc==SQLITE_OK && u.be.res==0 ){
63827         rc = SQLITE_FULL;   /* IMP: R-38219-53002 */
63828         goto abort_due_to_error;
63829       }
63830       assert( u.be.v>0 );  /* EV: R-40812-03570 */
63831     }
63832     u.be.pC->rowidIsValid = 0;
63833     u.be.pC->deferredMoveto = 0;
63834     u.be.pC->cacheStatus = CACHE_STALE;
63835   }
63836   pOut->u.i = u.be.v;
63837   break;
63838 }
63839
63840 /* Opcode: Insert P1 P2 P3 P4 P5
63841 **
63842 ** Write an entry into the table of cursor P1.  A new entry is
63843 ** created if it doesn't already exist or the data for an existing
63844 ** entry is overwritten.  The data is the value MEM_Blob stored in register
63845 ** number P2. The key is stored in register P3. The key must
63846 ** be a MEM_Int.
63847 **
63848 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
63849 ** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
63850 ** then rowid is stored for subsequent return by the
63851 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
63852 **
63853 ** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
63854 ** the last seek operation (OP_NotExists) was a success, then this
63855 ** operation will not attempt to find the appropriate row before doing
63856 ** the insert but will instead overwrite the row that the cursor is
63857 ** currently pointing to.  Presumably, the prior OP_NotExists opcode
63858 ** has already positioned the cursor correctly.  This is an optimization
63859 ** that boosts performance by avoiding redundant seeks.
63860 **
63861 ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
63862 ** UPDATE operation.  Otherwise (if the flag is clear) then this opcode
63863 ** is part of an INSERT operation.  The difference is only important to
63864 ** the update hook.
63865 **
63866 ** Parameter P4 may point to a string containing the table-name, or
63867 ** may be NULL. If it is not NULL, then the update-hook 
63868 ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
63869 **
63870 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
63871 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
63872 ** and register P2 becomes ephemeral.  If the cursor is changed, the
63873 ** value of register P2 will then change.  Make sure this does not
63874 ** cause any problems.)
63875 **
63876 ** This instruction only works on tables.  The equivalent instruction
63877 ** for indices is OP_IdxInsert.
63878 */
63879 /* Opcode: InsertInt P1 P2 P3 P4 P5
63880 **
63881 ** This works exactly like OP_Insert except that the key is the
63882 ** integer value P3, not the value of the integer stored in register P3.
63883 */
63884 case OP_Insert: 
63885 case OP_InsertInt: {
63886 #if 0  /* local variables moved into u.bf */
63887   Mem *pData;       /* MEM cell holding data for the record to be inserted */
63888   Mem *pKey;        /* MEM cell holding key  for the record */
63889   i64 iKey;         /* The integer ROWID or key for the record to be inserted */
63890   VdbeCursor *pC;   /* Cursor to table into which insert is written */
63891   int nZero;        /* Number of zero-bytes to append */
63892   int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
63893   const char *zDb;  /* database name - used by the update hook */
63894   const char *zTbl; /* Table name - used by the opdate hook */
63895   int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
63896 #endif /* local variables moved into u.bf */
63897
63898   u.bf.pData = &aMem[pOp->p2];
63899   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
63900   assert( memIsValid(u.bf.pData) );
63901   u.bf.pC = p->apCsr[pOp->p1];
63902   assert( u.bf.pC!=0 );
63903   assert( u.bf.pC->pCursor!=0 );
63904   assert( u.bf.pC->pseudoTableReg==0 );
63905   assert( u.bf.pC->isTable );
63906   REGISTER_TRACE(pOp->p2, u.bf.pData);
63907
63908   if( pOp->opcode==OP_Insert ){
63909     u.bf.pKey = &aMem[pOp->p3];
63910     assert( u.bf.pKey->flags & MEM_Int );
63911     assert( memIsValid(u.bf.pKey) );
63912     REGISTER_TRACE(pOp->p3, u.bf.pKey);
63913     u.bf.iKey = u.bf.pKey->u.i;
63914   }else{
63915     assert( pOp->opcode==OP_InsertInt );
63916     u.bf.iKey = pOp->p3;
63917   }
63918
63919   if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
63920   if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = u.bf.iKey;
63921   if( u.bf.pData->flags & MEM_Null ){
63922     u.bf.pData->z = 0;
63923     u.bf.pData->n = 0;
63924   }else{
63925     assert( u.bf.pData->flags & (MEM_Blob|MEM_Str) );
63926   }
63927   u.bf.seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bf.pC->seekResult : 0);
63928   if( u.bf.pData->flags & MEM_Zero ){
63929     u.bf.nZero = u.bf.pData->u.nZero;
63930   }else{
63931     u.bf.nZero = 0;
63932   }
63933   sqlite3BtreeSetCachedRowid(u.bf.pC->pCursor, 0);
63934   rc = sqlite3BtreeInsert(u.bf.pC->pCursor, 0, u.bf.iKey,
63935                           u.bf.pData->z, u.bf.pData->n, u.bf.nZero,
63936                           pOp->p5 & OPFLAG_APPEND, u.bf.seekResult
63937   );
63938   u.bf.pC->rowidIsValid = 0;
63939   u.bf.pC->deferredMoveto = 0;
63940   u.bf.pC->cacheStatus = CACHE_STALE;
63941
63942   /* Invoke the update-hook if required. */
63943   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
63944     u.bf.zDb = db->aDb[u.bf.pC->iDb].zName;
63945     u.bf.zTbl = pOp->p4.z;
63946     u.bf.op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
63947     assert( u.bf.pC->isTable );
63948     db->xUpdateCallback(db->pUpdateArg, u.bf.op, u.bf.zDb, u.bf.zTbl, u.bf.iKey);
63949     assert( u.bf.pC->iDb>=0 );
63950   }
63951   break;
63952 }
63953
63954 /* Opcode: Delete P1 P2 * P4 *
63955 **
63956 ** Delete the record at which the P1 cursor is currently pointing.
63957 **
63958 ** The cursor will be left pointing at either the next or the previous
63959 ** record in the table. If it is left pointing at the next record, then
63960 ** the next Next instruction will be a no-op.  Hence it is OK to delete
63961 ** a record from within an Next loop.
63962 **
63963 ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
63964 ** incremented (otherwise not).
63965 **
63966 ** P1 must not be pseudo-table.  It has to be a real table with
63967 ** multiple rows.
63968 **
63969 ** If P4 is not NULL, then it is the name of the table that P1 is
63970 ** pointing to.  The update hook will be invoked, if it exists.
63971 ** If P4 is not NULL then the P1 cursor must have been positioned
63972 ** using OP_NotFound prior to invoking this opcode.
63973 */
63974 case OP_Delete: {
63975 #if 0  /* local variables moved into u.bg */
63976   i64 iKey;
63977   VdbeCursor *pC;
63978 #endif /* local variables moved into u.bg */
63979
63980   u.bg.iKey = 0;
63981   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
63982   u.bg.pC = p->apCsr[pOp->p1];
63983   assert( u.bg.pC!=0 );
63984   assert( u.bg.pC->pCursor!=0 );  /* Only valid for real tables, no pseudotables */
63985
63986   /* If the update-hook will be invoked, set u.bg.iKey to the rowid of the
63987   ** row being deleted.
63988   */
63989   if( db->xUpdateCallback && pOp->p4.z ){
63990     assert( u.bg.pC->isTable );
63991     assert( u.bg.pC->rowidIsValid );  /* lastRowid set by previous OP_NotFound */
63992     u.bg.iKey = u.bg.pC->lastRowid;
63993   }
63994
63995   /* The OP_Delete opcode always follows an OP_NotExists or OP_Last or
63996   ** OP_Column on the same table without any intervening operations that
63997   ** might move or invalidate the cursor.  Hence cursor u.bg.pC is always pointing
63998   ** to the row to be deleted and the sqlite3VdbeCursorMoveto() operation
63999   ** below is always a no-op and cannot fail.  We will run it anyhow, though,
64000   ** to guard against future changes to the code generator.
64001   **/
64002   assert( u.bg.pC->deferredMoveto==0 );
64003   rc = sqlite3VdbeCursorMoveto(u.bg.pC);
64004   if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
64005
64006   sqlite3BtreeSetCachedRowid(u.bg.pC->pCursor, 0);
64007   rc = sqlite3BtreeDelete(u.bg.pC->pCursor);
64008   u.bg.pC->cacheStatus = CACHE_STALE;
64009
64010   /* Invoke the update-hook if required. */
64011   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
64012     const char *zDb = db->aDb[u.bg.pC->iDb].zName;
64013     const char *zTbl = pOp->p4.z;
64014     db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, u.bg.iKey);
64015     assert( u.bg.pC->iDb>=0 );
64016   }
64017   if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
64018   break;
64019 }
64020 /* Opcode: ResetCount * * * * *
64021 **
64022 ** The value of the change counter is copied to the database handle
64023 ** change counter (returned by subsequent calls to sqlite3_changes()).
64024 ** Then the VMs internal change counter resets to 0.
64025 ** This is used by trigger programs.
64026 */
64027 case OP_ResetCount: {
64028   sqlite3VdbeSetChanges(db, p->nChange);
64029   p->nChange = 0;
64030   break;
64031 }
64032
64033 /* Opcode: RowData P1 P2 * * *
64034 **
64035 ** Write into register P2 the complete row data for cursor P1.
64036 ** There is no interpretation of the data.  
64037 ** It is just copied onto the P2 register exactly as 
64038 ** it is found in the database file.
64039 **
64040 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
64041 ** of a real table, not a pseudo-table.
64042 */
64043 /* Opcode: RowKey P1 P2 * * *
64044 **
64045 ** Write into register P2 the complete row key for cursor P1.
64046 ** There is no interpretation of the data.  
64047 ** The key is copied onto the P3 register exactly as 
64048 ** it is found in the database file.
64049 **
64050 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
64051 ** of a real table, not a pseudo-table.
64052 */
64053 case OP_RowKey:
64054 case OP_RowData: {
64055 #if 0  /* local variables moved into u.bh */
64056   VdbeCursor *pC;
64057   BtCursor *pCrsr;
64058   u32 n;
64059   i64 n64;
64060 #endif /* local variables moved into u.bh */
64061
64062   pOut = &aMem[pOp->p2];
64063   memAboutToChange(p, pOut);
64064
64065   /* Note that RowKey and RowData are really exactly the same instruction */
64066   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
64067   u.bh.pC = p->apCsr[pOp->p1];
64068   assert( u.bh.pC->isTable || pOp->opcode==OP_RowKey );
64069   assert( u.bh.pC->isIndex || pOp->opcode==OP_RowData );
64070   assert( u.bh.pC!=0 );
64071   assert( u.bh.pC->nullRow==0 );
64072   assert( u.bh.pC->pseudoTableReg==0 );
64073   assert( u.bh.pC->pCursor!=0 );
64074   u.bh.pCrsr = u.bh.pC->pCursor;
64075   assert( sqlite3BtreeCursorIsValid(u.bh.pCrsr) );
64076
64077   /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
64078   ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
64079   ** the cursor.  Hence the following sqlite3VdbeCursorMoveto() call is always
64080   ** a no-op and can never fail.  But we leave it in place as a safety.
64081   */
64082   assert( u.bh.pC->deferredMoveto==0 );
64083   rc = sqlite3VdbeCursorMoveto(u.bh.pC);
64084   if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
64085
64086   if( u.bh.pC->isIndex ){
64087     assert( !u.bh.pC->isTable );
64088     rc = sqlite3BtreeKeySize(u.bh.pCrsr, &u.bh.n64);
64089     assert( rc==SQLITE_OK );    /* True because of CursorMoveto() call above */
64090     if( u.bh.n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
64091       goto too_big;
64092     }
64093     u.bh.n = (u32)u.bh.n64;
64094   }else{
64095     rc = sqlite3BtreeDataSize(u.bh.pCrsr, &u.bh.n);
64096     assert( rc==SQLITE_OK );    /* DataSize() cannot fail */
64097     if( u.bh.n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
64098       goto too_big;
64099     }
64100   }
64101   if( sqlite3VdbeMemGrow(pOut, u.bh.n, 0) ){
64102     goto no_mem;
64103   }
64104   pOut->n = u.bh.n;
64105   MemSetTypeFlag(pOut, MEM_Blob);
64106   if( u.bh.pC->isIndex ){
64107     rc = sqlite3BtreeKey(u.bh.pCrsr, 0, u.bh.n, pOut->z);
64108   }else{
64109     rc = sqlite3BtreeData(u.bh.pCrsr, 0, u.bh.n, pOut->z);
64110   }
64111   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever cast to text */
64112   UPDATE_MAX_BLOBSIZE(pOut);
64113   break;
64114 }
64115
64116 /* Opcode: Rowid P1 P2 * * *
64117 **
64118 ** Store in register P2 an integer which is the key of the table entry that
64119 ** P1 is currently point to.
64120 **
64121 ** P1 can be either an ordinary table or a virtual table.  There used to
64122 ** be a separate OP_VRowid opcode for use with virtual tables, but this
64123 ** one opcode now works for both table types.
64124 */
64125 case OP_Rowid: {                 /* out2-prerelease */
64126 #if 0  /* local variables moved into u.bi */
64127   VdbeCursor *pC;
64128   i64 v;
64129   sqlite3_vtab *pVtab;
64130   const sqlite3_module *pModule;
64131 #endif /* local variables moved into u.bi */
64132
64133   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
64134   u.bi.pC = p->apCsr[pOp->p1];
64135   assert( u.bi.pC!=0 );
64136   assert( u.bi.pC->pseudoTableReg==0 );
64137   if( u.bi.pC->nullRow ){
64138     pOut->flags = MEM_Null;
64139     break;
64140   }else if( u.bi.pC->deferredMoveto ){
64141     u.bi.v = u.bi.pC->movetoTarget;
64142 #ifndef SQLITE_OMIT_VIRTUALTABLE
64143   }else if( u.bi.pC->pVtabCursor ){
64144     u.bi.pVtab = u.bi.pC->pVtabCursor->pVtab;
64145     u.bi.pModule = u.bi.pVtab->pModule;
64146     assert( u.bi.pModule->xRowid );
64147     rc = u.bi.pModule->xRowid(u.bi.pC->pVtabCursor, &u.bi.v);
64148     importVtabErrMsg(p, u.bi.pVtab);
64149 #endif /* SQLITE_OMIT_VIRTUALTABLE */
64150   }else{
64151     assert( u.bi.pC->pCursor!=0 );
64152     rc = sqlite3VdbeCursorMoveto(u.bi.pC);
64153     if( rc ) goto abort_due_to_error;
64154     if( u.bi.pC->rowidIsValid ){
64155       u.bi.v = u.bi.pC->lastRowid;
64156     }else{
64157       rc = sqlite3BtreeKeySize(u.bi.pC->pCursor, &u.bi.v);
64158       assert( rc==SQLITE_OK );  /* Always so because of CursorMoveto() above */
64159     }
64160   }
64161   pOut->u.i = u.bi.v;
64162   break;
64163 }
64164
64165 /* Opcode: NullRow P1 * * * *
64166 **
64167 ** Move the cursor P1 to a null row.  Any OP_Column operations
64168 ** that occur while the cursor is on the null row will always
64169 ** write a NULL.
64170 */
64171 case OP_NullRow: {
64172 #if 0  /* local variables moved into u.bj */
64173   VdbeCursor *pC;
64174 #endif /* local variables moved into u.bj */
64175
64176   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
64177   u.bj.pC = p->apCsr[pOp->p1];
64178   assert( u.bj.pC!=0 );
64179   u.bj.pC->nullRow = 1;
64180   u.bj.pC->rowidIsValid = 0;
64181   if( u.bj.pC->pCursor ){
64182     sqlite3BtreeClearCursor(u.bj.pC->pCursor);
64183   }
64184   break;
64185 }
64186
64187 /* Opcode: Last P1 P2 * * *
64188 **
64189 ** The next use of the Rowid or Column or Next instruction for P1 
64190 ** will refer to the last entry in the database table or index.
64191 ** If the table or index is empty and P2>0, then jump immediately to P2.
64192 ** If P2 is 0 or if the table or index is not empty, fall through
64193 ** to the following instruction.
64194 */
64195 case OP_Last: {        /* jump */
64196 #if 0  /* local variables moved into u.bk */
64197   VdbeCursor *pC;
64198   BtCursor *pCrsr;
64199   int res;
64200 #endif /* local variables moved into u.bk */
64201
64202   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
64203   u.bk.pC = p->apCsr[pOp->p1];
64204   assert( u.bk.pC!=0 );
64205   u.bk.pCrsr = u.bk.pC->pCursor;
64206   if( u.bk.pCrsr==0 ){
64207     u.bk.res = 1;
64208   }else{
64209     rc = sqlite3BtreeLast(u.bk.pCrsr, &u.bk.res);
64210   }
64211   u.bk.pC->nullRow = (u8)u.bk.res;
64212   u.bk.pC->deferredMoveto = 0;
64213   u.bk.pC->rowidIsValid = 0;
64214   u.bk.pC->cacheStatus = CACHE_STALE;
64215   if( pOp->p2>0 && u.bk.res ){
64216     pc = pOp->p2 - 1;
64217   }
64218   break;
64219 }
64220
64221
64222 /* Opcode: Sort P1 P2 * * *
64223 **
64224 ** This opcode does exactly the same thing as OP_Rewind except that
64225 ** it increments an undocumented global variable used for testing.
64226 **
64227 ** Sorting is accomplished by writing records into a sorting index,
64228 ** then rewinding that index and playing it back from beginning to
64229 ** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
64230 ** rewinding so that the global variable will be incremented and
64231 ** regression tests can determine whether or not the optimizer is
64232 ** correctly optimizing out sorts.
64233 */
64234 case OP_Sort: {        /* jump */
64235 #ifdef SQLITE_TEST
64236   sqlite3_sort_count++;
64237   sqlite3_search_count--;
64238 #endif
64239   p->aCounter[SQLITE_STMTSTATUS_SORT-1]++;
64240   /* Fall through into OP_Rewind */
64241 }
64242 /* Opcode: Rewind P1 P2 * * *
64243 **
64244 ** The next use of the Rowid or Column or Next instruction for P1 
64245 ** will refer to the first entry in the database table or index.
64246 ** If the table or index is empty and P2>0, then jump immediately to P2.
64247 ** If P2 is 0 or if the table or index is not empty, fall through
64248 ** to the following instruction.
64249 */
64250 case OP_Rewind: {        /* jump */
64251 #if 0  /* local variables moved into u.bl */
64252   VdbeCursor *pC;
64253   BtCursor *pCrsr;
64254   int res;
64255 #endif /* local variables moved into u.bl */
64256
64257   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
64258   u.bl.pC = p->apCsr[pOp->p1];
64259   assert( u.bl.pC!=0 );
64260   u.bl.res = 1;
64261   if( (u.bl.pCrsr = u.bl.pC->pCursor)!=0 ){
64262     rc = sqlite3BtreeFirst(u.bl.pCrsr, &u.bl.res);
64263     u.bl.pC->atFirst = u.bl.res==0 ?1:0;
64264     u.bl.pC->deferredMoveto = 0;
64265     u.bl.pC->cacheStatus = CACHE_STALE;
64266     u.bl.pC->rowidIsValid = 0;
64267   }
64268   u.bl.pC->nullRow = (u8)u.bl.res;
64269   assert( pOp->p2>0 && pOp->p2<p->nOp );
64270   if( u.bl.res ){
64271     pc = pOp->p2 - 1;
64272   }
64273   break;
64274 }
64275
64276 /* Opcode: Next P1 P2 * * P5
64277 **
64278 ** Advance cursor P1 so that it points to the next key/data pair in its
64279 ** table or index.  If there are no more key/value pairs then fall through
64280 ** to the following instruction.  But if the cursor advance was successful,
64281 ** jump immediately to P2.
64282 **
64283 ** The P1 cursor must be for a real table, not a pseudo-table.
64284 **
64285 ** If P5 is positive and the jump is taken, then event counter
64286 ** number P5-1 in the prepared statement is incremented.
64287 **
64288 ** See also: Prev
64289 */
64290 /* Opcode: Prev P1 P2 * * P5
64291 **
64292 ** Back up cursor P1 so that it points to the previous key/data pair in its
64293 ** table or index.  If there is no previous key/value pairs then fall through
64294 ** to the following instruction.  But if the cursor backup was successful,
64295 ** jump immediately to P2.
64296 **
64297 ** The P1 cursor must be for a real table, not a pseudo-table.
64298 **
64299 ** If P5 is positive and the jump is taken, then event counter
64300 ** number P5-1 in the prepared statement is incremented.
64301 */
64302 case OP_Prev:          /* jump */
64303 case OP_Next: {        /* jump */
64304 #if 0  /* local variables moved into u.bm */
64305   VdbeCursor *pC;
64306   BtCursor *pCrsr;
64307   int res;
64308 #endif /* local variables moved into u.bm */
64309
64310   CHECK_FOR_INTERRUPT;
64311   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
64312   assert( pOp->p5<=ArraySize(p->aCounter) );
64313   u.bm.pC = p->apCsr[pOp->p1];
64314   if( u.bm.pC==0 ){
64315     break;  /* See ticket #2273 */
64316   }
64317   u.bm.pCrsr = u.bm.pC->pCursor;
64318   if( u.bm.pCrsr==0 ){
64319     u.bm.pC->nullRow = 1;
64320     break;
64321   }
64322   u.bm.res = 1;
64323   assert( u.bm.pC->deferredMoveto==0 );
64324   rc = pOp->opcode==OP_Next ? sqlite3BtreeNext(u.bm.pCrsr, &u.bm.res) :
64325                               sqlite3BtreePrevious(u.bm.pCrsr, &u.bm.res);
64326   u.bm.pC->nullRow = (u8)u.bm.res;
64327   u.bm.pC->cacheStatus = CACHE_STALE;
64328   if( u.bm.res==0 ){
64329     pc = pOp->p2 - 1;
64330     if( pOp->p5 ) p->aCounter[pOp->p5-1]++;
64331 #ifdef SQLITE_TEST
64332     sqlite3_search_count++;
64333 #endif
64334   }
64335   u.bm.pC->rowidIsValid = 0;
64336   break;
64337 }
64338
64339 /* Opcode: IdxInsert P1 P2 P3 * P5
64340 **
64341 ** Register P2 holds a SQL index key made using the
64342 ** MakeRecord instructions.  This opcode writes that key
64343 ** into the index P1.  Data for the entry is nil.
64344 **
64345 ** P3 is a flag that provides a hint to the b-tree layer that this
64346 ** insert is likely to be an append.
64347 **
64348 ** This instruction only works for indices.  The equivalent instruction
64349 ** for tables is OP_Insert.
64350 */
64351 case OP_IdxInsert: {        /* in2 */
64352 #if 0  /* local variables moved into u.bn */
64353   VdbeCursor *pC;
64354   BtCursor *pCrsr;
64355   int nKey;
64356   const char *zKey;
64357 #endif /* local variables moved into u.bn */
64358
64359   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
64360   u.bn.pC = p->apCsr[pOp->p1];
64361   assert( u.bn.pC!=0 );
64362   pIn2 = &aMem[pOp->p2];
64363   assert( pIn2->flags & MEM_Blob );
64364   u.bn.pCrsr = u.bn.pC->pCursor;
64365   if( ALWAYS(u.bn.pCrsr!=0) ){
64366     assert( u.bn.pC->isTable==0 );
64367     rc = ExpandBlob(pIn2);
64368     if( rc==SQLITE_OK ){
64369       u.bn.nKey = pIn2->n;
64370       u.bn.zKey = pIn2->z;
64371       rc = sqlite3BtreeInsert(u.bn.pCrsr, u.bn.zKey, u.bn.nKey, "", 0, 0, pOp->p3,
64372           ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bn.pC->seekResult : 0)
64373       );
64374       assert( u.bn.pC->deferredMoveto==0 );
64375       u.bn.pC->cacheStatus = CACHE_STALE;
64376     }
64377   }
64378   break;
64379 }
64380
64381 /* Opcode: IdxDelete P1 P2 P3 * *
64382 **
64383 ** The content of P3 registers starting at register P2 form
64384 ** an unpacked index key. This opcode removes that entry from the 
64385 ** index opened by cursor P1.
64386 */
64387 case OP_IdxDelete: {
64388 #if 0  /* local variables moved into u.bo */
64389   VdbeCursor *pC;
64390   BtCursor *pCrsr;
64391   int res;
64392   UnpackedRecord r;
64393 #endif /* local variables moved into u.bo */
64394
64395   assert( pOp->p3>0 );
64396   assert( pOp->p2>0 && pOp->p2+pOp->p3<=p->nMem+1 );
64397   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
64398   u.bo.pC = p->apCsr[pOp->p1];
64399   assert( u.bo.pC!=0 );
64400   u.bo.pCrsr = u.bo.pC->pCursor;
64401   if( ALWAYS(u.bo.pCrsr!=0) ){
64402     u.bo.r.pKeyInfo = u.bo.pC->pKeyInfo;
64403     u.bo.r.nField = (u16)pOp->p3;
64404     u.bo.r.flags = 0;
64405     u.bo.r.aMem = &aMem[pOp->p2];
64406 #ifdef SQLITE_DEBUG
64407     { int i; for(i=0; i<u.bo.r.nField; i++) assert( memIsValid(&u.bo.r.aMem[i]) ); }
64408 #endif
64409     rc = sqlite3BtreeMovetoUnpacked(u.bo.pCrsr, &u.bo.r, 0, 0, &u.bo.res);
64410     if( rc==SQLITE_OK && u.bo.res==0 ){
64411       rc = sqlite3BtreeDelete(u.bo.pCrsr);
64412     }
64413     assert( u.bo.pC->deferredMoveto==0 );
64414     u.bo.pC->cacheStatus = CACHE_STALE;
64415   }
64416   break;
64417 }
64418
64419 /* Opcode: IdxRowid P1 P2 * * *
64420 **
64421 ** Write into register P2 an integer which is the last entry in the record at
64422 ** the end of the index key pointed to by cursor P1.  This integer should be
64423 ** the rowid of the table entry to which this index entry points.
64424 **
64425 ** See also: Rowid, MakeRecord.
64426 */
64427 case OP_IdxRowid: {              /* out2-prerelease */
64428 #if 0  /* local variables moved into u.bp */
64429   BtCursor *pCrsr;
64430   VdbeCursor *pC;
64431   i64 rowid;
64432 #endif /* local variables moved into u.bp */
64433
64434   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
64435   u.bp.pC = p->apCsr[pOp->p1];
64436   assert( u.bp.pC!=0 );
64437   u.bp.pCrsr = u.bp.pC->pCursor;
64438   pOut->flags = MEM_Null;
64439   if( ALWAYS(u.bp.pCrsr!=0) ){
64440     rc = sqlite3VdbeCursorMoveto(u.bp.pC);
64441     if( NEVER(rc) ) goto abort_due_to_error;
64442     assert( u.bp.pC->deferredMoveto==0 );
64443     assert( u.bp.pC->isTable==0 );
64444     if( !u.bp.pC->nullRow ){
64445       rc = sqlite3VdbeIdxRowid(db, u.bp.pCrsr, &u.bp.rowid);
64446       if( rc!=SQLITE_OK ){
64447         goto abort_due_to_error;
64448       }
64449       pOut->u.i = u.bp.rowid;
64450       pOut->flags = MEM_Int;
64451     }
64452   }
64453   break;
64454 }
64455
64456 /* Opcode: IdxGE P1 P2 P3 P4 P5
64457 **
64458 ** The P4 register values beginning with P3 form an unpacked index 
64459 ** key that omits the ROWID.  Compare this key value against the index 
64460 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
64461 **
64462 ** If the P1 index entry is greater than or equal to the key value
64463 ** then jump to P2.  Otherwise fall through to the next instruction.
64464 **
64465 ** If P5 is non-zero then the key value is increased by an epsilon 
64466 ** prior to the comparison.  This make the opcode work like IdxGT except
64467 ** that if the key from register P3 is a prefix of the key in the cursor,
64468 ** the result is false whereas it would be true with IdxGT.
64469 */
64470 /* Opcode: IdxLT P1 P2 P3 P4 P5
64471 **
64472 ** The P4 register values beginning with P3 form an unpacked index 
64473 ** key that omits the ROWID.  Compare this key value against the index 
64474 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
64475 **
64476 ** If the P1 index entry is less than the key value then jump to P2.
64477 ** Otherwise fall through to the next instruction.
64478 **
64479 ** If P5 is non-zero then the key value is increased by an epsilon prior 
64480 ** to the comparison.  This makes the opcode work like IdxLE.
64481 */
64482 case OP_IdxLT:          /* jump */
64483 case OP_IdxGE: {        /* jump */
64484 #if 0  /* local variables moved into u.bq */
64485   VdbeCursor *pC;
64486   int res;
64487   UnpackedRecord r;
64488 #endif /* local variables moved into u.bq */
64489
64490   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
64491   u.bq.pC = p->apCsr[pOp->p1];
64492   assert( u.bq.pC!=0 );
64493   assert( u.bq.pC->isOrdered );
64494   if( ALWAYS(u.bq.pC->pCursor!=0) ){
64495     assert( u.bq.pC->deferredMoveto==0 );
64496     assert( pOp->p5==0 || pOp->p5==1 );
64497     assert( pOp->p4type==P4_INT32 );
64498     u.bq.r.pKeyInfo = u.bq.pC->pKeyInfo;
64499     u.bq.r.nField = (u16)pOp->p4.i;
64500     if( pOp->p5 ){
64501       u.bq.r.flags = UNPACKED_INCRKEY | UNPACKED_IGNORE_ROWID;
64502     }else{
64503       u.bq.r.flags = UNPACKED_IGNORE_ROWID;
64504     }
64505     u.bq.r.aMem = &aMem[pOp->p3];
64506 #ifdef SQLITE_DEBUG
64507     { int i; for(i=0; i<u.bq.r.nField; i++) assert( memIsValid(&u.bq.r.aMem[i]) ); }
64508 #endif
64509     rc = sqlite3VdbeIdxKeyCompare(u.bq.pC, &u.bq.r, &u.bq.res);
64510     if( pOp->opcode==OP_IdxLT ){
64511       u.bq.res = -u.bq.res;
64512     }else{
64513       assert( pOp->opcode==OP_IdxGE );
64514       u.bq.res++;
64515     }
64516     if( u.bq.res>0 ){
64517       pc = pOp->p2 - 1 ;
64518     }
64519   }
64520   break;
64521 }
64522
64523 /* Opcode: Destroy P1 P2 P3 * *
64524 **
64525 ** Delete an entire database table or index whose root page in the database
64526 ** file is given by P1.
64527 **
64528 ** The table being destroyed is in the main database file if P3==0.  If
64529 ** P3==1 then the table to be clear is in the auxiliary database file
64530 ** that is used to store tables create using CREATE TEMPORARY TABLE.
64531 **
64532 ** If AUTOVACUUM is enabled then it is possible that another root page
64533 ** might be moved into the newly deleted root page in order to keep all
64534 ** root pages contiguous at the beginning of the database.  The former
64535 ** value of the root page that moved - its value before the move occurred -
64536 ** is stored in register P2.  If no page 
64537 ** movement was required (because the table being dropped was already 
64538 ** the last one in the database) then a zero is stored in register P2.
64539 ** If AUTOVACUUM is disabled then a zero is stored in register P2.
64540 **
64541 ** See also: Clear
64542 */
64543 case OP_Destroy: {     /* out2-prerelease */
64544 #if 0  /* local variables moved into u.br */
64545   int iMoved;
64546   int iCnt;
64547   Vdbe *pVdbe;
64548   int iDb;
64549 #endif /* local variables moved into u.br */
64550 #ifndef SQLITE_OMIT_VIRTUALTABLE
64551   u.br.iCnt = 0;
64552   for(u.br.pVdbe=db->pVdbe; u.br.pVdbe; u.br.pVdbe = u.br.pVdbe->pNext){
64553     if( u.br.pVdbe->magic==VDBE_MAGIC_RUN && u.br.pVdbe->inVtabMethod<2 && u.br.pVdbe->pc>=0 ){
64554       u.br.iCnt++;
64555     }
64556   }
64557 #else
64558   u.br.iCnt = db->activeVdbeCnt;
64559 #endif
64560   pOut->flags = MEM_Null;
64561   if( u.br.iCnt>1 ){
64562     rc = SQLITE_LOCKED;
64563     p->errorAction = OE_Abort;
64564   }else{
64565     u.br.iDb = pOp->p3;
64566     assert( u.br.iCnt==1 );
64567     assert( (p->btreeMask & (1<<u.br.iDb))!=0 );
64568     rc = sqlite3BtreeDropTable(db->aDb[u.br.iDb].pBt, pOp->p1, &u.br.iMoved);
64569     pOut->flags = MEM_Int;
64570     pOut->u.i = u.br.iMoved;
64571 #ifndef SQLITE_OMIT_AUTOVACUUM
64572     if( rc==SQLITE_OK && u.br.iMoved!=0 ){
64573       sqlite3RootPageMoved(&db->aDb[u.br.iDb], u.br.iMoved, pOp->p1);
64574       resetSchemaOnFault = 1;
64575     }
64576 #endif
64577   }
64578   break;
64579 }
64580
64581 /* Opcode: Clear P1 P2 P3
64582 **
64583 ** Delete all contents of the database table or index whose root page
64584 ** in the database file is given by P1.  But, unlike Destroy, do not
64585 ** remove the table or index from the database file.
64586 **
64587 ** The table being clear is in the main database file if P2==0.  If
64588 ** P2==1 then the table to be clear is in the auxiliary database file
64589 ** that is used to store tables create using CREATE TEMPORARY TABLE.
64590 **
64591 ** If the P3 value is non-zero, then the table referred to must be an
64592 ** intkey table (an SQL table, not an index). In this case the row change 
64593 ** count is incremented by the number of rows in the table being cleared. 
64594 ** If P3 is greater than zero, then the value stored in register P3 is
64595 ** also incremented by the number of rows in the table being cleared.
64596 **
64597 ** See also: Destroy
64598 */
64599 case OP_Clear: {
64600 #if 0  /* local variables moved into u.bs */
64601   int nChange;
64602 #endif /* local variables moved into u.bs */
64603
64604   u.bs.nChange = 0;
64605   assert( (p->btreeMask & (1<<pOp->p2))!=0 );
64606   rc = sqlite3BtreeClearTable(
64607       db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &u.bs.nChange : 0)
64608   );
64609   if( pOp->p3 ){
64610     p->nChange += u.bs.nChange;
64611     if( pOp->p3>0 ){
64612       assert( memIsValid(&aMem[pOp->p3]) );
64613       memAboutToChange(p, &aMem[pOp->p3]);
64614       aMem[pOp->p3].u.i += u.bs.nChange;
64615     }
64616   }
64617   break;
64618 }
64619
64620 /* Opcode: CreateTable P1 P2 * * *
64621 **
64622 ** Allocate a new table in the main database file if P1==0 or in the
64623 ** auxiliary database file if P1==1 or in an attached database if
64624 ** P1>1.  Write the root page number of the new table into
64625 ** register P2
64626 **
64627 ** The difference between a table and an index is this:  A table must
64628 ** have a 4-byte integer key and can have arbitrary data.  An index
64629 ** has an arbitrary key but no data.
64630 **
64631 ** See also: CreateIndex
64632 */
64633 /* Opcode: CreateIndex P1 P2 * * *
64634 **
64635 ** Allocate a new index in the main database file if P1==0 or in the
64636 ** auxiliary database file if P1==1 or in an attached database if
64637 ** P1>1.  Write the root page number of the new table into
64638 ** register P2.
64639 **
64640 ** See documentation on OP_CreateTable for additional information.
64641 */
64642 case OP_CreateIndex:            /* out2-prerelease */
64643 case OP_CreateTable: {          /* out2-prerelease */
64644 #if 0  /* local variables moved into u.bt */
64645   int pgno;
64646   int flags;
64647   Db *pDb;
64648 #endif /* local variables moved into u.bt */
64649
64650   u.bt.pgno = 0;
64651   assert( pOp->p1>=0 && pOp->p1<db->nDb );
64652   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
64653   u.bt.pDb = &db->aDb[pOp->p1];
64654   assert( u.bt.pDb->pBt!=0 );
64655   if( pOp->opcode==OP_CreateTable ){
64656     /* u.bt.flags = BTREE_INTKEY; */
64657     u.bt.flags = BTREE_INTKEY;
64658   }else{
64659     u.bt.flags = BTREE_BLOBKEY;
64660   }
64661   rc = sqlite3BtreeCreateTable(u.bt.pDb->pBt, &u.bt.pgno, u.bt.flags);
64662   pOut->u.i = u.bt.pgno;
64663   break;
64664 }
64665
64666 /* Opcode: ParseSchema P1 P2 * P4 *
64667 **
64668 ** Read and parse all entries from the SQLITE_MASTER table of database P1
64669 ** that match the WHERE clause P4.  P2 is the "force" flag.   Always do
64670 ** the parsing if P2 is true.  If P2 is false, then this routine is a
64671 ** no-op if the schema is not currently loaded.  In other words, if P2
64672 ** is false, the SQLITE_MASTER table is only parsed if the rest of the
64673 ** schema is already loaded into the symbol table.
64674 **
64675 ** This opcode invokes the parser to create a new virtual machine,
64676 ** then runs the new virtual machine.  It is thus a re-entrant opcode.
64677 */
64678 case OP_ParseSchema: {
64679 #if 0  /* local variables moved into u.bu */
64680   int iDb;
64681   const char *zMaster;
64682   char *zSql;
64683   InitData initData;
64684 #endif /* local variables moved into u.bu */
64685
64686   u.bu.iDb = pOp->p1;
64687   assert( u.bu.iDb>=0 && u.bu.iDb<db->nDb );
64688
64689   /* If pOp->p2 is 0, then this opcode is being executed to read a
64690   ** single row, for example the row corresponding to a new index
64691   ** created by this VDBE, from the sqlite_master table. It only
64692   ** does this if the corresponding in-memory schema is currently
64693   ** loaded. Otherwise, the new index definition can be loaded along
64694   ** with the rest of the schema when it is required.
64695   **
64696   ** Although the mutex on the BtShared object that corresponds to
64697   ** database u.bu.iDb (the database containing the sqlite_master table
64698   ** read by this instruction) is currently held, it is necessary to
64699   ** obtain the mutexes on all attached databases before checking if
64700   ** the schema of u.bu.iDb is loaded. This is because, at the start of
64701   ** the sqlite3_exec() call below, SQLite will invoke
64702   ** sqlite3BtreeEnterAll(). If all mutexes are not already held, the
64703   ** u.bu.iDb mutex may be temporarily released to avoid deadlock. If
64704   ** this happens, then some other thread may delete the in-memory
64705   ** schema of database u.bu.iDb before the SQL statement runs. The schema
64706   ** will not be reloaded becuase the db->init.busy flag is set. This
64707   ** can result in a "no such table: sqlite_master" or "malformed
64708   ** database schema" error being returned to the user.
64709   */
64710   assert( sqlite3BtreeHoldsMutex(db->aDb[u.bu.iDb].pBt) );
64711   sqlite3BtreeEnterAll(db);
64712   if( pOp->p2 || DbHasProperty(db, u.bu.iDb, DB_SchemaLoaded) ){
64713     u.bu.zMaster = SCHEMA_TABLE(u.bu.iDb);
64714     u.bu.initData.db = db;
64715     u.bu.initData.iDb = pOp->p1;
64716     u.bu.initData.pzErrMsg = &p->zErrMsg;
64717     u.bu.zSql = sqlite3MPrintf(db,
64718        "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
64719        db->aDb[u.bu.iDb].zName, u.bu.zMaster, pOp->p4.z);
64720     if( u.bu.zSql==0 ){
64721       rc = SQLITE_NOMEM;
64722     }else{
64723       assert( db->init.busy==0 );
64724       db->init.busy = 1;
64725       u.bu.initData.rc = SQLITE_OK;
64726       assert( !db->mallocFailed );
64727       rc = sqlite3_exec(db, u.bu.zSql, sqlite3InitCallback, &u.bu.initData, 0);
64728       if( rc==SQLITE_OK ) rc = u.bu.initData.rc;
64729       sqlite3DbFree(db, u.bu.zSql);
64730       db->init.busy = 0;
64731     }
64732   }
64733   sqlite3BtreeLeaveAll(db);
64734   if( rc==SQLITE_NOMEM ){
64735     goto no_mem;
64736   }
64737   break;
64738 }
64739
64740 #if !defined(SQLITE_OMIT_ANALYZE)
64741 /* Opcode: LoadAnalysis P1 * * * *
64742 **
64743 ** Read the sqlite_stat1 table for database P1 and load the content
64744 ** of that table into the internal index hash table.  This will cause
64745 ** the analysis to be used when preparing all subsequent queries.
64746 */
64747 case OP_LoadAnalysis: {
64748   assert( pOp->p1>=0 && pOp->p1<db->nDb );
64749   rc = sqlite3AnalysisLoad(db, pOp->p1);
64750   break;  
64751 }
64752 #endif /* !defined(SQLITE_OMIT_ANALYZE) */
64753
64754 /* Opcode: DropTable P1 * * P4 *
64755 **
64756 ** Remove the internal (in-memory) data structures that describe
64757 ** the table named P4 in database P1.  This is called after a table
64758 ** is dropped in order to keep the internal representation of the
64759 ** schema consistent with what is on disk.
64760 */
64761 case OP_DropTable: {
64762   sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
64763   break;
64764 }
64765
64766 /* Opcode: DropIndex P1 * * P4 *
64767 **
64768 ** Remove the internal (in-memory) data structures that describe
64769 ** the index named P4 in database P1.  This is called after an index
64770 ** is dropped in order to keep the internal representation of the
64771 ** schema consistent with what is on disk.
64772 */
64773 case OP_DropIndex: {
64774   sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
64775   break;
64776 }
64777
64778 /* Opcode: DropTrigger P1 * * P4 *
64779 **
64780 ** Remove the internal (in-memory) data structures that describe
64781 ** the trigger named P4 in database P1.  This is called after a trigger
64782 ** is dropped in order to keep the internal representation of the
64783 ** schema consistent with what is on disk.
64784 */
64785 case OP_DropTrigger: {
64786   sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
64787   break;
64788 }
64789
64790
64791 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
64792 /* Opcode: IntegrityCk P1 P2 P3 * P5
64793 **
64794 ** Do an analysis of the currently open database.  Store in
64795 ** register P1 the text of an error message describing any problems.
64796 ** If no problems are found, store a NULL in register P1.
64797 **
64798 ** The register P3 contains the maximum number of allowed errors.
64799 ** At most reg(P3) errors will be reported.
64800 ** In other words, the analysis stops as soon as reg(P1) errors are 
64801 ** seen.  Reg(P1) is updated with the number of errors remaining.
64802 **
64803 ** The root page numbers of all tables in the database are integer
64804 ** stored in reg(P1), reg(P1+1), reg(P1+2), ....  There are P2 tables
64805 ** total.
64806 **
64807 ** If P5 is not zero, the check is done on the auxiliary database
64808 ** file, not the main database file.
64809 **
64810 ** This opcode is used to implement the integrity_check pragma.
64811 */
64812 case OP_IntegrityCk: {
64813 #if 0  /* local variables moved into u.bv */
64814   int nRoot;      /* Number of tables to check.  (Number of root pages.) */
64815   int *aRoot;     /* Array of rootpage numbers for tables to be checked */
64816   int j;          /* Loop counter */
64817   int nErr;       /* Number of errors reported */
64818   char *z;        /* Text of the error report */
64819   Mem *pnErr;     /* Register keeping track of errors remaining */
64820 #endif /* local variables moved into u.bv */
64821
64822   u.bv.nRoot = pOp->p2;
64823   assert( u.bv.nRoot>0 );
64824   u.bv.aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(u.bv.nRoot+1) );
64825   if( u.bv.aRoot==0 ) goto no_mem;
64826   assert( pOp->p3>0 && pOp->p3<=p->nMem );
64827   u.bv.pnErr = &aMem[pOp->p3];
64828   assert( (u.bv.pnErr->flags & MEM_Int)!=0 );
64829   assert( (u.bv.pnErr->flags & (MEM_Str|MEM_Blob))==0 );
64830   pIn1 = &aMem[pOp->p1];
64831   for(u.bv.j=0; u.bv.j<u.bv.nRoot; u.bv.j++){
64832     u.bv.aRoot[u.bv.j] = (int)sqlite3VdbeIntValue(&pIn1[u.bv.j]);
64833   }
64834   u.bv.aRoot[u.bv.j] = 0;
64835   assert( pOp->p5<db->nDb );
64836   assert( (p->btreeMask & (1<<pOp->p5))!=0 );
64837   u.bv.z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, u.bv.aRoot, u.bv.nRoot,
64838                                  (int)u.bv.pnErr->u.i, &u.bv.nErr);
64839   sqlite3DbFree(db, u.bv.aRoot);
64840   u.bv.pnErr->u.i -= u.bv.nErr;
64841   sqlite3VdbeMemSetNull(pIn1);
64842   if( u.bv.nErr==0 ){
64843     assert( u.bv.z==0 );
64844   }else if( u.bv.z==0 ){
64845     goto no_mem;
64846   }else{
64847     sqlite3VdbeMemSetStr(pIn1, u.bv.z, -1, SQLITE_UTF8, sqlite3_free);
64848   }
64849   UPDATE_MAX_BLOBSIZE(pIn1);
64850   sqlite3VdbeChangeEncoding(pIn1, encoding);
64851   break;
64852 }
64853 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
64854
64855 /* Opcode: RowSetAdd P1 P2 * * *
64856 **
64857 ** Insert the integer value held by register P2 into a boolean index
64858 ** held in register P1.
64859 **
64860 ** An assertion fails if P2 is not an integer.
64861 */
64862 case OP_RowSetAdd: {       /* in1, in2 */
64863   pIn1 = &aMem[pOp->p1];
64864   pIn2 = &aMem[pOp->p2];
64865   assert( (pIn2->flags & MEM_Int)!=0 );
64866   if( (pIn1->flags & MEM_RowSet)==0 ){
64867     sqlite3VdbeMemSetRowSet(pIn1);
64868     if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
64869   }
64870   sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
64871   break;
64872 }
64873
64874 /* Opcode: RowSetRead P1 P2 P3 * *
64875 **
64876 ** Extract the smallest value from boolean index P1 and put that value into
64877 ** register P3.  Or, if boolean index P1 is initially empty, leave P3
64878 ** unchanged and jump to instruction P2.
64879 */
64880 case OP_RowSetRead: {       /* jump, in1, out3 */
64881 #if 0  /* local variables moved into u.bw */
64882   i64 val;
64883 #endif /* local variables moved into u.bw */
64884   CHECK_FOR_INTERRUPT;
64885   pIn1 = &aMem[pOp->p1];
64886   if( (pIn1->flags & MEM_RowSet)==0
64887    || sqlite3RowSetNext(pIn1->u.pRowSet, &u.bw.val)==0
64888   ){
64889     /* The boolean index is empty */
64890     sqlite3VdbeMemSetNull(pIn1);
64891     pc = pOp->p2 - 1;
64892   }else{
64893     /* A value was pulled from the index */
64894     sqlite3VdbeMemSetInt64(&aMem[pOp->p3], u.bw.val);
64895   }
64896   break;
64897 }
64898
64899 /* Opcode: RowSetTest P1 P2 P3 P4
64900 **
64901 ** Register P3 is assumed to hold a 64-bit integer value. If register P1
64902 ** contains a RowSet object and that RowSet object contains
64903 ** the value held in P3, jump to register P2. Otherwise, insert the
64904 ** integer in P3 into the RowSet and continue on to the
64905 ** next opcode.
64906 **
64907 ** The RowSet object is optimized for the case where successive sets
64908 ** of integers, where each set contains no duplicates. Each set
64909 ** of values is identified by a unique P4 value. The first set
64910 ** must have P4==0, the final set P4=-1.  P4 must be either -1 or
64911 ** non-negative.  For non-negative values of P4 only the lower 4
64912 ** bits are significant.
64913 **
64914 ** This allows optimizations: (a) when P4==0 there is no need to test
64915 ** the rowset object for P3, as it is guaranteed not to contain it,
64916 ** (b) when P4==-1 there is no need to insert the value, as it will
64917 ** never be tested for, and (c) when a value that is part of set X is
64918 ** inserted, there is no need to search to see if the same value was
64919 ** previously inserted as part of set X (only if it was previously
64920 ** inserted as part of some other set).
64921 */
64922 case OP_RowSetTest: {                     /* jump, in1, in3 */
64923 #if 0  /* local variables moved into u.bx */
64924   int iSet;
64925   int exists;
64926 #endif /* local variables moved into u.bx */
64927
64928   pIn1 = &aMem[pOp->p1];
64929   pIn3 = &aMem[pOp->p3];
64930   u.bx.iSet = pOp->p4.i;
64931   assert( pIn3->flags&MEM_Int );
64932
64933   /* If there is anything other than a rowset object in memory cell P1,
64934   ** delete it now and initialize P1 with an empty rowset
64935   */
64936   if( (pIn1->flags & MEM_RowSet)==0 ){
64937     sqlite3VdbeMemSetRowSet(pIn1);
64938     if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
64939   }
64940
64941   assert( pOp->p4type==P4_INT32 );
64942   assert( u.bx.iSet==-1 || u.bx.iSet>=0 );
64943   if( u.bx.iSet ){
64944     u.bx.exists = sqlite3RowSetTest(pIn1->u.pRowSet,
64945                                (u8)(u.bx.iSet>=0 ? u.bx.iSet & 0xf : 0xff),
64946                                pIn3->u.i);
64947     if( u.bx.exists ){
64948       pc = pOp->p2 - 1;
64949       break;
64950     }
64951   }
64952   if( u.bx.iSet>=0 ){
64953     sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
64954   }
64955   break;
64956 }
64957
64958
64959 #ifndef SQLITE_OMIT_TRIGGER
64960
64961 /* Opcode: Program P1 P2 P3 P4 *
64962 **
64963 ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM). 
64964 **
64965 ** P1 contains the address of the memory cell that contains the first memory 
64966 ** cell in an array of values used as arguments to the sub-program. P2 
64967 ** contains the address to jump to if the sub-program throws an IGNORE 
64968 ** exception using the RAISE() function. Register P3 contains the address 
64969 ** of a memory cell in this (the parent) VM that is used to allocate the 
64970 ** memory required by the sub-vdbe at runtime.
64971 **
64972 ** P4 is a pointer to the VM containing the trigger program.
64973 */
64974 case OP_Program: {        /* jump */
64975 #if 0  /* local variables moved into u.by */
64976   int nMem;               /* Number of memory registers for sub-program */
64977   int nByte;              /* Bytes of runtime space required for sub-program */
64978   Mem *pRt;               /* Register to allocate runtime space */
64979   Mem *pMem;              /* Used to iterate through memory cells */
64980   Mem *pEnd;              /* Last memory cell in new array */
64981   VdbeFrame *pFrame;      /* New vdbe frame to execute in */
64982   SubProgram *pProgram;   /* Sub-program to execute */
64983   void *t;                /* Token identifying trigger */
64984 #endif /* local variables moved into u.by */
64985
64986   u.by.pProgram = pOp->p4.pProgram;
64987   u.by.pRt = &aMem[pOp->p3];
64988   assert( memIsValid(u.by.pRt) );
64989   assert( u.by.pProgram->nOp>0 );
64990
64991   /* If the p5 flag is clear, then recursive invocation of triggers is
64992   ** disabled for backwards compatibility (p5 is set if this sub-program
64993   ** is really a trigger, not a foreign key action, and the flag set
64994   ** and cleared by the "PRAGMA recursive_triggers" command is clear).
64995   **
64996   ** It is recursive invocation of triggers, at the SQL level, that is
64997   ** disabled. In some cases a single trigger may generate more than one
64998   ** SubProgram (if the trigger may be executed with more than one different
64999   ** ON CONFLICT algorithm). SubProgram structures associated with a
65000   ** single trigger all have the same value for the SubProgram.token
65001   ** variable.  */
65002   if( pOp->p5 ){
65003     u.by.t = u.by.pProgram->token;
65004     for(u.by.pFrame=p->pFrame; u.by.pFrame && u.by.pFrame->token!=u.by.t; u.by.pFrame=u.by.pFrame->pParent);
65005     if( u.by.pFrame ) break;
65006   }
65007
65008   if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
65009     rc = SQLITE_ERROR;
65010     sqlite3SetString(&p->zErrMsg, db, "too many levels of trigger recursion");
65011     break;
65012   }
65013
65014   /* Register u.by.pRt is used to store the memory required to save the state
65015   ** of the current program, and the memory required at runtime to execute
65016   ** the trigger program. If this trigger has been fired before, then u.by.pRt
65017   ** is already allocated. Otherwise, it must be initialized.  */
65018   if( (u.by.pRt->flags&MEM_Frame)==0 ){
65019     /* SubProgram.nMem is set to the number of memory cells used by the
65020     ** program stored in SubProgram.aOp. As well as these, one memory
65021     ** cell is required for each cursor used by the program. Set local
65022     ** variable u.by.nMem (and later, VdbeFrame.nChildMem) to this value.
65023     */
65024     u.by.nMem = u.by.pProgram->nMem + u.by.pProgram->nCsr;
65025     u.by.nByte = ROUND8(sizeof(VdbeFrame))
65026               + u.by.nMem * sizeof(Mem)
65027               + u.by.pProgram->nCsr * sizeof(VdbeCursor *);
65028     u.by.pFrame = sqlite3DbMallocZero(db, u.by.nByte);
65029     if( !u.by.pFrame ){
65030       goto no_mem;
65031     }
65032     sqlite3VdbeMemRelease(u.by.pRt);
65033     u.by.pRt->flags = MEM_Frame;
65034     u.by.pRt->u.pFrame = u.by.pFrame;
65035
65036     u.by.pFrame->v = p;
65037     u.by.pFrame->nChildMem = u.by.nMem;
65038     u.by.pFrame->nChildCsr = u.by.pProgram->nCsr;
65039     u.by.pFrame->pc = pc;
65040     u.by.pFrame->aMem = p->aMem;
65041     u.by.pFrame->nMem = p->nMem;
65042     u.by.pFrame->apCsr = p->apCsr;
65043     u.by.pFrame->nCursor = p->nCursor;
65044     u.by.pFrame->aOp = p->aOp;
65045     u.by.pFrame->nOp = p->nOp;
65046     u.by.pFrame->token = u.by.pProgram->token;
65047
65048     u.by.pEnd = &VdbeFrameMem(u.by.pFrame)[u.by.pFrame->nChildMem];
65049     for(u.by.pMem=VdbeFrameMem(u.by.pFrame); u.by.pMem!=u.by.pEnd; u.by.pMem++){
65050       u.by.pMem->flags = MEM_Null;
65051       u.by.pMem->db = db;
65052     }
65053   }else{
65054     u.by.pFrame = u.by.pRt->u.pFrame;
65055     assert( u.by.pProgram->nMem+u.by.pProgram->nCsr==u.by.pFrame->nChildMem );
65056     assert( u.by.pProgram->nCsr==u.by.pFrame->nChildCsr );
65057     assert( pc==u.by.pFrame->pc );
65058   }
65059
65060   p->nFrame++;
65061   u.by.pFrame->pParent = p->pFrame;
65062   u.by.pFrame->lastRowid = db->lastRowid;
65063   u.by.pFrame->nChange = p->nChange;
65064   p->nChange = 0;
65065   p->pFrame = u.by.pFrame;
65066   p->aMem = aMem = &VdbeFrameMem(u.by.pFrame)[-1];
65067   p->nMem = u.by.pFrame->nChildMem;
65068   p->nCursor = (u16)u.by.pFrame->nChildCsr;
65069   p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
65070   p->aOp = aOp = u.by.pProgram->aOp;
65071   p->nOp = u.by.pProgram->nOp;
65072   pc = -1;
65073
65074   break;
65075 }
65076
65077 /* Opcode: Param P1 P2 * * *
65078 **
65079 ** This opcode is only ever present in sub-programs called via the 
65080 ** OP_Program instruction. Copy a value currently stored in a memory 
65081 ** cell of the calling (parent) frame to cell P2 in the current frames 
65082 ** address space. This is used by trigger programs to access the new.* 
65083 ** and old.* values.
65084 **
65085 ** The address of the cell in the parent frame is determined by adding
65086 ** the value of the P1 argument to the value of the P1 argument to the
65087 ** calling OP_Program instruction.
65088 */
65089 case OP_Param: {           /* out2-prerelease */
65090 #if 0  /* local variables moved into u.bz */
65091   VdbeFrame *pFrame;
65092   Mem *pIn;
65093 #endif /* local variables moved into u.bz */
65094   u.bz.pFrame = p->pFrame;
65095   u.bz.pIn = &u.bz.pFrame->aMem[pOp->p1 + u.bz.pFrame->aOp[u.bz.pFrame->pc].p1];
65096   sqlite3VdbeMemShallowCopy(pOut, u.bz.pIn, MEM_Ephem);
65097   break;
65098 }
65099
65100 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
65101
65102 #ifndef SQLITE_OMIT_FOREIGN_KEY
65103 /* Opcode: FkCounter P1 P2 * * *
65104 **
65105 ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
65106 ** If P1 is non-zero, the database constraint counter is incremented 
65107 ** (deferred foreign key constraints). Otherwise, if P1 is zero, the 
65108 ** statement counter is incremented (immediate foreign key constraints).
65109 */
65110 case OP_FkCounter: {
65111   if( pOp->p1 ){
65112     db->nDeferredCons += pOp->p2;
65113   }else{
65114     p->nFkConstraint += pOp->p2;
65115   }
65116   break;
65117 }
65118
65119 /* Opcode: FkIfZero P1 P2 * * *
65120 **
65121 ** This opcode tests if a foreign key constraint-counter is currently zero.
65122 ** If so, jump to instruction P2. Otherwise, fall through to the next 
65123 ** instruction.
65124 **
65125 ** If P1 is non-zero, then the jump is taken if the database constraint-counter
65126 ** is zero (the one that counts deferred constraint violations). If P1 is
65127 ** zero, the jump is taken if the statement constraint-counter is zero
65128 ** (immediate foreign key constraint violations).
65129 */
65130 case OP_FkIfZero: {         /* jump */
65131   if( pOp->p1 ){
65132     if( db->nDeferredCons==0 ) pc = pOp->p2-1;
65133   }else{
65134     if( p->nFkConstraint==0 ) pc = pOp->p2-1;
65135   }
65136   break;
65137 }
65138 #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
65139
65140 #ifndef SQLITE_OMIT_AUTOINCREMENT
65141 /* Opcode: MemMax P1 P2 * * *
65142 **
65143 ** P1 is a register in the root frame of this VM (the root frame is
65144 ** different from the current frame if this instruction is being executed
65145 ** within a sub-program). Set the value of register P1 to the maximum of 
65146 ** its current value and the value in register P2.
65147 **
65148 ** This instruction throws an error if the memory cell is not initially
65149 ** an integer.
65150 */
65151 case OP_MemMax: {        /* in2 */
65152 #if 0  /* local variables moved into u.ca */
65153   Mem *pIn1;
65154   VdbeFrame *pFrame;
65155 #endif /* local variables moved into u.ca */
65156   if( p->pFrame ){
65157     for(u.ca.pFrame=p->pFrame; u.ca.pFrame->pParent; u.ca.pFrame=u.ca.pFrame->pParent);
65158     u.ca.pIn1 = &u.ca.pFrame->aMem[pOp->p1];
65159   }else{
65160     u.ca.pIn1 = &aMem[pOp->p1];
65161   }
65162   assert( memIsValid(u.ca.pIn1) );
65163   sqlite3VdbeMemIntegerify(u.ca.pIn1);
65164   pIn2 = &aMem[pOp->p2];
65165   sqlite3VdbeMemIntegerify(pIn2);
65166   if( u.ca.pIn1->u.i<pIn2->u.i){
65167     u.ca.pIn1->u.i = pIn2->u.i;
65168   }
65169   break;
65170 }
65171 #endif /* SQLITE_OMIT_AUTOINCREMENT */
65172
65173 /* Opcode: IfPos P1 P2 * * *
65174 **
65175 ** If the value of register P1 is 1 or greater, jump to P2.
65176 **
65177 ** It is illegal to use this instruction on a register that does
65178 ** not contain an integer.  An assertion fault will result if you try.
65179 */
65180 case OP_IfPos: {        /* jump, in1 */
65181   pIn1 = &aMem[pOp->p1];
65182   assert( pIn1->flags&MEM_Int );
65183   if( pIn1->u.i>0 ){
65184      pc = pOp->p2 - 1;
65185   }
65186   break;
65187 }
65188
65189 /* Opcode: IfNeg P1 P2 * * *
65190 **
65191 ** If the value of register P1 is less than zero, jump to P2. 
65192 **
65193 ** It is illegal to use this instruction on a register that does
65194 ** not contain an integer.  An assertion fault will result if you try.
65195 */
65196 case OP_IfNeg: {        /* jump, in1 */
65197   pIn1 = &aMem[pOp->p1];
65198   assert( pIn1->flags&MEM_Int );
65199   if( pIn1->u.i<0 ){
65200      pc = pOp->p2 - 1;
65201   }
65202   break;
65203 }
65204
65205 /* Opcode: IfZero P1 P2 P3 * *
65206 **
65207 ** The register P1 must contain an integer.  Add literal P3 to the
65208 ** value in register P1.  If the result is exactly 0, jump to P2. 
65209 **
65210 ** It is illegal to use this instruction on a register that does
65211 ** not contain an integer.  An assertion fault will result if you try.
65212 */
65213 case OP_IfZero: {        /* jump, in1 */
65214   pIn1 = &aMem[pOp->p1];
65215   assert( pIn1->flags&MEM_Int );
65216   pIn1->u.i += pOp->p3;
65217   if( pIn1->u.i==0 ){
65218      pc = pOp->p2 - 1;
65219   }
65220   break;
65221 }
65222
65223 /* Opcode: AggStep * P2 P3 P4 P5
65224 **
65225 ** Execute the step function for an aggregate.  The
65226 ** function has P5 arguments.   P4 is a pointer to the FuncDef
65227 ** structure that specifies the function.  Use register
65228 ** P3 as the accumulator.
65229 **
65230 ** The P5 arguments are taken from register P2 and its
65231 ** successors.
65232 */
65233 case OP_AggStep: {
65234 #if 0  /* local variables moved into u.cb */
65235   int n;
65236   int i;
65237   Mem *pMem;
65238   Mem *pRec;
65239   sqlite3_context ctx;
65240   sqlite3_value **apVal;
65241 #endif /* local variables moved into u.cb */
65242
65243   u.cb.n = pOp->p5;
65244   assert( u.cb.n>=0 );
65245   u.cb.pRec = &aMem[pOp->p2];
65246   u.cb.apVal = p->apArg;
65247   assert( u.cb.apVal || u.cb.n==0 );
65248   for(u.cb.i=0; u.cb.i<u.cb.n; u.cb.i++, u.cb.pRec++){
65249     assert( memIsValid(u.cb.pRec) );
65250     u.cb.apVal[u.cb.i] = u.cb.pRec;
65251     memAboutToChange(p, u.cb.pRec);
65252     sqlite3VdbeMemStoreType(u.cb.pRec);
65253   }
65254   u.cb.ctx.pFunc = pOp->p4.pFunc;
65255   assert( pOp->p3>0 && pOp->p3<=p->nMem );
65256   u.cb.ctx.pMem = u.cb.pMem = &aMem[pOp->p3];
65257   u.cb.pMem->n++;
65258   u.cb.ctx.s.flags = MEM_Null;
65259   u.cb.ctx.s.z = 0;
65260   u.cb.ctx.s.zMalloc = 0;
65261   u.cb.ctx.s.xDel = 0;
65262   u.cb.ctx.s.db = db;
65263   u.cb.ctx.isError = 0;
65264   u.cb.ctx.pColl = 0;
65265   if( u.cb.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
65266     assert( pOp>p->aOp );
65267     assert( pOp[-1].p4type==P4_COLLSEQ );
65268     assert( pOp[-1].opcode==OP_CollSeq );
65269     u.cb.ctx.pColl = pOp[-1].p4.pColl;
65270   }
65271   (u.cb.ctx.pFunc->xStep)(&u.cb.ctx, u.cb.n, u.cb.apVal); /* IMP: R-24505-23230 */
65272   if( u.cb.ctx.isError ){
65273     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.cb.ctx.s));
65274     rc = u.cb.ctx.isError;
65275   }
65276   sqlite3VdbeMemRelease(&u.cb.ctx.s);
65277   break;
65278 }
65279
65280 /* Opcode: AggFinal P1 P2 * P4 *
65281 **
65282 ** Execute the finalizer function for an aggregate.  P1 is
65283 ** the memory location that is the accumulator for the aggregate.
65284 **
65285 ** P2 is the number of arguments that the step function takes and
65286 ** P4 is a pointer to the FuncDef for this function.  The P2
65287 ** argument is not used by this opcode.  It is only there to disambiguate
65288 ** functions that can take varying numbers of arguments.  The
65289 ** P4 argument is only needed for the degenerate case where
65290 ** the step function was not previously called.
65291 */
65292 case OP_AggFinal: {
65293 #if 0  /* local variables moved into u.cc */
65294   Mem *pMem;
65295 #endif /* local variables moved into u.cc */
65296   assert( pOp->p1>0 && pOp->p1<=p->nMem );
65297   u.cc.pMem = &aMem[pOp->p1];
65298   assert( (u.cc.pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
65299   rc = sqlite3VdbeMemFinalize(u.cc.pMem, pOp->p4.pFunc);
65300   if( rc ){
65301     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(u.cc.pMem));
65302   }
65303   sqlite3VdbeChangeEncoding(u.cc.pMem, encoding);
65304   UPDATE_MAX_BLOBSIZE(u.cc.pMem);
65305   if( sqlite3VdbeMemTooBig(u.cc.pMem) ){
65306     goto too_big;
65307   }
65308   break;
65309 }
65310
65311 #ifndef SQLITE_OMIT_WAL
65312 /* Opcode: Checkpoint P1 * * * *
65313 **
65314 ** Checkpoint database P1. This is a no-op if P1 is not currently in
65315 ** WAL mode.
65316 */
65317 case OP_Checkpoint: {
65318   rc = sqlite3Checkpoint(db, pOp->p1);
65319   break;
65320 };  
65321 #endif
65322
65323 #ifndef SQLITE_OMIT_PRAGMA
65324 /* Opcode: JournalMode P1 P2 P3 * P5
65325 **
65326 ** Change the journal mode of database P1 to P3. P3 must be one of the
65327 ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
65328 ** modes (delete, truncate, persist, off and memory), this is a simple
65329 ** operation. No IO is required.
65330 **
65331 ** If changing into or out of WAL mode the procedure is more complicated.
65332 **
65333 ** Write a string containing the final journal-mode to register P2.
65334 */
65335 case OP_JournalMode: {    /* out2-prerelease */
65336 #if 0  /* local variables moved into u.cd */
65337   Btree *pBt;                     /* Btree to change journal mode of */
65338   Pager *pPager;                  /* Pager associated with pBt */
65339   int eNew;                       /* New journal mode */
65340   int eOld;                       /* The old journal mode */
65341   const char *zFilename;          /* Name of database file for pPager */
65342 #endif /* local variables moved into u.cd */
65343
65344   u.cd.eNew = pOp->p3;
65345   assert( u.cd.eNew==PAGER_JOURNALMODE_DELETE
65346        || u.cd.eNew==PAGER_JOURNALMODE_TRUNCATE
65347        || u.cd.eNew==PAGER_JOURNALMODE_PERSIST
65348        || u.cd.eNew==PAGER_JOURNALMODE_OFF
65349        || u.cd.eNew==PAGER_JOURNALMODE_MEMORY
65350        || u.cd.eNew==PAGER_JOURNALMODE_WAL
65351        || u.cd.eNew==PAGER_JOURNALMODE_QUERY
65352   );
65353   assert( pOp->p1>=0 && pOp->p1<db->nDb );
65354
65355   /* This opcode is used in two places: PRAGMA journal_mode and ATTACH.
65356   ** In PRAGMA journal_mode, the sqlite3VdbeUsesBtree() routine is called
65357   ** when the statment is prepared and so p->aMutex.nMutex>0.  All mutexes
65358   ** are already acquired.  But when used in ATTACH, sqlite3VdbeUsesBtree()
65359   ** is not called when the statement is prepared because it requires the
65360   ** iDb index of the database as a parameter, and the database has not
65361   ** yet been attached so that index is unavailable.  We have to wait
65362   ** until runtime (now) to get the mutex on the newly attached database.
65363   ** No other mutexes are required by the ATTACH command so this is safe
65364   ** to do.
65365   */
65366   assert( (p->btreeMask & (1<<pOp->p1))!=0 || p->aMutex.nMutex==0 );
65367   if( p->aMutex.nMutex==0 ){
65368     /* This occurs right after ATTACH.  Get a mutex on the newly ATTACHed
65369     ** database. */
65370     sqlite3VdbeUsesBtree(p, pOp->p1);
65371     sqlite3VdbeMutexArrayEnter(p);
65372   }
65373
65374   u.cd.pBt = db->aDb[pOp->p1].pBt;
65375   u.cd.pPager = sqlite3BtreePager(u.cd.pBt);
65376   u.cd.eOld = sqlite3PagerGetJournalMode(u.cd.pPager);
65377   if( u.cd.eNew==PAGER_JOURNALMODE_QUERY ) u.cd.eNew = u.cd.eOld;
65378   if( !sqlite3PagerOkToChangeJournalMode(u.cd.pPager) ) u.cd.eNew = u.cd.eOld;
65379
65380 #ifndef SQLITE_OMIT_WAL
65381   u.cd.zFilename = sqlite3PagerFilename(u.cd.pPager);
65382
65383   /* Do not allow a transition to journal_mode=WAL for a database
65384   ** in temporary storage or if the VFS does not support shared memory
65385   */
65386   if( u.cd.eNew==PAGER_JOURNALMODE_WAL
65387    && (u.cd.zFilename[0]==0                         /* Temp file */
65388        || !sqlite3PagerWalSupported(u.cd.pPager))   /* No shared-memory support */
65389   ){
65390     u.cd.eNew = u.cd.eOld;
65391   }
65392
65393   if( (u.cd.eNew!=u.cd.eOld)
65394    && (u.cd.eOld==PAGER_JOURNALMODE_WAL || u.cd.eNew==PAGER_JOURNALMODE_WAL)
65395   ){
65396     if( !db->autoCommit || db->activeVdbeCnt>1 ){
65397       rc = SQLITE_ERROR;
65398       sqlite3SetString(&p->zErrMsg, db,
65399           "cannot change %s wal mode from within a transaction",
65400           (u.cd.eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
65401       );
65402       break;
65403     }else{
65404
65405       if( u.cd.eOld==PAGER_JOURNALMODE_WAL ){
65406         /* If leaving WAL mode, close the log file. If successful, the call
65407         ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
65408         ** file. An EXCLUSIVE lock may still be held on the database file
65409         ** after a successful return.
65410         */
65411         rc = sqlite3PagerCloseWal(u.cd.pPager);
65412         if( rc==SQLITE_OK ){
65413           sqlite3PagerSetJournalMode(u.cd.pPager, u.cd.eNew);
65414         }
65415       }else if( u.cd.eOld==PAGER_JOURNALMODE_MEMORY ){
65416         /* Cannot transition directly from MEMORY to WAL.  Use mode OFF
65417         ** as an intermediate */
65418         sqlite3PagerSetJournalMode(u.cd.pPager, PAGER_JOURNALMODE_OFF);
65419       }
65420
65421       /* Open a transaction on the database file. Regardless of the journal
65422       ** mode, this transaction always uses a rollback journal.
65423       */
65424       assert( sqlite3BtreeIsInTrans(u.cd.pBt)==0 );
65425       if( rc==SQLITE_OK ){
65426         rc = sqlite3BtreeSetVersion(u.cd.pBt, (u.cd.eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
65427       }
65428     }
65429   }
65430 #endif /* ifndef SQLITE_OMIT_WAL */
65431
65432   if( rc ){
65433     u.cd.eNew = u.cd.eOld;
65434   }
65435   u.cd.eNew = sqlite3PagerSetJournalMode(u.cd.pPager, u.cd.eNew);
65436
65437   pOut = &aMem[pOp->p2];
65438   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
65439   pOut->z = (char *)sqlite3JournalModename(u.cd.eNew);
65440   pOut->n = sqlite3Strlen30(pOut->z);
65441   pOut->enc = SQLITE_UTF8;
65442   sqlite3VdbeChangeEncoding(pOut, encoding);
65443   break;
65444 };
65445 #endif /* SQLITE_OMIT_PRAGMA */
65446
65447 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
65448 /* Opcode: Vacuum * * * * *
65449 **
65450 ** Vacuum the entire database.  This opcode will cause other virtual
65451 ** machines to be created and run.  It may not be called from within
65452 ** a transaction.
65453 */
65454 case OP_Vacuum: {
65455   rc = sqlite3RunVacuum(&p->zErrMsg, db);
65456   break;
65457 }
65458 #endif
65459
65460 #if !defined(SQLITE_OMIT_AUTOVACUUM)
65461 /* Opcode: IncrVacuum P1 P2 * * *
65462 **
65463 ** Perform a single step of the incremental vacuum procedure on
65464 ** the P1 database. If the vacuum has finished, jump to instruction
65465 ** P2. Otherwise, fall through to the next instruction.
65466 */
65467 case OP_IncrVacuum: {        /* jump */
65468 #if 0  /* local variables moved into u.ce */
65469   Btree *pBt;
65470 #endif /* local variables moved into u.ce */
65471
65472   assert( pOp->p1>=0 && pOp->p1<db->nDb );
65473   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
65474   u.ce.pBt = db->aDb[pOp->p1].pBt;
65475   rc = sqlite3BtreeIncrVacuum(u.ce.pBt);
65476   if( rc==SQLITE_DONE ){
65477     pc = pOp->p2 - 1;
65478     rc = SQLITE_OK;
65479   }
65480   break;
65481 }
65482 #endif
65483
65484 /* Opcode: Expire P1 * * * *
65485 **
65486 ** Cause precompiled statements to become expired. An expired statement
65487 ** fails with an error code of SQLITE_SCHEMA if it is ever executed 
65488 ** (via sqlite3_step()).
65489 ** 
65490 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
65491 ** then only the currently executing statement is affected. 
65492 */
65493 case OP_Expire: {
65494   if( !pOp->p1 ){
65495     sqlite3ExpirePreparedStatements(db);
65496   }else{
65497     p->expired = 1;
65498   }
65499   break;
65500 }
65501
65502 #ifndef SQLITE_OMIT_SHARED_CACHE
65503 /* Opcode: TableLock P1 P2 P3 P4 *
65504 **
65505 ** Obtain a lock on a particular table. This instruction is only used when
65506 ** the shared-cache feature is enabled. 
65507 **
65508 ** P1 is the index of the database in sqlite3.aDb[] of the database
65509 ** on which the lock is acquired.  A readlock is obtained if P3==0 or
65510 ** a write lock if P3==1.
65511 **
65512 ** P2 contains the root-page of the table to lock.
65513 **
65514 ** P4 contains a pointer to the name of the table being locked. This is only
65515 ** used to generate an error message if the lock cannot be obtained.
65516 */
65517 case OP_TableLock: {
65518   u8 isWriteLock = (u8)pOp->p3;
65519   if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
65520     int p1 = pOp->p1; 
65521     assert( p1>=0 && p1<db->nDb );
65522     assert( (p->btreeMask & (1<<p1))!=0 );
65523     assert( isWriteLock==0 || isWriteLock==1 );
65524     rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
65525     if( (rc&0xFF)==SQLITE_LOCKED ){
65526       const char *z = pOp->p4.z;
65527       sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
65528     }
65529   }
65530   break;
65531 }
65532 #endif /* SQLITE_OMIT_SHARED_CACHE */
65533
65534 #ifndef SQLITE_OMIT_VIRTUALTABLE
65535 /* Opcode: VBegin * * * P4 *
65536 **
65537 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the 
65538 ** xBegin method for that table.
65539 **
65540 ** Also, whether or not P4 is set, check that this is not being called from
65541 ** within a callback to a virtual table xSync() method. If it is, the error
65542 ** code will be set to SQLITE_LOCKED.
65543 */
65544 case OP_VBegin: {
65545 #if 0  /* local variables moved into u.cf */
65546   VTable *pVTab;
65547 #endif /* local variables moved into u.cf */
65548   u.cf.pVTab = pOp->p4.pVtab;
65549   rc = sqlite3VtabBegin(db, u.cf.pVTab);
65550   if( u.cf.pVTab ) importVtabErrMsg(p, u.cf.pVTab->pVtab);
65551   break;
65552 }
65553 #endif /* SQLITE_OMIT_VIRTUALTABLE */
65554
65555 #ifndef SQLITE_OMIT_VIRTUALTABLE
65556 /* Opcode: VCreate P1 * * P4 *
65557 **
65558 ** P4 is the name of a virtual table in database P1. Call the xCreate method
65559 ** for that table.
65560 */
65561 case OP_VCreate: {
65562   rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
65563   break;
65564 }
65565 #endif /* SQLITE_OMIT_VIRTUALTABLE */
65566
65567 #ifndef SQLITE_OMIT_VIRTUALTABLE
65568 /* Opcode: VDestroy P1 * * P4 *
65569 **
65570 ** P4 is the name of a virtual table in database P1.  Call the xDestroy method
65571 ** of that table.
65572 */
65573 case OP_VDestroy: {
65574   p->inVtabMethod = 2;
65575   rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
65576   p->inVtabMethod = 0;
65577   break;
65578 }
65579 #endif /* SQLITE_OMIT_VIRTUALTABLE */
65580
65581 #ifndef SQLITE_OMIT_VIRTUALTABLE
65582 /* Opcode: VOpen P1 * * P4 *
65583 **
65584 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
65585 ** P1 is a cursor number.  This opcode opens a cursor to the virtual
65586 ** table and stores that cursor in P1.
65587 */
65588 case OP_VOpen: {
65589 #if 0  /* local variables moved into u.cg */
65590   VdbeCursor *pCur;
65591   sqlite3_vtab_cursor *pVtabCursor;
65592   sqlite3_vtab *pVtab;
65593   sqlite3_module *pModule;
65594 #endif /* local variables moved into u.cg */
65595
65596   u.cg.pCur = 0;
65597   u.cg.pVtabCursor = 0;
65598   u.cg.pVtab = pOp->p4.pVtab->pVtab;
65599   u.cg.pModule = (sqlite3_module *)u.cg.pVtab->pModule;
65600   assert(u.cg.pVtab && u.cg.pModule);
65601   rc = u.cg.pModule->xOpen(u.cg.pVtab, &u.cg.pVtabCursor);
65602   importVtabErrMsg(p, u.cg.pVtab);
65603   if( SQLITE_OK==rc ){
65604     /* Initialize sqlite3_vtab_cursor base class */
65605     u.cg.pVtabCursor->pVtab = u.cg.pVtab;
65606
65607     /* Initialise vdbe cursor object */
65608     u.cg.pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
65609     if( u.cg.pCur ){
65610       u.cg.pCur->pVtabCursor = u.cg.pVtabCursor;
65611       u.cg.pCur->pModule = u.cg.pVtabCursor->pVtab->pModule;
65612     }else{
65613       db->mallocFailed = 1;
65614       u.cg.pModule->xClose(u.cg.pVtabCursor);
65615     }
65616   }
65617   break;
65618 }
65619 #endif /* SQLITE_OMIT_VIRTUALTABLE */
65620
65621 #ifndef SQLITE_OMIT_VIRTUALTABLE
65622 /* Opcode: VFilter P1 P2 P3 P4 *
65623 **
65624 ** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
65625 ** the filtered result set is empty.
65626 **
65627 ** P4 is either NULL or a string that was generated by the xBestIndex
65628 ** method of the module.  The interpretation of the P4 string is left
65629 ** to the module implementation.
65630 **
65631 ** This opcode invokes the xFilter method on the virtual table specified
65632 ** by P1.  The integer query plan parameter to xFilter is stored in register
65633 ** P3. Register P3+1 stores the argc parameter to be passed to the
65634 ** xFilter method. Registers P3+2..P3+1+argc are the argc
65635 ** additional parameters which are passed to
65636 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
65637 **
65638 ** A jump is made to P2 if the result set after filtering would be empty.
65639 */
65640 case OP_VFilter: {   /* jump */
65641 #if 0  /* local variables moved into u.ch */
65642   int nArg;
65643   int iQuery;
65644   const sqlite3_module *pModule;
65645   Mem *pQuery;
65646   Mem *pArgc;
65647   sqlite3_vtab_cursor *pVtabCursor;
65648   sqlite3_vtab *pVtab;
65649   VdbeCursor *pCur;
65650   int res;
65651   int i;
65652   Mem **apArg;
65653 #endif /* local variables moved into u.ch */
65654
65655   u.ch.pQuery = &aMem[pOp->p3];
65656   u.ch.pArgc = &u.ch.pQuery[1];
65657   u.ch.pCur = p->apCsr[pOp->p1];
65658   assert( memIsValid(u.ch.pQuery) );
65659   REGISTER_TRACE(pOp->p3, u.ch.pQuery);
65660   assert( u.ch.pCur->pVtabCursor );
65661   u.ch.pVtabCursor = u.ch.pCur->pVtabCursor;
65662   u.ch.pVtab = u.ch.pVtabCursor->pVtab;
65663   u.ch.pModule = u.ch.pVtab->pModule;
65664
65665   /* Grab the index number and argc parameters */
65666   assert( (u.ch.pQuery->flags&MEM_Int)!=0 && u.ch.pArgc->flags==MEM_Int );
65667   u.ch.nArg = (int)u.ch.pArgc->u.i;
65668   u.ch.iQuery = (int)u.ch.pQuery->u.i;
65669
65670   /* Invoke the xFilter method */
65671   {
65672     u.ch.res = 0;
65673     u.ch.apArg = p->apArg;
65674     for(u.ch.i = 0; u.ch.i<u.ch.nArg; u.ch.i++){
65675       u.ch.apArg[u.ch.i] = &u.ch.pArgc[u.ch.i+1];
65676       sqlite3VdbeMemStoreType(u.ch.apArg[u.ch.i]);
65677     }
65678
65679     p->inVtabMethod = 1;
65680     rc = u.ch.pModule->xFilter(u.ch.pVtabCursor, u.ch.iQuery, pOp->p4.z, u.ch.nArg, u.ch.apArg);
65681     p->inVtabMethod = 0;
65682     importVtabErrMsg(p, u.ch.pVtab);
65683     if( rc==SQLITE_OK ){
65684       u.ch.res = u.ch.pModule->xEof(u.ch.pVtabCursor);
65685     }
65686
65687     if( u.ch.res ){
65688       pc = pOp->p2 - 1;
65689     }
65690   }
65691   u.ch.pCur->nullRow = 0;
65692
65693   break;
65694 }
65695 #endif /* SQLITE_OMIT_VIRTUALTABLE */
65696
65697 #ifndef SQLITE_OMIT_VIRTUALTABLE
65698 /* Opcode: VColumn P1 P2 P3 * *
65699 **
65700 ** Store the value of the P2-th column of
65701 ** the row of the virtual-table that the 
65702 ** P1 cursor is pointing to into register P3.
65703 */
65704 case OP_VColumn: {
65705 #if 0  /* local variables moved into u.ci */
65706   sqlite3_vtab *pVtab;
65707   const sqlite3_module *pModule;
65708   Mem *pDest;
65709   sqlite3_context sContext;
65710 #endif /* local variables moved into u.ci */
65711
65712   VdbeCursor *pCur = p->apCsr[pOp->p1];
65713   assert( pCur->pVtabCursor );
65714   assert( pOp->p3>0 && pOp->p3<=p->nMem );
65715   u.ci.pDest = &aMem[pOp->p3];
65716   memAboutToChange(p, u.ci.pDest);
65717   if( pCur->nullRow ){
65718     sqlite3VdbeMemSetNull(u.ci.pDest);
65719     break;
65720   }
65721   u.ci.pVtab = pCur->pVtabCursor->pVtab;
65722   u.ci.pModule = u.ci.pVtab->pModule;
65723   assert( u.ci.pModule->xColumn );
65724   memset(&u.ci.sContext, 0, sizeof(u.ci.sContext));
65725
65726   /* The output cell may already have a buffer allocated. Move
65727   ** the current contents to u.ci.sContext.s so in case the user-function
65728   ** can use the already allocated buffer instead of allocating a
65729   ** new one.
65730   */
65731   sqlite3VdbeMemMove(&u.ci.sContext.s, u.ci.pDest);
65732   MemSetTypeFlag(&u.ci.sContext.s, MEM_Null);
65733
65734   rc = u.ci.pModule->xColumn(pCur->pVtabCursor, &u.ci.sContext, pOp->p2);
65735   importVtabErrMsg(p, u.ci.pVtab);
65736   if( u.ci.sContext.isError ){
65737     rc = u.ci.sContext.isError;
65738   }
65739
65740   /* Copy the result of the function to the P3 register. We
65741   ** do this regardless of whether or not an error occurred to ensure any
65742   ** dynamic allocation in u.ci.sContext.s (a Mem struct) is  released.
65743   */
65744   sqlite3VdbeChangeEncoding(&u.ci.sContext.s, encoding);
65745   sqlite3VdbeMemMove(u.ci.pDest, &u.ci.sContext.s);
65746   REGISTER_TRACE(pOp->p3, u.ci.pDest);
65747   UPDATE_MAX_BLOBSIZE(u.ci.pDest);
65748
65749   if( sqlite3VdbeMemTooBig(u.ci.pDest) ){
65750     goto too_big;
65751   }
65752   break;
65753 }
65754 #endif /* SQLITE_OMIT_VIRTUALTABLE */
65755
65756 #ifndef SQLITE_OMIT_VIRTUALTABLE
65757 /* Opcode: VNext P1 P2 * * *
65758 **
65759 ** Advance virtual table P1 to the next row in its result set and
65760 ** jump to instruction P2.  Or, if the virtual table has reached
65761 ** the end of its result set, then fall through to the next instruction.
65762 */
65763 case OP_VNext: {   /* jump */
65764 #if 0  /* local variables moved into u.cj */
65765   sqlite3_vtab *pVtab;
65766   const sqlite3_module *pModule;
65767   int res;
65768   VdbeCursor *pCur;
65769 #endif /* local variables moved into u.cj */
65770
65771   u.cj.res = 0;
65772   u.cj.pCur = p->apCsr[pOp->p1];
65773   assert( u.cj.pCur->pVtabCursor );
65774   if( u.cj.pCur->nullRow ){
65775     break;
65776   }
65777   u.cj.pVtab = u.cj.pCur->pVtabCursor->pVtab;
65778   u.cj.pModule = u.cj.pVtab->pModule;
65779   assert( u.cj.pModule->xNext );
65780
65781   /* Invoke the xNext() method of the module. There is no way for the
65782   ** underlying implementation to return an error if one occurs during
65783   ** xNext(). Instead, if an error occurs, true is returned (indicating that
65784   ** data is available) and the error code returned when xColumn or
65785   ** some other method is next invoked on the save virtual table cursor.
65786   */
65787   p->inVtabMethod = 1;
65788   rc = u.cj.pModule->xNext(u.cj.pCur->pVtabCursor);
65789   p->inVtabMethod = 0;
65790   importVtabErrMsg(p, u.cj.pVtab);
65791   if( rc==SQLITE_OK ){
65792     u.cj.res = u.cj.pModule->xEof(u.cj.pCur->pVtabCursor);
65793   }
65794
65795   if( !u.cj.res ){
65796     /* If there is data, jump to P2 */
65797     pc = pOp->p2 - 1;
65798   }
65799   break;
65800 }
65801 #endif /* SQLITE_OMIT_VIRTUALTABLE */
65802
65803 #ifndef SQLITE_OMIT_VIRTUALTABLE
65804 /* Opcode: VRename P1 * * P4 *
65805 **
65806 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
65807 ** This opcode invokes the corresponding xRename method. The value
65808 ** in register P1 is passed as the zName argument to the xRename method.
65809 */
65810 case OP_VRename: {
65811 #if 0  /* local variables moved into u.ck */
65812   sqlite3_vtab *pVtab;
65813   Mem *pName;
65814 #endif /* local variables moved into u.ck */
65815
65816   u.ck.pVtab = pOp->p4.pVtab->pVtab;
65817   u.ck.pName = &aMem[pOp->p1];
65818   assert( u.ck.pVtab->pModule->xRename );
65819   assert( memIsValid(u.ck.pName) );
65820   REGISTER_TRACE(pOp->p1, u.ck.pName);
65821   assert( u.ck.pName->flags & MEM_Str );
65822   rc = u.ck.pVtab->pModule->xRename(u.ck.pVtab, u.ck.pName->z);
65823   importVtabErrMsg(p, u.ck.pVtab);
65824   p->expired = 0;
65825
65826   break;
65827 }
65828 #endif
65829
65830 #ifndef SQLITE_OMIT_VIRTUALTABLE
65831 /* Opcode: VUpdate P1 P2 P3 P4 *
65832 **
65833 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
65834 ** This opcode invokes the corresponding xUpdate method. P2 values
65835 ** are contiguous memory cells starting at P3 to pass to the xUpdate 
65836 ** invocation. The value in register (P3+P2-1) corresponds to the 
65837 ** p2th element of the argv array passed to xUpdate.
65838 **
65839 ** The xUpdate method will do a DELETE or an INSERT or both.
65840 ** The argv[0] element (which corresponds to memory cell P3)
65841 ** is the rowid of a row to delete.  If argv[0] is NULL then no 
65842 ** deletion occurs.  The argv[1] element is the rowid of the new 
65843 ** row.  This can be NULL to have the virtual table select the new 
65844 ** rowid for itself.  The subsequent elements in the array are 
65845 ** the values of columns in the new row.
65846 **
65847 ** If P2==1 then no insert is performed.  argv[0] is the rowid of
65848 ** a row to delete.
65849 **
65850 ** P1 is a boolean flag. If it is set to true and the xUpdate call
65851 ** is successful, then the value returned by sqlite3_last_insert_rowid() 
65852 ** is set to the value of the rowid for the row just inserted.
65853 */
65854 case OP_VUpdate: {
65855 #if 0  /* local variables moved into u.cl */
65856   sqlite3_vtab *pVtab;
65857   sqlite3_module *pModule;
65858   int nArg;
65859   int i;
65860   sqlite_int64 rowid;
65861   Mem **apArg;
65862   Mem *pX;
65863 #endif /* local variables moved into u.cl */
65864
65865   u.cl.pVtab = pOp->p4.pVtab->pVtab;
65866   u.cl.pModule = (sqlite3_module *)u.cl.pVtab->pModule;
65867   u.cl.nArg = pOp->p2;
65868   assert( pOp->p4type==P4_VTAB );
65869   if( ALWAYS(u.cl.pModule->xUpdate) ){
65870     u.cl.apArg = p->apArg;
65871     u.cl.pX = &aMem[pOp->p3];
65872     for(u.cl.i=0; u.cl.i<u.cl.nArg; u.cl.i++){
65873       assert( memIsValid(u.cl.pX) );
65874       memAboutToChange(p, u.cl.pX);
65875       sqlite3VdbeMemStoreType(u.cl.pX);
65876       u.cl.apArg[u.cl.i] = u.cl.pX;
65877       u.cl.pX++;
65878     }
65879     rc = u.cl.pModule->xUpdate(u.cl.pVtab, u.cl.nArg, u.cl.apArg, &u.cl.rowid);
65880     importVtabErrMsg(p, u.cl.pVtab);
65881     if( rc==SQLITE_OK && pOp->p1 ){
65882       assert( u.cl.nArg>1 && u.cl.apArg[0] && (u.cl.apArg[0]->flags&MEM_Null) );
65883       db->lastRowid = u.cl.rowid;
65884     }
65885     p->nChange++;
65886   }
65887   break;
65888 }
65889 #endif /* SQLITE_OMIT_VIRTUALTABLE */
65890
65891 #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
65892 /* Opcode: Pagecount P1 P2 * * *
65893 **
65894 ** Write the current number of pages in database P1 to memory cell P2.
65895 */
65896 case OP_Pagecount: {            /* out2-prerelease */
65897   pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
65898   break;
65899 }
65900 #endif
65901
65902 #ifndef SQLITE_OMIT_TRACE
65903 /* Opcode: Trace * * * P4 *
65904 **
65905 ** If tracing is enabled (by the sqlite3_trace()) interface, then
65906 ** the UTF-8 string contained in P4 is emitted on the trace callback.
65907 */
65908 case OP_Trace: {
65909 #if 0  /* local variables moved into u.cm */
65910   char *zTrace;
65911 #endif /* local variables moved into u.cm */
65912
65913   u.cm.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
65914   if( u.cm.zTrace ){
65915     if( db->xTrace ){
65916       char *z = sqlite3VdbeExpandSql(p, u.cm.zTrace);
65917       db->xTrace(db->pTraceArg, z);
65918       sqlite3DbFree(db, z);
65919     }
65920 #ifdef SQLITE_DEBUG
65921     if( (db->flags & SQLITE_SqlTrace)!=0 ){
65922       sqlite3DebugPrintf("SQL-trace: %s\n", u.cm.zTrace);
65923     }
65924 #endif /* SQLITE_DEBUG */
65925   }
65926   break;
65927 }
65928 #endif
65929
65930
65931 /* Opcode: Noop * * * * *
65932 **
65933 ** Do nothing.  This instruction is often useful as a jump
65934 ** destination.
65935 */
65936 /*
65937 ** The magic Explain opcode are only inserted when explain==2 (which
65938 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
65939 ** This opcode records information from the optimizer.  It is the
65940 ** the same as a no-op.  This opcodesnever appears in a real VM program.
65941 */
65942 default: {          /* This is really OP_Noop and OP_Explain */
65943   assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
65944   break;
65945 }
65946
65947 /*****************************************************************************
65948 ** The cases of the switch statement above this line should all be indented
65949 ** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
65950 ** readability.  From this point on down, the normal indentation rules are
65951 ** restored.
65952 *****************************************************************************/
65953     }
65954
65955 #ifdef VDBE_PROFILE
65956     {
65957       u64 elapsed = sqlite3Hwtime() - start;
65958       pOp->cycles += elapsed;
65959       pOp->cnt++;
65960 #if 0
65961         fprintf(stdout, "%10llu ", elapsed);
65962         sqlite3VdbePrintOp(stdout, origPc, &aOp[origPc]);
65963 #endif
65964     }
65965 #endif
65966
65967     /* The following code adds nothing to the actual functionality
65968     ** of the program.  It is only here for testing and debugging.
65969     ** On the other hand, it does burn CPU cycles every time through
65970     ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
65971     */
65972 #ifndef NDEBUG
65973     assert( pc>=-1 && pc<p->nOp );
65974
65975 #ifdef SQLITE_DEBUG
65976     if( p->trace ){
65977       if( rc!=0 ) fprintf(p->trace,"rc=%d\n",rc);
65978       if( pOp->opflags & (OPFLG_OUT2_PRERELEASE|OPFLG_OUT2) ){
65979         registerTrace(p->trace, pOp->p2, &aMem[pOp->p2]);
65980       }
65981       if( pOp->opflags & OPFLG_OUT3 ){
65982         registerTrace(p->trace, pOp->p3, &aMem[pOp->p3]);
65983       }
65984     }
65985 #endif  /* SQLITE_DEBUG */
65986 #endif  /* NDEBUG */
65987   }  /* The end of the for(;;) loop the loops through opcodes */
65988
65989   /* If we reach this point, it means that execution is finished with
65990   ** an error of some kind.
65991   */
65992 vdbe_error_halt:
65993   assert( rc );
65994   p->rc = rc;
65995   testcase( sqlite3GlobalConfig.xLog!=0 );
65996   sqlite3_log(rc, "statement aborts at %d: [%s] %s", 
65997                    pc, p->zSql, p->zErrMsg);
65998   sqlite3VdbeHalt(p);
65999   if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
66000   rc = SQLITE_ERROR;
66001   if( resetSchemaOnFault ) sqlite3ResetInternalSchema(db, 0);
66002
66003   /* This is the only way out of this procedure.  We have to
66004   ** release the mutexes on btrees that were acquired at the
66005   ** top. */
66006 vdbe_return:
66007   sqlite3BtreeMutexArrayLeave(&p->aMutex);
66008   return rc;
66009
66010   /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
66011   ** is encountered.
66012   */
66013 too_big:
66014   sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
66015   rc = SQLITE_TOOBIG;
66016   goto vdbe_error_halt;
66017
66018   /* Jump to here if a malloc() fails.
66019   */
66020 no_mem:
66021   db->mallocFailed = 1;
66022   sqlite3SetString(&p->zErrMsg, db, "out of memory");
66023   rc = SQLITE_NOMEM;
66024   goto vdbe_error_halt;
66025
66026   /* Jump to here for any other kind of fatal error.  The "rc" variable
66027   ** should hold the error number.
66028   */
66029 abort_due_to_error:
66030   assert( p->zErrMsg==0 );
66031   if( db->mallocFailed ) rc = SQLITE_NOMEM;
66032   if( rc!=SQLITE_IOERR_NOMEM ){
66033     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
66034   }
66035   goto vdbe_error_halt;
66036
66037   /* Jump to here if the sqlite3_interrupt() API sets the interrupt
66038   ** flag.
66039   */
66040 abort_due_to_interrupt:
66041   assert( db->u1.isInterrupted );
66042   rc = SQLITE_INTERRUPT;
66043   p->rc = rc;
66044   sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
66045   goto vdbe_error_halt;
66046 }
66047
66048 /************** End of vdbe.c ************************************************/
66049 /************** Begin file vdbeblob.c ****************************************/
66050 /*
66051 ** 2007 May 1
66052 **
66053 ** The author disclaims copyright to this source code.  In place of
66054 ** a legal notice, here is a blessing:
66055 **
66056 **    May you do good and not evil.
66057 **    May you find forgiveness for yourself and forgive others.
66058 **    May you share freely, never taking more than you give.
66059 **
66060 *************************************************************************
66061 **
66062 ** This file contains code used to implement incremental BLOB I/O.
66063 */
66064
66065
66066 #ifndef SQLITE_OMIT_INCRBLOB
66067
66068 /*
66069 ** Valid sqlite3_blob* handles point to Incrblob structures.
66070 */
66071 typedef struct Incrblob Incrblob;
66072 struct Incrblob {
66073   int flags;              /* Copy of "flags" passed to sqlite3_blob_open() */
66074   int nByte;              /* Size of open blob, in bytes */
66075   int iOffset;            /* Byte offset of blob in cursor data */
66076   BtCursor *pCsr;         /* Cursor pointing at blob row */
66077   sqlite3_stmt *pStmt;    /* Statement holding cursor open */
66078   sqlite3 *db;            /* The associated database */
66079 };
66080
66081 /*
66082 ** Open a blob handle.
66083 */
66084 SQLITE_API int sqlite3_blob_open(
66085   sqlite3* db,            /* The database connection */
66086   const char *zDb,        /* The attached database containing the blob */
66087   const char *zTable,     /* The table containing the blob */
66088   const char *zColumn,    /* The column containing the blob */
66089   sqlite_int64 iRow,      /* The row containing the glob */
66090   int flags,              /* True -> read/write access, false -> read-only */
66091   sqlite3_blob **ppBlob   /* Handle for accessing the blob returned here */
66092 ){
66093   int nAttempt = 0;
66094   int iCol;               /* Index of zColumn in row-record */
66095
66096   /* This VDBE program seeks a btree cursor to the identified 
66097   ** db/table/row entry. The reason for using a vdbe program instead
66098   ** of writing code to use the b-tree layer directly is that the
66099   ** vdbe program will take advantage of the various transaction,
66100   ** locking and error handling infrastructure built into the vdbe.
66101   **
66102   ** After seeking the cursor, the vdbe executes an OP_ResultRow.
66103   ** Code external to the Vdbe then "borrows" the b-tree cursor and
66104   ** uses it to implement the blob_read(), blob_write() and 
66105   ** blob_bytes() functions.
66106   **
66107   ** The sqlite3_blob_close() function finalizes the vdbe program,
66108   ** which closes the b-tree cursor and (possibly) commits the 
66109   ** transaction.
66110   */
66111   static const VdbeOpList openBlob[] = {
66112     {OP_Transaction, 0, 0, 0},     /* 0: Start a transaction */
66113     {OP_VerifyCookie, 0, 0, 0},    /* 1: Check the schema cookie */
66114     {OP_TableLock, 0, 0, 0},       /* 2: Acquire a read or write lock */
66115
66116     /* One of the following two instructions is replaced by an OP_Noop. */
66117     {OP_OpenRead, 0, 0, 0},        /* 3: Open cursor 0 for reading */
66118     {OP_OpenWrite, 0, 0, 0},       /* 4: Open cursor 0 for read/write */
66119
66120     {OP_Variable, 1, 1, 1},        /* 5: Push the rowid to the stack */
66121     {OP_NotExists, 0, 9, 1},       /* 6: Seek the cursor */
66122     {OP_Column, 0, 0, 1},          /* 7  */
66123     {OP_ResultRow, 1, 0, 0},       /* 8  */
66124     {OP_Close, 0, 0, 0},           /* 9  */
66125     {OP_Halt, 0, 0, 0},            /* 10 */
66126   };
66127
66128   Vdbe *v = 0;
66129   int rc = SQLITE_OK;
66130   char *zErr = 0;
66131   Table *pTab;
66132   Parse *pParse;
66133
66134   *ppBlob = 0;
66135   sqlite3_mutex_enter(db->mutex);
66136   pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
66137   if( pParse==0 ){
66138     rc = SQLITE_NOMEM;
66139     goto blob_open_out;
66140   }
66141   do {
66142     memset(pParse, 0, sizeof(Parse));
66143     pParse->db = db;
66144
66145     sqlite3BtreeEnterAll(db);
66146     pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
66147     if( pTab && IsVirtual(pTab) ){
66148       pTab = 0;
66149       sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
66150     }
66151 #ifndef SQLITE_OMIT_VIEW
66152     if( pTab && pTab->pSelect ){
66153       pTab = 0;
66154       sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
66155     }
66156 #endif
66157     if( !pTab ){
66158       if( pParse->zErrMsg ){
66159         sqlite3DbFree(db, zErr);
66160         zErr = pParse->zErrMsg;
66161         pParse->zErrMsg = 0;
66162       }
66163       rc = SQLITE_ERROR;
66164       sqlite3BtreeLeaveAll(db);
66165       goto blob_open_out;
66166     }
66167
66168     /* Now search pTab for the exact column. */
66169     for(iCol=0; iCol < pTab->nCol; iCol++) {
66170       if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
66171         break;
66172       }
66173     }
66174     if( iCol==pTab->nCol ){
66175       sqlite3DbFree(db, zErr);
66176       zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
66177       rc = SQLITE_ERROR;
66178       sqlite3BtreeLeaveAll(db);
66179       goto blob_open_out;
66180     }
66181
66182     /* If the value is being opened for writing, check that the
66183     ** column is not indexed, and that it is not part of a foreign key. 
66184     ** It is against the rules to open a column to which either of these
66185     ** descriptions applies for writing.  */
66186     if( flags ){
66187       const char *zFault = 0;
66188       Index *pIdx;
66189 #ifndef SQLITE_OMIT_FOREIGN_KEY
66190       if( db->flags&SQLITE_ForeignKeys ){
66191         /* Check that the column is not part of an FK child key definition. It
66192         ** is not necessary to check if it is part of a parent key, as parent
66193         ** key columns must be indexed. The check below will pick up this 
66194         ** case.  */
66195         FKey *pFKey;
66196         for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
66197           int j;
66198           for(j=0; j<pFKey->nCol; j++){
66199             if( pFKey->aCol[j].iFrom==iCol ){
66200               zFault = "foreign key";
66201             }
66202           }
66203         }
66204       }
66205 #endif
66206       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
66207         int j;
66208         for(j=0; j<pIdx->nColumn; j++){
66209           if( pIdx->aiColumn[j]==iCol ){
66210             zFault = "indexed";
66211           }
66212         }
66213       }
66214       if( zFault ){
66215         sqlite3DbFree(db, zErr);
66216         zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
66217         rc = SQLITE_ERROR;
66218         sqlite3BtreeLeaveAll(db);
66219         goto blob_open_out;
66220       }
66221     }
66222
66223     v = sqlite3VdbeCreate(db);
66224     if( v ){
66225       int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
66226       sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
66227       flags = !!flags;                 /* flags = (flags ? 1 : 0); */
66228
66229       /* Configure the OP_Transaction */
66230       sqlite3VdbeChangeP1(v, 0, iDb);
66231       sqlite3VdbeChangeP2(v, 0, flags);
66232
66233       /* Configure the OP_VerifyCookie */
66234       sqlite3VdbeChangeP1(v, 1, iDb);
66235       sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);
66236
66237       /* Make sure a mutex is held on the table to be accessed */
66238       sqlite3VdbeUsesBtree(v, iDb); 
66239
66240       /* Configure the OP_TableLock instruction */
66241 #ifdef SQLITE_OMIT_SHARED_CACHE
66242       sqlite3VdbeChangeToNoop(v, 2, 1);
66243 #else
66244       sqlite3VdbeChangeP1(v, 2, iDb);
66245       sqlite3VdbeChangeP2(v, 2, pTab->tnum);
66246       sqlite3VdbeChangeP3(v, 2, flags);
66247       sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
66248 #endif
66249
66250       /* Remove either the OP_OpenWrite or OpenRead. Set the P2 
66251       ** parameter of the other to pTab->tnum.  */
66252       sqlite3VdbeChangeToNoop(v, 4 - flags, 1);
66253       sqlite3VdbeChangeP2(v, 3 + flags, pTab->tnum);
66254       sqlite3VdbeChangeP3(v, 3 + flags, iDb);
66255
66256       /* Configure the number of columns. Configure the cursor to
66257       ** think that the table has one more column than it really
66258       ** does. An OP_Column to retrieve this imaginary column will
66259       ** always return an SQL NULL. This is useful because it means
66260       ** we can invoke OP_Column to fill in the vdbe cursors type 
66261       ** and offset cache without causing any IO.
66262       */
66263       sqlite3VdbeChangeP4(v, 3+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
66264       sqlite3VdbeChangeP2(v, 7, pTab->nCol);
66265       if( !db->mallocFailed ){
66266         sqlite3VdbeMakeReady(v, 1, 1, 1, 0, 0, 0);
66267       }
66268     }
66269    
66270     sqlite3BtreeLeaveAll(db);
66271     if( db->mallocFailed ){
66272       goto blob_open_out;
66273     }
66274
66275     sqlite3_bind_int64((sqlite3_stmt *)v, 1, iRow);
66276     rc = sqlite3_step((sqlite3_stmt *)v);
66277     if( rc!=SQLITE_ROW ){
66278       nAttempt++;
66279       rc = sqlite3_finalize((sqlite3_stmt *)v);
66280       sqlite3DbFree(db, zErr);
66281       zErr = sqlite3MPrintf(db, sqlite3_errmsg(db));
66282       v = 0;
66283     }
66284   } while( nAttempt<5 && rc==SQLITE_SCHEMA );
66285
66286   if( rc==SQLITE_ROW ){
66287     /* The row-record has been opened successfully. Check that the
66288     ** column in question contains text or a blob. If it contains
66289     ** text, it is up to the caller to get the encoding right.
66290     */
66291     Incrblob *pBlob;
66292     u32 type = v->apCsr[0]->aType[iCol];
66293
66294     if( type<12 ){
66295       sqlite3DbFree(db, zErr);
66296       zErr = sqlite3MPrintf(db, "cannot open value of type %s",
66297           type==0?"null": type==7?"real": "integer"
66298       );
66299       rc = SQLITE_ERROR;
66300       goto blob_open_out;
66301     }
66302     pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
66303     if( db->mallocFailed ){
66304       sqlite3DbFree(db, pBlob);
66305       goto blob_open_out;
66306     }
66307     pBlob->flags = flags;
66308     pBlob->pCsr =  v->apCsr[0]->pCursor;
66309     sqlite3BtreeEnterCursor(pBlob->pCsr);
66310     sqlite3BtreeCacheOverflow(pBlob->pCsr);
66311     sqlite3BtreeLeaveCursor(pBlob->pCsr);
66312     pBlob->pStmt = (sqlite3_stmt *)v;
66313     pBlob->iOffset = v->apCsr[0]->aOffset[iCol];
66314     pBlob->nByte = sqlite3VdbeSerialTypeLen(type);
66315     pBlob->db = db;
66316     *ppBlob = (sqlite3_blob *)pBlob;
66317     rc = SQLITE_OK;
66318   }else if( rc==SQLITE_OK ){
66319     sqlite3DbFree(db, zErr);
66320     zErr = sqlite3MPrintf(db, "no such rowid: %lld", iRow);
66321     rc = SQLITE_ERROR;
66322   }
66323
66324 blob_open_out:
66325   if( v && (rc!=SQLITE_OK || db->mallocFailed) ){
66326     sqlite3VdbeFinalize(v);
66327   }
66328   sqlite3Error(db, rc, zErr);
66329   sqlite3DbFree(db, zErr);
66330   sqlite3StackFree(db, pParse);
66331   rc = sqlite3ApiExit(db, rc);
66332   sqlite3_mutex_leave(db->mutex);
66333   return rc;
66334 }
66335
66336 /*
66337 ** Close a blob handle that was previously created using
66338 ** sqlite3_blob_open().
66339 */
66340 SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
66341   Incrblob *p = (Incrblob *)pBlob;
66342   int rc;
66343   sqlite3 *db;
66344
66345   if( p ){
66346     db = p->db;
66347     sqlite3_mutex_enter(db->mutex);
66348     rc = sqlite3_finalize(p->pStmt);
66349     sqlite3DbFree(db, p);
66350     sqlite3_mutex_leave(db->mutex);
66351   }else{
66352     rc = SQLITE_OK;
66353   }
66354   return rc;
66355 }
66356
66357 /*
66358 ** Perform a read or write operation on a blob
66359 */
66360 static int blobReadWrite(
66361   sqlite3_blob *pBlob, 
66362   void *z, 
66363   int n, 
66364   int iOffset, 
66365   int (*xCall)(BtCursor*, u32, u32, void*)
66366 ){
66367   int rc;
66368   Incrblob *p = (Incrblob *)pBlob;
66369   Vdbe *v;
66370   sqlite3 *db;
66371
66372   if( p==0 ) return SQLITE_MISUSE_BKPT;
66373   db = p->db;
66374   sqlite3_mutex_enter(db->mutex);
66375   v = (Vdbe*)p->pStmt;
66376
66377   if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
66378     /* Request is out of range. Return a transient error. */
66379     rc = SQLITE_ERROR;
66380     sqlite3Error(db, SQLITE_ERROR, 0);
66381   } else if( v==0 ){
66382     /* If there is no statement handle, then the blob-handle has
66383     ** already been invalidated. Return SQLITE_ABORT in this case.
66384     */
66385     rc = SQLITE_ABORT;
66386   }else{
66387     /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
66388     ** returned, clean-up the statement handle.
66389     */
66390     assert( db == v->db );
66391     sqlite3BtreeEnterCursor(p->pCsr);
66392     rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
66393     sqlite3BtreeLeaveCursor(p->pCsr);
66394     if( rc==SQLITE_ABORT ){
66395       sqlite3VdbeFinalize(v);
66396       p->pStmt = 0;
66397     }else{
66398       db->errCode = rc;
66399       v->rc = rc;
66400     }
66401   }
66402   rc = sqlite3ApiExit(db, rc);
66403   sqlite3_mutex_leave(db->mutex);
66404   return rc;
66405 }
66406
66407 /*
66408 ** Read data from a blob handle.
66409 */
66410 SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
66411   return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
66412 }
66413
66414 /*
66415 ** Write data to a blob handle.
66416 */
66417 SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
66418   return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
66419 }
66420
66421 /*
66422 ** Query a blob handle for the size of the data.
66423 **
66424 ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
66425 ** so no mutex is required for access.
66426 */
66427 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
66428   Incrblob *p = (Incrblob *)pBlob;
66429   return p ? p->nByte : 0;
66430 }
66431
66432 #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
66433
66434 /************** End of vdbeblob.c ********************************************/
66435 /************** Begin file journal.c *****************************************/
66436 /*
66437 ** 2007 August 22
66438 **
66439 ** The author disclaims copyright to this source code.  In place of
66440 ** a legal notice, here is a blessing:
66441 **
66442 **    May you do good and not evil.
66443 **    May you find forgiveness for yourself and forgive others.
66444 **    May you share freely, never taking more than you give.
66445 **
66446 *************************************************************************
66447 **
66448 ** This file implements a special kind of sqlite3_file object used
66449 ** by SQLite to create journal files if the atomic-write optimization
66450 ** is enabled.
66451 **
66452 ** The distinctive characteristic of this sqlite3_file is that the
66453 ** actual on disk file is created lazily. When the file is created,
66454 ** the caller specifies a buffer size for an in-memory buffer to
66455 ** be used to service read() and write() requests. The actual file
66456 ** on disk is not created or populated until either:
66457 **
66458 **   1) The in-memory representation grows too large for the allocated 
66459 **      buffer, or
66460 **   2) The sqlite3JournalCreate() function is called.
66461 */
66462 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
66463
66464
66465 /*
66466 ** A JournalFile object is a subclass of sqlite3_file used by
66467 ** as an open file handle for journal files.
66468 */
66469 struct JournalFile {
66470   sqlite3_io_methods *pMethod;    /* I/O methods on journal files */
66471   int nBuf;                       /* Size of zBuf[] in bytes */
66472   char *zBuf;                     /* Space to buffer journal writes */
66473   int iSize;                      /* Amount of zBuf[] currently used */
66474   int flags;                      /* xOpen flags */
66475   sqlite3_vfs *pVfs;              /* The "real" underlying VFS */
66476   sqlite3_file *pReal;            /* The "real" underlying file descriptor */
66477   const char *zJournal;           /* Name of the journal file */
66478 };
66479 typedef struct JournalFile JournalFile;
66480
66481 /*
66482 ** If it does not already exists, create and populate the on-disk file 
66483 ** for JournalFile p.
66484 */
66485 static int createFile(JournalFile *p){
66486   int rc = SQLITE_OK;
66487   if( !p->pReal ){
66488     sqlite3_file *pReal = (sqlite3_file *)&p[1];
66489     rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
66490     if( rc==SQLITE_OK ){
66491       p->pReal = pReal;
66492       if( p->iSize>0 ){
66493         assert(p->iSize<=p->nBuf);
66494         rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
66495       }
66496     }
66497   }
66498   return rc;
66499 }
66500
66501 /*
66502 ** Close the file.
66503 */
66504 static int jrnlClose(sqlite3_file *pJfd){
66505   JournalFile *p = (JournalFile *)pJfd;
66506   if( p->pReal ){
66507     sqlite3OsClose(p->pReal);
66508   }
66509   sqlite3_free(p->zBuf);
66510   return SQLITE_OK;
66511 }
66512
66513 /*
66514 ** Read data from the file.
66515 */
66516 static int jrnlRead(
66517   sqlite3_file *pJfd,    /* The journal file from which to read */
66518   void *zBuf,            /* Put the results here */
66519   int iAmt,              /* Number of bytes to read */
66520   sqlite_int64 iOfst     /* Begin reading at this offset */
66521 ){
66522   int rc = SQLITE_OK;
66523   JournalFile *p = (JournalFile *)pJfd;
66524   if( p->pReal ){
66525     rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
66526   }else if( (iAmt+iOfst)>p->iSize ){
66527     rc = SQLITE_IOERR_SHORT_READ;
66528   }else{
66529     memcpy(zBuf, &p->zBuf[iOfst], iAmt);
66530   }
66531   return rc;
66532 }
66533
66534 /*
66535 ** Write data to the file.
66536 */
66537 static int jrnlWrite(
66538   sqlite3_file *pJfd,    /* The journal file into which to write */
66539   const void *zBuf,      /* Take data to be written from here */
66540   int iAmt,              /* Number of bytes to write */
66541   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
66542 ){
66543   int rc = SQLITE_OK;
66544   JournalFile *p = (JournalFile *)pJfd;
66545   if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
66546     rc = createFile(p);
66547   }
66548   if( rc==SQLITE_OK ){
66549     if( p->pReal ){
66550       rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
66551     }else{
66552       memcpy(&p->zBuf[iOfst], zBuf, iAmt);
66553       if( p->iSize<(iOfst+iAmt) ){
66554         p->iSize = (iOfst+iAmt);
66555       }
66556     }
66557   }
66558   return rc;
66559 }
66560
66561 /*
66562 ** Truncate the file.
66563 */
66564 static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
66565   int rc = SQLITE_OK;
66566   JournalFile *p = (JournalFile *)pJfd;
66567   if( p->pReal ){
66568     rc = sqlite3OsTruncate(p->pReal, size);
66569   }else if( size<p->iSize ){
66570     p->iSize = size;
66571   }
66572   return rc;
66573 }
66574
66575 /*
66576 ** Sync the file.
66577 */
66578 static int jrnlSync(sqlite3_file *pJfd, int flags){
66579   int rc;
66580   JournalFile *p = (JournalFile *)pJfd;
66581   if( p->pReal ){
66582     rc = sqlite3OsSync(p->pReal, flags);
66583   }else{
66584     rc = SQLITE_OK;
66585   }
66586   return rc;
66587 }
66588
66589 /*
66590 ** Query the size of the file in bytes.
66591 */
66592 static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
66593   int rc = SQLITE_OK;
66594   JournalFile *p = (JournalFile *)pJfd;
66595   if( p->pReal ){
66596     rc = sqlite3OsFileSize(p->pReal, pSize);
66597   }else{
66598     *pSize = (sqlite_int64) p->iSize;
66599   }
66600   return rc;
66601 }
66602
66603 /*
66604 ** Table of methods for JournalFile sqlite3_file object.
66605 */
66606 static struct sqlite3_io_methods JournalFileMethods = {
66607   1,             /* iVersion */
66608   jrnlClose,     /* xClose */
66609   jrnlRead,      /* xRead */
66610   jrnlWrite,     /* xWrite */
66611   jrnlTruncate,  /* xTruncate */
66612   jrnlSync,      /* xSync */
66613   jrnlFileSize,  /* xFileSize */
66614   0,             /* xLock */
66615   0,             /* xUnlock */
66616   0,             /* xCheckReservedLock */
66617   0,             /* xFileControl */
66618   0,             /* xSectorSize */
66619   0,             /* xDeviceCharacteristics */
66620   0,             /* xShmMap */
66621   0,             /* xShmLock */
66622   0,             /* xShmBarrier */
66623   0              /* xShmUnmap */
66624 };
66625
66626 /* 
66627 ** Open a journal file.
66628 */
66629 SQLITE_PRIVATE int sqlite3JournalOpen(
66630   sqlite3_vfs *pVfs,         /* The VFS to use for actual file I/O */
66631   const char *zName,         /* Name of the journal file */
66632   sqlite3_file *pJfd,        /* Preallocated, blank file handle */
66633   int flags,                 /* Opening flags */
66634   int nBuf                   /* Bytes buffered before opening the file */
66635 ){
66636   JournalFile *p = (JournalFile *)pJfd;
66637   memset(p, 0, sqlite3JournalSize(pVfs));
66638   if( nBuf>0 ){
66639     p->zBuf = sqlite3MallocZero(nBuf);
66640     if( !p->zBuf ){
66641       return SQLITE_NOMEM;
66642     }
66643   }else{
66644     return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
66645   }
66646   p->pMethod = &JournalFileMethods;
66647   p->nBuf = nBuf;
66648   p->flags = flags;
66649   p->zJournal = zName;
66650   p->pVfs = pVfs;
66651   return SQLITE_OK;
66652 }
66653
66654 /*
66655 ** If the argument p points to a JournalFile structure, and the underlying
66656 ** file has not yet been created, create it now.
66657 */
66658 SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
66659   if( p->pMethods!=&JournalFileMethods ){
66660     return SQLITE_OK;
66661   }
66662   return createFile((JournalFile *)p);
66663 }
66664
66665 /* 
66666 ** Return the number of bytes required to store a JournalFile that uses vfs
66667 ** pVfs to create the underlying on-disk files.
66668 */
66669 SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
66670   return (pVfs->szOsFile+sizeof(JournalFile));
66671 }
66672 #endif
66673
66674 /************** End of journal.c *********************************************/
66675 /************** Begin file memjournal.c **************************************/
66676 /*
66677 ** 2008 October 7
66678 **
66679 ** The author disclaims copyright to this source code.  In place of
66680 ** a legal notice, here is a blessing:
66681 **
66682 **    May you do good and not evil.
66683 **    May you find forgiveness for yourself and forgive others.
66684 **    May you share freely, never taking more than you give.
66685 **
66686 *************************************************************************
66687 **
66688 ** This file contains code use to implement an in-memory rollback journal.
66689 ** The in-memory rollback journal is used to journal transactions for
66690 ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
66691 */
66692
66693 /* Forward references to internal structures */
66694 typedef struct MemJournal MemJournal;
66695 typedef struct FilePoint FilePoint;
66696 typedef struct FileChunk FileChunk;
66697
66698 /* Space to hold the rollback journal is allocated in increments of
66699 ** this many bytes.
66700 **
66701 ** The size chosen is a little less than a power of two.  That way,
66702 ** the FileChunk object will have a size that almost exactly fills
66703 ** a power-of-two allocation.  This mimimizes wasted space in power-of-two
66704 ** memory allocators.
66705 */
66706 #define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
66707
66708 /* Macro to find the minimum of two numeric values.
66709 */
66710 #ifndef MIN
66711 # define MIN(x,y) ((x)<(y)?(x):(y))
66712 #endif
66713
66714 /*
66715 ** The rollback journal is composed of a linked list of these structures.
66716 */
66717 struct FileChunk {
66718   FileChunk *pNext;               /* Next chunk in the journal */
66719   u8 zChunk[JOURNAL_CHUNKSIZE];   /* Content of this chunk */
66720 };
66721
66722 /*
66723 ** An instance of this object serves as a cursor into the rollback journal.
66724 ** The cursor can be either for reading or writing.
66725 */
66726 struct FilePoint {
66727   sqlite3_int64 iOffset;          /* Offset from the beginning of the file */
66728   FileChunk *pChunk;              /* Specific chunk into which cursor points */
66729 };
66730
66731 /*
66732 ** This subclass is a subclass of sqlite3_file.  Each open memory-journal
66733 ** is an instance of this class.
66734 */
66735 struct MemJournal {
66736   sqlite3_io_methods *pMethod;    /* Parent class. MUST BE FIRST */
66737   FileChunk *pFirst;              /* Head of in-memory chunk-list */
66738   FilePoint endpoint;             /* Pointer to the end of the file */
66739   FilePoint readpoint;            /* Pointer to the end of the last xRead() */
66740 };
66741
66742 /*
66743 ** Read data from the in-memory journal file.  This is the implementation
66744 ** of the sqlite3_vfs.xRead method.
66745 */
66746 static int memjrnlRead(
66747   sqlite3_file *pJfd,    /* The journal file from which to read */
66748   void *zBuf,            /* Put the results here */
66749   int iAmt,              /* Number of bytes to read */
66750   sqlite_int64 iOfst     /* Begin reading at this offset */
66751 ){
66752   MemJournal *p = (MemJournal *)pJfd;
66753   u8 *zOut = zBuf;
66754   int nRead = iAmt;
66755   int iChunkOffset;
66756   FileChunk *pChunk;
66757
66758   /* SQLite never tries to read past the end of a rollback journal file */
66759   assert( iOfst+iAmt<=p->endpoint.iOffset );
66760
66761   if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
66762     sqlite3_int64 iOff = 0;
66763     for(pChunk=p->pFirst; 
66764         ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
66765         pChunk=pChunk->pNext
66766     ){
66767       iOff += JOURNAL_CHUNKSIZE;
66768     }
66769   }else{
66770     pChunk = p->readpoint.pChunk;
66771   }
66772
66773   iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
66774   do {
66775     int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
66776     int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
66777     memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
66778     zOut += nCopy;
66779     nRead -= iSpace;
66780     iChunkOffset = 0;
66781   } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
66782   p->readpoint.iOffset = iOfst+iAmt;
66783   p->readpoint.pChunk = pChunk;
66784
66785   return SQLITE_OK;
66786 }
66787
66788 /*
66789 ** Write data to the file.
66790 */
66791 static int memjrnlWrite(
66792   sqlite3_file *pJfd,    /* The journal file into which to write */
66793   const void *zBuf,      /* Take data to be written from here */
66794   int iAmt,              /* Number of bytes to write */
66795   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
66796 ){
66797   MemJournal *p = (MemJournal *)pJfd;
66798   int nWrite = iAmt;
66799   u8 *zWrite = (u8 *)zBuf;
66800
66801   /* An in-memory journal file should only ever be appended to. Random
66802   ** access writes are not required by sqlite.
66803   */
66804   assert( iOfst==p->endpoint.iOffset );
66805   UNUSED_PARAMETER(iOfst);
66806
66807   while( nWrite>0 ){
66808     FileChunk *pChunk = p->endpoint.pChunk;
66809     int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
66810     int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
66811
66812     if( iChunkOffset==0 ){
66813       /* New chunk is required to extend the file. */
66814       FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
66815       if( !pNew ){
66816         return SQLITE_IOERR_NOMEM;
66817       }
66818       pNew->pNext = 0;
66819       if( pChunk ){
66820         assert( p->pFirst );
66821         pChunk->pNext = pNew;
66822       }else{
66823         assert( !p->pFirst );
66824         p->pFirst = pNew;
66825       }
66826       p->endpoint.pChunk = pNew;
66827     }
66828
66829     memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
66830     zWrite += iSpace;
66831     nWrite -= iSpace;
66832     p->endpoint.iOffset += iSpace;
66833   }
66834
66835   return SQLITE_OK;
66836 }
66837
66838 /*
66839 ** Truncate the file.
66840 */
66841 static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
66842   MemJournal *p = (MemJournal *)pJfd;
66843   FileChunk *pChunk;
66844   assert(size==0);
66845   UNUSED_PARAMETER(size);
66846   pChunk = p->pFirst;
66847   while( pChunk ){
66848     FileChunk *pTmp = pChunk;
66849     pChunk = pChunk->pNext;
66850     sqlite3_free(pTmp);
66851   }
66852   sqlite3MemJournalOpen(pJfd);
66853   return SQLITE_OK;
66854 }
66855
66856 /*
66857 ** Close the file.
66858 */
66859 static int memjrnlClose(sqlite3_file *pJfd){
66860   memjrnlTruncate(pJfd, 0);
66861   return SQLITE_OK;
66862 }
66863
66864
66865 /*
66866 ** Sync the file.
66867 **
66868 ** Syncing an in-memory journal is a no-op.  And, in fact, this routine
66869 ** is never called in a working implementation.  This implementation
66870 ** exists purely as a contingency, in case some malfunction in some other
66871 ** part of SQLite causes Sync to be called by mistake.
66872 */
66873 static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){
66874   UNUSED_PARAMETER2(NotUsed, NotUsed2);
66875   return SQLITE_OK;
66876 }
66877
66878 /*
66879 ** Query the size of the file in bytes.
66880 */
66881 static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
66882   MemJournal *p = (MemJournal *)pJfd;
66883   *pSize = (sqlite_int64) p->endpoint.iOffset;
66884   return SQLITE_OK;
66885 }
66886
66887 /*
66888 ** Table of methods for MemJournal sqlite3_file object.
66889 */
66890 static const struct sqlite3_io_methods MemJournalMethods = {
66891   1,                /* iVersion */
66892   memjrnlClose,     /* xClose */
66893   memjrnlRead,      /* xRead */
66894   memjrnlWrite,     /* xWrite */
66895   memjrnlTruncate,  /* xTruncate */
66896   memjrnlSync,      /* xSync */
66897   memjrnlFileSize,  /* xFileSize */
66898   0,                /* xLock */
66899   0,                /* xUnlock */
66900   0,                /* xCheckReservedLock */
66901   0,                /* xFileControl */
66902   0,                /* xSectorSize */
66903   0,                /* xDeviceCharacteristics */
66904   0,                /* xShmMap */
66905   0,                /* xShmLock */
66906   0,                /* xShmBarrier */
66907   0                 /* xShmUnlock */
66908 };
66909
66910 /* 
66911 ** Open a journal file.
66912 */
66913 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
66914   MemJournal *p = (MemJournal *)pJfd;
66915   assert( EIGHT_BYTE_ALIGNMENT(p) );
66916   memset(p, 0, sqlite3MemJournalSize());
66917   p->pMethod = (sqlite3_io_methods*)&MemJournalMethods;
66918 }
66919
66920 /*
66921 ** Return true if the file-handle passed as an argument is 
66922 ** an in-memory journal 
66923 */
66924 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
66925   return pJfd->pMethods==&MemJournalMethods;
66926 }
66927
66928 /* 
66929 ** Return the number of bytes required to store a MemJournal file descriptor.
66930 */
66931 SQLITE_PRIVATE int sqlite3MemJournalSize(void){
66932   return sizeof(MemJournal);
66933 }
66934
66935 /************** End of memjournal.c ******************************************/
66936 /************** Begin file walker.c ******************************************/
66937 /*
66938 ** 2008 August 16
66939 **
66940 ** The author disclaims copyright to this source code.  In place of
66941 ** a legal notice, here is a blessing:
66942 **
66943 **    May you do good and not evil.
66944 **    May you find forgiveness for yourself and forgive others.
66945 **    May you share freely, never taking more than you give.
66946 **
66947 *************************************************************************
66948 ** This file contains routines used for walking the parser tree for
66949 ** an SQL statement.
66950 */
66951
66952
66953 /*
66954 ** Walk an expression tree.  Invoke the callback once for each node
66955 ** of the expression, while decending.  (In other words, the callback
66956 ** is invoked before visiting children.)
66957 **
66958 ** The return value from the callback should be one of the WRC_*
66959 ** constants to specify how to proceed with the walk.
66960 **
66961 **    WRC_Continue      Continue descending down the tree.
66962 **
66963 **    WRC_Prune         Do not descend into child nodes.  But allow
66964 **                      the walk to continue with sibling nodes.
66965 **
66966 **    WRC_Abort         Do no more callbacks.  Unwind the stack and
66967 **                      return the top-level walk call.
66968 **
66969 ** The return value from this routine is WRC_Abort to abandon the tree walk
66970 ** and WRC_Continue to continue.
66971 */
66972 SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
66973   int rc;
66974   if( pExpr==0 ) return WRC_Continue;
66975   testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
66976   testcase( ExprHasProperty(pExpr, EP_Reduced) );
66977   rc = pWalker->xExprCallback(pWalker, pExpr);
66978   if( rc==WRC_Continue
66979               && !ExprHasAnyProperty(pExpr,EP_TokenOnly) ){
66980     if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
66981     if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
66982     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
66983       if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
66984     }else{
66985       if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
66986     }
66987   }
66988   return rc & WRC_Abort;
66989 }
66990
66991 /*
66992 ** Call sqlite3WalkExpr() for every expression in list p or until
66993 ** an abort request is seen.
66994 */
66995 SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
66996   int i;
66997   struct ExprList_item *pItem;
66998   if( p ){
66999     for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
67000       if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
67001     }
67002   }
67003   return WRC_Continue;
67004 }
67005
67006 /*
67007 ** Walk all expressions associated with SELECT statement p.  Do
67008 ** not invoke the SELECT callback on p, but do (of course) invoke
67009 ** any expr callbacks and SELECT callbacks that come from subqueries.
67010 ** Return WRC_Abort or WRC_Continue.
67011 */
67012 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
67013   if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
67014   if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
67015   if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
67016   if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
67017   if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
67018   if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
67019   if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
67020   return WRC_Continue;
67021 }
67022
67023 /*
67024 ** Walk the parse trees associated with all subqueries in the
67025 ** FROM clause of SELECT statement p.  Do not invoke the select
67026 ** callback on p, but do invoke it on each FROM clause subquery
67027 ** and on any subqueries further down in the tree.  Return 
67028 ** WRC_Abort or WRC_Continue;
67029 */
67030 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
67031   SrcList *pSrc;
67032   int i;
67033   struct SrcList_item *pItem;
67034
67035   pSrc = p->pSrc;
67036   if( ALWAYS(pSrc) ){
67037     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
67038       if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
67039         return WRC_Abort;
67040       }
67041     }
67042   }
67043   return WRC_Continue;
67044
67045
67046 /*
67047 ** Call sqlite3WalkExpr() for every expression in Select statement p.
67048 ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
67049 ** on the compound select chain, p->pPrior.
67050 **
67051 ** Return WRC_Continue under normal conditions.  Return WRC_Abort if
67052 ** there is an abort request.
67053 **
67054 ** If the Walker does not have an xSelectCallback() then this routine
67055 ** is a no-op returning WRC_Continue.
67056 */
67057 SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
67058   int rc;
67059   if( p==0 || pWalker->xSelectCallback==0 ) return WRC_Continue;
67060   rc = WRC_Continue;
67061   while( p  ){
67062     rc = pWalker->xSelectCallback(pWalker, p);
67063     if( rc ) break;
67064     if( sqlite3WalkSelectExpr(pWalker, p) ) return WRC_Abort;
67065     if( sqlite3WalkSelectFrom(pWalker, p) ) return WRC_Abort;
67066     p = p->pPrior;
67067   }
67068   return rc & WRC_Abort;
67069 }
67070
67071 /************** End of walker.c **********************************************/
67072 /************** Begin file resolve.c *****************************************/
67073 /*
67074 ** 2008 August 18
67075 **
67076 ** The author disclaims copyright to this source code.  In place of
67077 ** a legal notice, here is a blessing:
67078 **
67079 **    May you do good and not evil.
67080 **    May you find forgiveness for yourself and forgive others.
67081 **    May you share freely, never taking more than you give.
67082 **
67083 *************************************************************************
67084 **
67085 ** This file contains routines used for walking the parser tree and
67086 ** resolve all identifiers by associating them with a particular
67087 ** table and column.
67088 */
67089
67090 /*
67091 ** Turn the pExpr expression into an alias for the iCol-th column of the
67092 ** result set in pEList.
67093 **
67094 ** If the result set column is a simple column reference, then this routine
67095 ** makes an exact copy.  But for any other kind of expression, this
67096 ** routine make a copy of the result set column as the argument to the
67097 ** TK_AS operator.  The TK_AS operator causes the expression to be
67098 ** evaluated just once and then reused for each alias.
67099 **
67100 ** The reason for suppressing the TK_AS term when the expression is a simple
67101 ** column reference is so that the column reference will be recognized as
67102 ** usable by indices within the WHERE clause processing logic. 
67103 **
67104 ** Hack:  The TK_AS operator is inhibited if zType[0]=='G'.  This means
67105 ** that in a GROUP BY clause, the expression is evaluated twice.  Hence:
67106 **
67107 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
67108 **
67109 ** Is equivalent to:
67110 **
67111 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
67112 **
67113 ** The result of random()%5 in the GROUP BY clause is probably different
67114 ** from the result in the result-set.  We might fix this someday.  Or
67115 ** then again, we might not...
67116 */
67117 static void resolveAlias(
67118   Parse *pParse,         /* Parsing context */
67119   ExprList *pEList,      /* A result set */
67120   int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */
67121   Expr *pExpr,           /* Transform this into an alias to the result set */
67122   const char *zType      /* "GROUP" or "ORDER" or "" */
67123 ){
67124   Expr *pOrig;           /* The iCol-th column of the result set */
67125   Expr *pDup;            /* Copy of pOrig */
67126   sqlite3 *db;           /* The database connection */
67127
67128   assert( iCol>=0 && iCol<pEList->nExpr );
67129   pOrig = pEList->a[iCol].pExpr;
67130   assert( pOrig!=0 );
67131   assert( pOrig->flags & EP_Resolved );
67132   db = pParse->db;
67133   if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
67134     pDup = sqlite3ExprDup(db, pOrig, 0);
67135     pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
67136     if( pDup==0 ) return;
67137     if( pEList->a[iCol].iAlias==0 ){
67138       pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);
67139     }
67140     pDup->iTable = pEList->a[iCol].iAlias;
67141   }else if( ExprHasProperty(pOrig, EP_IntValue) || pOrig->u.zToken==0 ){
67142     pDup = sqlite3ExprDup(db, pOrig, 0);
67143     if( pDup==0 ) return;
67144   }else{
67145     char *zToken = pOrig->u.zToken;
67146     assert( zToken!=0 );
67147     pOrig->u.zToken = 0;
67148     pDup = sqlite3ExprDup(db, pOrig, 0);
67149     pOrig->u.zToken = zToken;
67150     if( pDup==0 ) return;
67151     assert( (pDup->flags & (EP_Reduced|EP_TokenOnly))==0 );
67152     pDup->flags2 |= EP2_MallocedToken;
67153     pDup->u.zToken = sqlite3DbStrDup(db, zToken);
67154   }
67155   if( pExpr->flags & EP_ExpCollate ){
67156     pDup->pColl = pExpr->pColl;
67157     pDup->flags |= EP_ExpCollate;
67158   }
67159
67160   /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This 
67161   ** prevents ExprDelete() from deleting the Expr structure itself,
67162   ** allowing it to be repopulated by the memcpy() on the following line.
67163   */
67164   ExprSetProperty(pExpr, EP_Static);
67165   sqlite3ExprDelete(db, pExpr);
67166   memcpy(pExpr, pDup, sizeof(*pExpr));
67167   sqlite3DbFree(db, pDup);
67168 }
67169
67170 /*
67171 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
67172 ** that name in the set of source tables in pSrcList and make the pExpr 
67173 ** expression node refer back to that source column.  The following changes
67174 ** are made to pExpr:
67175 **
67176 **    pExpr->iDb           Set the index in db->aDb[] of the database X
67177 **                         (even if X is implied).
67178 **    pExpr->iTable        Set to the cursor number for the table obtained
67179 **                         from pSrcList.
67180 **    pExpr->pTab          Points to the Table structure of X.Y (even if
67181 **                         X and/or Y are implied.)
67182 **    pExpr->iColumn       Set to the column number within the table.
67183 **    pExpr->op            Set to TK_COLUMN.
67184 **    pExpr->pLeft         Any expression this points to is deleted
67185 **    pExpr->pRight        Any expression this points to is deleted.
67186 **
67187 ** The zDb variable is the name of the database (the "X").  This value may be
67188 ** NULL meaning that name is of the form Y.Z or Z.  Any available database
67189 ** can be used.  The zTable variable is the name of the table (the "Y").  This
67190 ** value can be NULL if zDb is also NULL.  If zTable is NULL it
67191 ** means that the form of the name is Z and that columns from any table
67192 ** can be used.
67193 **
67194 ** If the name cannot be resolved unambiguously, leave an error message
67195 ** in pParse and return WRC_Abort.  Return WRC_Prune on success.
67196 */
67197 static int lookupName(
67198   Parse *pParse,       /* The parsing context */
67199   const char *zDb,     /* Name of the database containing table, or NULL */
67200   const char *zTab,    /* Name of table containing column, or NULL */
67201   const char *zCol,    /* Name of the column. */
67202   NameContext *pNC,    /* The name context used to resolve the name */
67203   Expr *pExpr          /* Make this EXPR node point to the selected column */
67204 ){
67205   int i, j;            /* Loop counters */
67206   int cnt = 0;                      /* Number of matching column names */
67207   int cntTab = 0;                   /* Number of matching table names */
67208   sqlite3 *db = pParse->db;         /* The database connection */
67209   struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
67210   struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
67211   NameContext *pTopNC = pNC;        /* First namecontext in the list */
67212   Schema *pSchema = 0;              /* Schema of the expression */
67213   int isTrigger = 0;
67214
67215   assert( pNC );     /* the name context cannot be NULL. */
67216   assert( zCol );    /* The Z in X.Y.Z cannot be NULL */
67217   assert( ~ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
67218
67219   /* Initialize the node to no-match */
67220   pExpr->iTable = -1;
67221   pExpr->pTab = 0;
67222   ExprSetIrreducible(pExpr);
67223
67224   /* Start at the inner-most context and move outward until a match is found */
67225   while( pNC && cnt==0 ){
67226     ExprList *pEList;
67227     SrcList *pSrcList = pNC->pSrcList;
67228
67229     if( pSrcList ){
67230       for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
67231         Table *pTab;
67232         int iDb;
67233         Column *pCol;
67234   
67235         pTab = pItem->pTab;
67236         assert( pTab!=0 && pTab->zName!=0 );
67237         iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
67238         assert( pTab->nCol>0 );
67239         if( zTab ){
67240           if( pItem->zAlias ){
67241             char *zTabName = pItem->zAlias;
67242             if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
67243           }else{
67244             char *zTabName = pTab->zName;
67245             if( NEVER(zTabName==0) || sqlite3StrICmp(zTabName, zTab)!=0 ){
67246               continue;
67247             }
67248             if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
67249               continue;
67250             }
67251           }
67252         }
67253         if( 0==(cntTab++) ){
67254           pExpr->iTable = pItem->iCursor;
67255           pExpr->pTab = pTab;
67256           pSchema = pTab->pSchema;
67257           pMatch = pItem;
67258         }
67259         for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
67260           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
67261             IdList *pUsing;
67262             cnt++;
67263             pExpr->iTable = pItem->iCursor;
67264             pExpr->pTab = pTab;
67265             pMatch = pItem;
67266             pSchema = pTab->pSchema;
67267             /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
67268             pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
67269             if( i<pSrcList->nSrc-1 ){
67270               if( pItem[1].jointype & JT_NATURAL ){
67271                 /* If this match occurred in the left table of a natural join,
67272                 ** then skip the right table to avoid a duplicate match */
67273                 pItem++;
67274                 i++;
67275               }else if( (pUsing = pItem[1].pUsing)!=0 ){
67276                 /* If this match occurs on a column that is in the USING clause
67277                 ** of a join, skip the search of the right table of the join
67278                 ** to avoid a duplicate match there. */
67279                 int k;
67280                 for(k=0; k<pUsing->nId; k++){
67281                   if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ){
67282                     pItem++;
67283                     i++;
67284                     break;
67285                   }
67286                 }
67287               }
67288             }
67289             break;
67290           }
67291         }
67292       }
67293     }
67294
67295 #ifndef SQLITE_OMIT_TRIGGER
67296     /* If we have not already resolved the name, then maybe 
67297     ** it is a new.* or old.* trigger argument reference
67298     */
67299     if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){
67300       int op = pParse->eTriggerOp;
67301       Table *pTab = 0;
67302       assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
67303       if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
67304         pExpr->iTable = 1;
67305         pTab = pParse->pTriggerTab;
67306       }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
67307         pExpr->iTable = 0;
67308         pTab = pParse->pTriggerTab;
67309       }
67310
67311       if( pTab ){ 
67312         int iCol;
67313         pSchema = pTab->pSchema;
67314         cntTab++;
67315         for(iCol=0; iCol<pTab->nCol; iCol++){
67316           Column *pCol = &pTab->aCol[iCol];
67317           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
67318             if( iCol==pTab->iPKey ){
67319               iCol = -1;
67320             }
67321             break;
67322           }
67323         }
67324         if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) ){
67325           iCol = -1;        /* IMP: R-44911-55124 */
67326         }
67327         if( iCol<pTab->nCol ){
67328           cnt++;
67329           if( iCol<0 ){
67330             pExpr->affinity = SQLITE_AFF_INTEGER;
67331           }else if( pExpr->iTable==0 ){
67332             testcase( iCol==31 );
67333             testcase( iCol==32 );
67334             pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
67335           }else{
67336             testcase( iCol==31 );
67337             testcase( iCol==32 );
67338             pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
67339           }
67340           pExpr->iColumn = (i16)iCol;
67341           pExpr->pTab = pTab;
67342           isTrigger = 1;
67343         }
67344       }
67345     }
67346 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
67347
67348     /*
67349     ** Perhaps the name is a reference to the ROWID
67350     */
67351     if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
67352       cnt = 1;
67353       pExpr->iColumn = -1;     /* IMP: R-44911-55124 */
67354       pExpr->affinity = SQLITE_AFF_INTEGER;
67355     }
67356
67357     /*
67358     ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
67359     ** might refer to an result-set alias.  This happens, for example, when
67360     ** we are resolving names in the WHERE clause of the following command:
67361     **
67362     **     SELECT a+b AS x FROM table WHERE x<10;
67363     **
67364     ** In cases like this, replace pExpr with a copy of the expression that
67365     ** forms the result set entry ("a+b" in the example) and return immediately.
67366     ** Note that the expression in the result set should have already been
67367     ** resolved by the time the WHERE clause is resolved.
67368     */
67369     if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
67370       for(j=0; j<pEList->nExpr; j++){
67371         char *zAs = pEList->a[j].zName;
67372         if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
67373           Expr *pOrig;
67374           assert( pExpr->pLeft==0 && pExpr->pRight==0 );
67375           assert( pExpr->x.pList==0 );
67376           assert( pExpr->x.pSelect==0 );
67377           pOrig = pEList->a[j].pExpr;
67378           if( !pNC->allowAgg && ExprHasProperty(pOrig, EP_Agg) ){
67379             sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
67380             return WRC_Abort;
67381           }
67382           resolveAlias(pParse, pEList, j, pExpr, "");
67383           cnt = 1;
67384           pMatch = 0;
67385           assert( zTab==0 && zDb==0 );
67386           goto lookupname_end;
67387         }
67388       } 
67389     }
67390
67391     /* Advance to the next name context.  The loop will exit when either
67392     ** we have a match (cnt>0) or when we run out of name contexts.
67393     */
67394     if( cnt==0 ){
67395       pNC = pNC->pNext;
67396     }
67397   }
67398
67399   /*
67400   ** If X and Y are NULL (in other words if only the column name Z is
67401   ** supplied) and the value of Z is enclosed in double-quotes, then
67402   ** Z is a string literal if it doesn't match any column names.  In that
67403   ** case, we need to return right away and not make any changes to
67404   ** pExpr.
67405   **
67406   ** Because no reference was made to outer contexts, the pNC->nRef
67407   ** fields are not changed in any context.
67408   */
67409   if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
67410     pExpr->op = TK_STRING;
67411     pExpr->pTab = 0;
67412     return WRC_Prune;
67413   }
67414
67415   /*
67416   ** cnt==0 means there was not match.  cnt>1 means there were two or
67417   ** more matches.  Either way, we have an error.
67418   */
67419   if( cnt!=1 ){
67420     const char *zErr;
67421     zErr = cnt==0 ? "no such column" : "ambiguous column name";
67422     if( zDb ){
67423       sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
67424     }else if( zTab ){
67425       sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
67426     }else{
67427       sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
67428     }
67429     pParse->checkSchema = 1;
67430     pTopNC->nErr++;
67431   }
67432
67433   /* If a column from a table in pSrcList is referenced, then record
67434   ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
67435   ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
67436   ** column number is greater than the number of bits in the bitmask
67437   ** then set the high-order bit of the bitmask.
67438   */
67439   if( pExpr->iColumn>=0 && pMatch!=0 ){
67440     int n = pExpr->iColumn;
67441     testcase( n==BMS-1 );
67442     if( n>=BMS ){
67443       n = BMS-1;
67444     }
67445     assert( pMatch->iCursor==pExpr->iTable );
67446     pMatch->colUsed |= ((Bitmask)1)<<n;
67447   }
67448
67449   /* Clean up and return
67450   */
67451   sqlite3ExprDelete(db, pExpr->pLeft);
67452   pExpr->pLeft = 0;
67453   sqlite3ExprDelete(db, pExpr->pRight);
67454   pExpr->pRight = 0;
67455   pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
67456 lookupname_end:
67457   if( cnt==1 ){
67458     assert( pNC!=0 );
67459     sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
67460     /* Increment the nRef value on all name contexts from TopNC up to
67461     ** the point where the name matched. */
67462     for(;;){
67463       assert( pTopNC!=0 );
67464       pTopNC->nRef++;
67465       if( pTopNC==pNC ) break;
67466       pTopNC = pTopNC->pNext;
67467     }
67468     return WRC_Prune;
67469   } else {
67470     return WRC_Abort;
67471   }
67472 }
67473
67474 /*
67475 ** Allocate and return a pointer to an expression to load the column iCol
67476 ** from datasource iSrc in SrcList pSrc.
67477 */
67478 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
67479   Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
67480   if( p ){
67481     struct SrcList_item *pItem = &pSrc->a[iSrc];
67482     p->pTab = pItem->pTab;
67483     p->iTable = pItem->iCursor;
67484     if( p->pTab->iPKey==iCol ){
67485       p->iColumn = -1;
67486     }else{
67487       p->iColumn = (ynVar)iCol;
67488       testcase( iCol==BMS );
67489       testcase( iCol==BMS-1 );
67490       pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
67491     }
67492     ExprSetProperty(p, EP_Resolved);
67493   }
67494   return p;
67495 }
67496
67497 /*
67498 ** This routine is callback for sqlite3WalkExpr().
67499 **
67500 ** Resolve symbolic names into TK_COLUMN operators for the current
67501 ** node in the expression tree.  Return 0 to continue the search down
67502 ** the tree or 2 to abort the tree walk.
67503 **
67504 ** This routine also does error checking and name resolution for
67505 ** function names.  The operator for aggregate functions is changed
67506 ** to TK_AGG_FUNCTION.
67507 */
67508 static int resolveExprStep(Walker *pWalker, Expr *pExpr){
67509   NameContext *pNC;
67510   Parse *pParse;
67511
67512   pNC = pWalker->u.pNC;
67513   assert( pNC!=0 );
67514   pParse = pNC->pParse;
67515   assert( pParse==pWalker->pParse );
67516
67517   if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
67518   ExprSetProperty(pExpr, EP_Resolved);
67519 #ifndef NDEBUG
67520   if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
67521     SrcList *pSrcList = pNC->pSrcList;
67522     int i;
67523     for(i=0; i<pNC->pSrcList->nSrc; i++){
67524       assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
67525     }
67526   }
67527 #endif
67528   switch( pExpr->op ){
67529
67530 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
67531     /* The special operator TK_ROW means use the rowid for the first
67532     ** column in the FROM clause.  This is used by the LIMIT and ORDER BY
67533     ** clause processing on UPDATE and DELETE statements.
67534     */
67535     case TK_ROW: {
67536       SrcList *pSrcList = pNC->pSrcList;
67537       struct SrcList_item *pItem;
67538       assert( pSrcList && pSrcList->nSrc==1 );
67539       pItem = pSrcList->a; 
67540       pExpr->op = TK_COLUMN;
67541       pExpr->pTab = pItem->pTab;
67542       pExpr->iTable = pItem->iCursor;
67543       pExpr->iColumn = -1;
67544       pExpr->affinity = SQLITE_AFF_INTEGER;
67545       break;
67546     }
67547 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
67548
67549     /* A lone identifier is the name of a column.
67550     */
67551     case TK_ID: {
67552       return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
67553     }
67554   
67555     /* A table name and column name:     ID.ID
67556     ** Or a database, table and column:  ID.ID.ID
67557     */
67558     case TK_DOT: {
67559       const char *zColumn;
67560       const char *zTable;
67561       const char *zDb;
67562       Expr *pRight;
67563
67564       /* if( pSrcList==0 ) break; */
67565       pRight = pExpr->pRight;
67566       if( pRight->op==TK_ID ){
67567         zDb = 0;
67568         zTable = pExpr->pLeft->u.zToken;
67569         zColumn = pRight->u.zToken;
67570       }else{
67571         assert( pRight->op==TK_DOT );
67572         zDb = pExpr->pLeft->u.zToken;
67573         zTable = pRight->pLeft->u.zToken;
67574         zColumn = pRight->pRight->u.zToken;
67575       }
67576       return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
67577     }
67578
67579     /* Resolve function names
67580     */
67581     case TK_CONST_FUNC:
67582     case TK_FUNCTION: {
67583       ExprList *pList = pExpr->x.pList;    /* The argument list */
67584       int n = pList ? pList->nExpr : 0;    /* Number of arguments */
67585       int no_such_func = 0;       /* True if no such function exists */
67586       int wrong_num_args = 0;     /* True if wrong number of arguments */
67587       int is_agg = 0;             /* True if is an aggregate function */
67588       int auth;                   /* Authorization to use the function */
67589       int nId;                    /* Number of characters in function name */
67590       const char *zId;            /* The function name. */
67591       FuncDef *pDef;              /* Information about the function */
67592       u8 enc = ENC(pParse->db);   /* The database encoding */
67593
67594       testcase( pExpr->op==TK_CONST_FUNC );
67595       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
67596       zId = pExpr->u.zToken;
67597       nId = sqlite3Strlen30(zId);
67598       pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
67599       if( pDef==0 ){
67600         pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
67601         if( pDef==0 ){
67602           no_such_func = 1;
67603         }else{
67604           wrong_num_args = 1;
67605         }
67606       }else{
67607         is_agg = pDef->xFunc==0;
67608       }
67609 #ifndef SQLITE_OMIT_AUTHORIZATION
67610       if( pDef ){
67611         auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
67612         if( auth!=SQLITE_OK ){
67613           if( auth==SQLITE_DENY ){
67614             sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
67615                                     pDef->zName);
67616             pNC->nErr++;
67617           }
67618           pExpr->op = TK_NULL;
67619           return WRC_Prune;
67620         }
67621       }
67622 #endif
67623       if( is_agg && !pNC->allowAgg ){
67624         sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
67625         pNC->nErr++;
67626         is_agg = 0;
67627       }else if( no_such_func ){
67628         sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
67629         pNC->nErr++;
67630       }else if( wrong_num_args ){
67631         sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
67632              nId, zId);
67633         pNC->nErr++;
67634       }
67635       if( is_agg ){
67636         pExpr->op = TK_AGG_FUNCTION;
67637         pNC->hasAgg = 1;
67638       }
67639       if( is_agg ) pNC->allowAgg = 0;
67640       sqlite3WalkExprList(pWalker, pList);
67641       if( is_agg ) pNC->allowAgg = 1;
67642       /* FIX ME:  Compute pExpr->affinity based on the expected return
67643       ** type of the function 
67644       */
67645       return WRC_Prune;
67646     }
67647 #ifndef SQLITE_OMIT_SUBQUERY
67648     case TK_SELECT:
67649     case TK_EXISTS:  testcase( pExpr->op==TK_EXISTS );
67650 #endif
67651     case TK_IN: {
67652       testcase( pExpr->op==TK_IN );
67653       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
67654         int nRef = pNC->nRef;
67655 #ifndef SQLITE_OMIT_CHECK
67656         if( pNC->isCheck ){
67657           sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
67658         }
67659 #endif
67660         sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
67661         assert( pNC->nRef>=nRef );
67662         if( nRef!=pNC->nRef ){
67663           ExprSetProperty(pExpr, EP_VarSelect);
67664         }
67665       }
67666       break;
67667     }
67668 #ifndef SQLITE_OMIT_CHECK
67669     case TK_VARIABLE: {
67670       if( pNC->isCheck ){
67671         sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
67672       }
67673       break;
67674     }
67675 #endif
67676   }
67677   return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
67678 }
67679
67680 /*
67681 ** pEList is a list of expressions which are really the result set of the
67682 ** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
67683 ** This routine checks to see if pE is a simple identifier which corresponds
67684 ** to the AS-name of one of the terms of the expression list.  If it is,
67685 ** this routine return an integer between 1 and N where N is the number of
67686 ** elements in pEList, corresponding to the matching entry.  If there is
67687 ** no match, or if pE is not a simple identifier, then this routine
67688 ** return 0.
67689 **
67690 ** pEList has been resolved.  pE has not.
67691 */
67692 static int resolveAsName(
67693   Parse *pParse,     /* Parsing context for error messages */
67694   ExprList *pEList,  /* List of expressions to scan */
67695   Expr *pE           /* Expression we are trying to match */
67696 ){
67697   int i;             /* Loop counter */
67698
67699   UNUSED_PARAMETER(pParse);
67700
67701   if( pE->op==TK_ID ){
67702     char *zCol = pE->u.zToken;
67703     for(i=0; i<pEList->nExpr; i++){
67704       char *zAs = pEList->a[i].zName;
67705       if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
67706         return i+1;
67707       }
67708     }
67709   }
67710   return 0;
67711 }
67712
67713 /*
67714 ** pE is a pointer to an expression which is a single term in the
67715 ** ORDER BY of a compound SELECT.  The expression has not been
67716 ** name resolved.
67717 **
67718 ** At the point this routine is called, we already know that the
67719 ** ORDER BY term is not an integer index into the result set.  That
67720 ** case is handled by the calling routine.
67721 **
67722 ** Attempt to match pE against result set columns in the left-most
67723 ** SELECT statement.  Return the index i of the matching column,
67724 ** as an indication to the caller that it should sort by the i-th column.
67725 ** The left-most column is 1.  In other words, the value returned is the
67726 ** same integer value that would be used in the SQL statement to indicate
67727 ** the column.
67728 **
67729 ** If there is no match, return 0.  Return -1 if an error occurs.
67730 */
67731 static int resolveOrderByTermToExprList(
67732   Parse *pParse,     /* Parsing context for error messages */
67733   Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
67734   Expr *pE           /* The specific ORDER BY term */
67735 ){
67736   int i;             /* Loop counter */
67737   ExprList *pEList;  /* The columns of the result set */
67738   NameContext nc;    /* Name context for resolving pE */
67739   sqlite3 *db;       /* Database connection */
67740   int rc;            /* Return code from subprocedures */
67741   u8 savedSuppErr;   /* Saved value of db->suppressErr */
67742
67743   assert( sqlite3ExprIsInteger(pE, &i)==0 );
67744   pEList = pSelect->pEList;
67745
67746   /* Resolve all names in the ORDER BY term expression
67747   */
67748   memset(&nc, 0, sizeof(nc));
67749   nc.pParse = pParse;
67750   nc.pSrcList = pSelect->pSrc;
67751   nc.pEList = pEList;
67752   nc.allowAgg = 1;
67753   nc.nErr = 0;
67754   db = pParse->db;
67755   savedSuppErr = db->suppressErr;
67756   db->suppressErr = 1;
67757   rc = sqlite3ResolveExprNames(&nc, pE);
67758   db->suppressErr = savedSuppErr;
67759   if( rc ) return 0;
67760
67761   /* Try to match the ORDER BY expression against an expression
67762   ** in the result set.  Return an 1-based index of the matching
67763   ** result-set entry.
67764   */
67765   for(i=0; i<pEList->nExpr; i++){
67766     if( sqlite3ExprCompare(pEList->a[i].pExpr, pE)<2 ){
67767       return i+1;
67768     }
67769   }
67770
67771   /* If no match, return 0. */
67772   return 0;
67773 }
67774
67775 /*
67776 ** Generate an ORDER BY or GROUP BY term out-of-range error.
67777 */
67778 static void resolveOutOfRangeError(
67779   Parse *pParse,         /* The error context into which to write the error */
67780   const char *zType,     /* "ORDER" or "GROUP" */
67781   int i,                 /* The index (1-based) of the term out of range */
67782   int mx                 /* Largest permissible value of i */
67783 ){
67784   sqlite3ErrorMsg(pParse, 
67785     "%r %s BY term out of range - should be "
67786     "between 1 and %d", i, zType, mx);
67787 }
67788
67789 /*
67790 ** Analyze the ORDER BY clause in a compound SELECT statement.   Modify
67791 ** each term of the ORDER BY clause is a constant integer between 1
67792 ** and N where N is the number of columns in the compound SELECT.
67793 **
67794 ** ORDER BY terms that are already an integer between 1 and N are
67795 ** unmodified.  ORDER BY terms that are integers outside the range of
67796 ** 1 through N generate an error.  ORDER BY terms that are expressions
67797 ** are matched against result set expressions of compound SELECT
67798 ** beginning with the left-most SELECT and working toward the right.
67799 ** At the first match, the ORDER BY expression is transformed into
67800 ** the integer column number.
67801 **
67802 ** Return the number of errors seen.
67803 */
67804 static int resolveCompoundOrderBy(
67805   Parse *pParse,        /* Parsing context.  Leave error messages here */
67806   Select *pSelect       /* The SELECT statement containing the ORDER BY */
67807 ){
67808   int i;
67809   ExprList *pOrderBy;
67810   ExprList *pEList;
67811   sqlite3 *db;
67812   int moreToDo = 1;
67813
67814   pOrderBy = pSelect->pOrderBy;
67815   if( pOrderBy==0 ) return 0;
67816   db = pParse->db;
67817 #if SQLITE_MAX_COLUMN
67818   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
67819     sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
67820     return 1;
67821   }
67822 #endif
67823   for(i=0; i<pOrderBy->nExpr; i++){
67824     pOrderBy->a[i].done = 0;
67825   }
67826   pSelect->pNext = 0;
67827   while( pSelect->pPrior ){
67828     pSelect->pPrior->pNext = pSelect;
67829     pSelect = pSelect->pPrior;
67830   }
67831   while( pSelect && moreToDo ){
67832     struct ExprList_item *pItem;
67833     moreToDo = 0;
67834     pEList = pSelect->pEList;
67835     assert( pEList!=0 );
67836     for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
67837       int iCol = -1;
67838       Expr *pE, *pDup;
67839       if( pItem->done ) continue;
67840       pE = pItem->pExpr;
67841       if( sqlite3ExprIsInteger(pE, &iCol) ){
67842         if( iCol<=0 || iCol>pEList->nExpr ){
67843           resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
67844           return 1;
67845         }
67846       }else{
67847         iCol = resolveAsName(pParse, pEList, pE);
67848         if( iCol==0 ){
67849           pDup = sqlite3ExprDup(db, pE, 0);
67850           if( !db->mallocFailed ){
67851             assert(pDup);
67852             iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
67853           }
67854           sqlite3ExprDelete(db, pDup);
67855         }
67856       }
67857       if( iCol>0 ){
67858         CollSeq *pColl = pE->pColl;
67859         int flags = pE->flags & EP_ExpCollate;
67860         sqlite3ExprDelete(db, pE);
67861         pItem->pExpr = pE = sqlite3Expr(db, TK_INTEGER, 0);
67862         if( pE==0 ) return 1;
67863         pE->pColl = pColl;
67864         pE->flags |= EP_IntValue | flags;
67865         pE->u.iValue = iCol;
67866         pItem->iCol = (u16)iCol;
67867         pItem->done = 1;
67868       }else{
67869         moreToDo = 1;
67870       }
67871     }
67872     pSelect = pSelect->pNext;
67873   }
67874   for(i=0; i<pOrderBy->nExpr; i++){
67875     if( pOrderBy->a[i].done==0 ){
67876       sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
67877             "column in the result set", i+1);
67878       return 1;
67879     }
67880   }
67881   return 0;
67882 }
67883
67884 /*
67885 ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
67886 ** the SELECT statement pSelect.  If any term is reference to a
67887 ** result set expression (as determined by the ExprList.a.iCol field)
67888 ** then convert that term into a copy of the corresponding result set
67889 ** column.
67890 **
67891 ** If any errors are detected, add an error message to pParse and
67892 ** return non-zero.  Return zero if no errors are seen.
67893 */
67894 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
67895   Parse *pParse,        /* Parsing context.  Leave error messages here */
67896   Select *pSelect,      /* The SELECT statement containing the clause */
67897   ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
67898   const char *zType     /* "ORDER" or "GROUP" */
67899 ){
67900   int i;
67901   sqlite3 *db = pParse->db;
67902   ExprList *pEList;
67903   struct ExprList_item *pItem;
67904
67905   if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
67906 #if SQLITE_MAX_COLUMN
67907   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
67908     sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
67909     return 1;
67910   }
67911 #endif
67912   pEList = pSelect->pEList;
67913   assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */
67914   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
67915     if( pItem->iCol ){
67916       if( pItem->iCol>pEList->nExpr ){
67917         resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
67918         return 1;
67919       }
67920       resolveAlias(pParse, pEList, pItem->iCol-1, pItem->pExpr, zType);
67921     }
67922   }
67923   return 0;
67924 }
67925
67926 /*
67927 ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
67928 ** The Name context of the SELECT statement is pNC.  zType is either
67929 ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
67930 **
67931 ** This routine resolves each term of the clause into an expression.
67932 ** If the order-by term is an integer I between 1 and N (where N is the
67933 ** number of columns in the result set of the SELECT) then the expression
67934 ** in the resolution is a copy of the I-th result-set expression.  If
67935 ** the order-by term is an identify that corresponds to the AS-name of
67936 ** a result-set expression, then the term resolves to a copy of the
67937 ** result-set expression.  Otherwise, the expression is resolved in
67938 ** the usual way - using sqlite3ResolveExprNames().
67939 **
67940 ** This routine returns the number of errors.  If errors occur, then
67941 ** an appropriate error message might be left in pParse.  (OOM errors
67942 ** excepted.)
67943 */
67944 static int resolveOrderGroupBy(
67945   NameContext *pNC,     /* The name context of the SELECT statement */
67946   Select *pSelect,      /* The SELECT statement holding pOrderBy */
67947   ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */
67948   const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
67949 ){
67950   int i;                         /* Loop counter */
67951   int iCol;                      /* Column number */
67952   struct ExprList_item *pItem;   /* A term of the ORDER BY clause */
67953   Parse *pParse;                 /* Parsing context */
67954   int nResult;                   /* Number of terms in the result set */
67955
67956   if( pOrderBy==0 ) return 0;
67957   nResult = pSelect->pEList->nExpr;
67958   pParse = pNC->pParse;
67959   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
67960     Expr *pE = pItem->pExpr;
67961     iCol = resolveAsName(pParse, pSelect->pEList, pE);
67962     if( iCol>0 ){
67963       /* If an AS-name match is found, mark this ORDER BY column as being
67964       ** a copy of the iCol-th result-set column.  The subsequent call to
67965       ** sqlite3ResolveOrderGroupBy() will convert the expression to a
67966       ** copy of the iCol-th result-set expression. */
67967       pItem->iCol = (u16)iCol;
67968       continue;
67969     }
67970     if( sqlite3ExprIsInteger(pE, &iCol) ){
67971       /* The ORDER BY term is an integer constant.  Again, set the column
67972       ** number so that sqlite3ResolveOrderGroupBy() will convert the
67973       ** order-by term to a copy of the result-set expression */
67974       if( iCol<1 ){
67975         resolveOutOfRangeError(pParse, zType, i+1, nResult);
67976         return 1;
67977       }
67978       pItem->iCol = (u16)iCol;
67979       continue;
67980     }
67981
67982     /* Otherwise, treat the ORDER BY term as an ordinary expression */
67983     pItem->iCol = 0;
67984     if( sqlite3ResolveExprNames(pNC, pE) ){
67985       return 1;
67986     }
67987   }
67988   return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
67989 }
67990
67991 /*
67992 ** Resolve names in the SELECT statement p and all of its descendents.
67993 */
67994 static int resolveSelectStep(Walker *pWalker, Select *p){
67995   NameContext *pOuterNC;  /* Context that contains this SELECT */
67996   NameContext sNC;        /* Name context of this SELECT */
67997   int isCompound;         /* True if p is a compound select */
67998   int nCompound;          /* Number of compound terms processed so far */
67999   Parse *pParse;          /* Parsing context */
68000   ExprList *pEList;       /* Result set expression list */
68001   int i;                  /* Loop counter */
68002   ExprList *pGroupBy;     /* The GROUP BY clause */
68003   Select *pLeftmost;      /* Left-most of SELECT of a compound */
68004   sqlite3 *db;            /* Database connection */
68005   
68006
68007   assert( p!=0 );
68008   if( p->selFlags & SF_Resolved ){
68009     return WRC_Prune;
68010   }
68011   pOuterNC = pWalker->u.pNC;
68012   pParse = pWalker->pParse;
68013   db = pParse->db;
68014
68015   /* Normally sqlite3SelectExpand() will be called first and will have
68016   ** already expanded this SELECT.  However, if this is a subquery within
68017   ** an expression, sqlite3ResolveExprNames() will be called without a
68018   ** prior call to sqlite3SelectExpand().  When that happens, let
68019   ** sqlite3SelectPrep() do all of the processing for this SELECT.
68020   ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
68021   ** this routine in the correct order.
68022   */
68023   if( (p->selFlags & SF_Expanded)==0 ){
68024     sqlite3SelectPrep(pParse, p, pOuterNC);
68025     return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
68026   }
68027
68028   isCompound = p->pPrior!=0;
68029   nCompound = 0;
68030   pLeftmost = p;
68031   while( p ){
68032     assert( (p->selFlags & SF_Expanded)!=0 );
68033     assert( (p->selFlags & SF_Resolved)==0 );
68034     p->selFlags |= SF_Resolved;
68035
68036     /* Resolve the expressions in the LIMIT and OFFSET clauses. These
68037     ** are not allowed to refer to any names, so pass an empty NameContext.
68038     */
68039     memset(&sNC, 0, sizeof(sNC));
68040     sNC.pParse = pParse;
68041     if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
68042         sqlite3ResolveExprNames(&sNC, p->pOffset) ){
68043       return WRC_Abort;
68044     }
68045   
68046     /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
68047     ** resolve the result-set expression list.
68048     */
68049     sNC.allowAgg = 1;
68050     sNC.pSrcList = p->pSrc;
68051     sNC.pNext = pOuterNC;
68052   
68053     /* Resolve names in the result set. */
68054     pEList = p->pEList;
68055     assert( pEList!=0 );
68056     for(i=0; i<pEList->nExpr; i++){
68057       Expr *pX = pEList->a[i].pExpr;
68058       if( sqlite3ResolveExprNames(&sNC, pX) ){
68059         return WRC_Abort;
68060       }
68061     }
68062   
68063     /* Recursively resolve names in all subqueries
68064     */
68065     for(i=0; i<p->pSrc->nSrc; i++){
68066       struct SrcList_item *pItem = &p->pSrc->a[i];
68067       if( pItem->pSelect ){
68068         const char *zSavedContext = pParse->zAuthContext;
68069         if( pItem->zName ) pParse->zAuthContext = pItem->zName;
68070         sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
68071         pParse->zAuthContext = zSavedContext;
68072         if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
68073       }
68074     }
68075   
68076     /* If there are no aggregate functions in the result-set, and no GROUP BY 
68077     ** expression, do not allow aggregates in any of the other expressions.
68078     */
68079     assert( (p->selFlags & SF_Aggregate)==0 );
68080     pGroupBy = p->pGroupBy;
68081     if( pGroupBy || sNC.hasAgg ){
68082       p->selFlags |= SF_Aggregate;
68083     }else{
68084       sNC.allowAgg = 0;
68085     }
68086   
68087     /* If a HAVING clause is present, then there must be a GROUP BY clause.
68088     */
68089     if( p->pHaving && !pGroupBy ){
68090       sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
68091       return WRC_Abort;
68092     }
68093   
68094     /* Add the expression list to the name-context before parsing the
68095     ** other expressions in the SELECT statement. This is so that
68096     ** expressions in the WHERE clause (etc.) can refer to expressions by
68097     ** aliases in the result set.
68098     **
68099     ** Minor point: If this is the case, then the expression will be
68100     ** re-evaluated for each reference to it.
68101     */
68102     sNC.pEList = p->pEList;
68103     if( sqlite3ResolveExprNames(&sNC, p->pWhere) ||
68104        sqlite3ResolveExprNames(&sNC, p->pHaving)
68105     ){
68106       return WRC_Abort;
68107     }
68108
68109     /* The ORDER BY and GROUP BY clauses may not refer to terms in
68110     ** outer queries 
68111     */
68112     sNC.pNext = 0;
68113     sNC.allowAgg = 1;
68114
68115     /* Process the ORDER BY clause for singleton SELECT statements.
68116     ** The ORDER BY clause for compounds SELECT statements is handled
68117     ** below, after all of the result-sets for all of the elements of
68118     ** the compound have been resolved.
68119     */
68120     if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
68121       return WRC_Abort;
68122     }
68123     if( db->mallocFailed ){
68124       return WRC_Abort;
68125     }
68126   
68127     /* Resolve the GROUP BY clause.  At the same time, make sure 
68128     ** the GROUP BY clause does not contain aggregate functions.
68129     */
68130     if( pGroupBy ){
68131       struct ExprList_item *pItem;
68132     
68133       if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
68134         return WRC_Abort;
68135       }
68136       for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
68137         if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
68138           sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
68139               "the GROUP BY clause");
68140           return WRC_Abort;
68141         }
68142       }
68143     }
68144
68145     /* Advance to the next term of the compound
68146     */
68147     p = p->pPrior;
68148     nCompound++;
68149   }
68150
68151   /* Resolve the ORDER BY on a compound SELECT after all terms of
68152   ** the compound have been resolved.
68153   */
68154   if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
68155     return WRC_Abort;
68156   }
68157
68158   return WRC_Prune;
68159 }
68160
68161 /*
68162 ** This routine walks an expression tree and resolves references to
68163 ** table columns and result-set columns.  At the same time, do error
68164 ** checking on function usage and set a flag if any aggregate functions
68165 ** are seen.
68166 **
68167 ** To resolve table columns references we look for nodes (or subtrees) of the 
68168 ** form X.Y.Z or Y.Z or just Z where
68169 **
68170 **      X:   The name of a database.  Ex:  "main" or "temp" or
68171 **           the symbolic name assigned to an ATTACH-ed database.
68172 **
68173 **      Y:   The name of a table in a FROM clause.  Or in a trigger
68174 **           one of the special names "old" or "new".
68175 **
68176 **      Z:   The name of a column in table Y.
68177 **
68178 ** The node at the root of the subtree is modified as follows:
68179 **
68180 **    Expr.op        Changed to TK_COLUMN
68181 **    Expr.pTab      Points to the Table object for X.Y
68182 **    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
68183 **    Expr.iTable    The VDBE cursor number for X.Y
68184 **
68185 **
68186 ** To resolve result-set references, look for expression nodes of the
68187 ** form Z (with no X and Y prefix) where the Z matches the right-hand
68188 ** size of an AS clause in the result-set of a SELECT.  The Z expression
68189 ** is replaced by a copy of the left-hand side of the result-set expression.
68190 ** Table-name and function resolution occurs on the substituted expression
68191 ** tree.  For example, in:
68192 **
68193 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
68194 **
68195 ** The "x" term of the order by is replaced by "a+b" to render:
68196 **
68197 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
68198 **
68199 ** Function calls are checked to make sure that the function is 
68200 ** defined and that the correct number of arguments are specified.
68201 ** If the function is an aggregate function, then the pNC->hasAgg is
68202 ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
68203 ** If an expression contains aggregate functions then the EP_Agg
68204 ** property on the expression is set.
68205 **
68206 ** An error message is left in pParse if anything is amiss.  The number
68207 ** if errors is returned.
68208 */
68209 SQLITE_PRIVATE int sqlite3ResolveExprNames( 
68210   NameContext *pNC,       /* Namespace to resolve expressions in. */
68211   Expr *pExpr             /* The expression to be analyzed. */
68212 ){
68213   int savedHasAgg;
68214   Walker w;
68215
68216   if( pExpr==0 ) return 0;
68217 #if SQLITE_MAX_EXPR_DEPTH>0
68218   {
68219     Parse *pParse = pNC->pParse;
68220     if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
68221       return 1;
68222     }
68223     pParse->nHeight += pExpr->nHeight;
68224   }
68225 #endif
68226   savedHasAgg = pNC->hasAgg;
68227   pNC->hasAgg = 0;
68228   w.xExprCallback = resolveExprStep;
68229   w.xSelectCallback = resolveSelectStep;
68230   w.pParse = pNC->pParse;
68231   w.u.pNC = pNC;
68232   sqlite3WalkExpr(&w, pExpr);
68233 #if SQLITE_MAX_EXPR_DEPTH>0
68234   pNC->pParse->nHeight -= pExpr->nHeight;
68235 #endif
68236   if( pNC->nErr>0 || w.pParse->nErr>0 ){
68237     ExprSetProperty(pExpr, EP_Error);
68238   }
68239   if( pNC->hasAgg ){
68240     ExprSetProperty(pExpr, EP_Agg);
68241   }else if( savedHasAgg ){
68242     pNC->hasAgg = 1;
68243   }
68244   return ExprHasProperty(pExpr, EP_Error);
68245 }
68246
68247
68248 /*
68249 ** Resolve all names in all expressions of a SELECT and in all
68250 ** decendents of the SELECT, including compounds off of p->pPrior,
68251 ** subqueries in expressions, and subqueries used as FROM clause
68252 ** terms.
68253 **
68254 ** See sqlite3ResolveExprNames() for a description of the kinds of
68255 ** transformations that occur.
68256 **
68257 ** All SELECT statements should have been expanded using
68258 ** sqlite3SelectExpand() prior to invoking this routine.
68259 */
68260 SQLITE_PRIVATE void sqlite3ResolveSelectNames(
68261   Parse *pParse,         /* The parser context */
68262   Select *p,             /* The SELECT statement being coded. */
68263   NameContext *pOuterNC  /* Name context for parent SELECT statement */
68264 ){
68265   Walker w;
68266
68267   assert( p!=0 );
68268   w.xExprCallback = resolveExprStep;
68269   w.xSelectCallback = resolveSelectStep;
68270   w.pParse = pParse;
68271   w.u.pNC = pOuterNC;
68272   sqlite3WalkSelect(&w, p);
68273 }
68274
68275 /************** End of resolve.c *********************************************/
68276 /************** Begin file expr.c ********************************************/
68277 /*
68278 ** 2001 September 15
68279 **
68280 ** The author disclaims copyright to this source code.  In place of
68281 ** a legal notice, here is a blessing:
68282 **
68283 **    May you do good and not evil.
68284 **    May you find forgiveness for yourself and forgive others.
68285 **    May you share freely, never taking more than you give.
68286 **
68287 *************************************************************************
68288 ** This file contains routines used for analyzing expressions and
68289 ** for generating VDBE code that evaluates expressions in SQLite.
68290 */
68291
68292 /*
68293 ** Return the 'affinity' of the expression pExpr if any.
68294 **
68295 ** If pExpr is a column, a reference to a column via an 'AS' alias,
68296 ** or a sub-select with a column as the return value, then the 
68297 ** affinity of that column is returned. Otherwise, 0x00 is returned,
68298 ** indicating no affinity for the expression.
68299 **
68300 ** i.e. the WHERE clause expresssions in the following statements all
68301 ** have an affinity:
68302 **
68303 ** CREATE TABLE t1(a);
68304 ** SELECT * FROM t1 WHERE a;
68305 ** SELECT a AS b FROM t1 WHERE b;
68306 ** SELECT * FROM t1 WHERE (select a from t1);
68307 */
68308 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
68309   int op = pExpr->op;
68310   if( op==TK_SELECT ){
68311     assert( pExpr->flags&EP_xIsSelect );
68312     return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
68313   }
68314 #ifndef SQLITE_OMIT_CAST
68315   if( op==TK_CAST ){
68316     assert( !ExprHasProperty(pExpr, EP_IntValue) );
68317     return sqlite3AffinityType(pExpr->u.zToken);
68318   }
68319 #endif
68320   if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER) 
68321    && pExpr->pTab!=0
68322   ){
68323     /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
68324     ** a TK_COLUMN but was previously evaluated and cached in a register */
68325     int j = pExpr->iColumn;
68326     if( j<0 ) return SQLITE_AFF_INTEGER;
68327     assert( pExpr->pTab && j<pExpr->pTab->nCol );
68328     return pExpr->pTab->aCol[j].affinity;
68329   }
68330   return pExpr->affinity;
68331 }
68332
68333 /*
68334 ** Set the explicit collating sequence for an expression to the
68335 ** collating sequence supplied in the second argument.
68336 */
68337 SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Expr *pExpr, CollSeq *pColl){
68338   if( pExpr && pColl ){
68339     pExpr->pColl = pColl;
68340     pExpr->flags |= EP_ExpCollate;
68341   }
68342   return pExpr;
68343 }
68344
68345 /*
68346 ** Set the collating sequence for expression pExpr to be the collating
68347 ** sequence named by pToken.   Return a pointer to the revised expression.
68348 ** The collating sequence is marked as "explicit" using the EP_ExpCollate
68349 ** flag.  An explicit collating sequence will override implicit
68350 ** collating sequences.
68351 */
68352 SQLITE_PRIVATE Expr *sqlite3ExprSetCollByToken(Parse *pParse, Expr *pExpr, Token *pCollName){
68353   char *zColl = 0;            /* Dequoted name of collation sequence */
68354   CollSeq *pColl;
68355   sqlite3 *db = pParse->db;
68356   zColl = sqlite3NameFromToken(db, pCollName);
68357   pColl = sqlite3LocateCollSeq(pParse, zColl);
68358   sqlite3ExprSetColl(pExpr, pColl);
68359   sqlite3DbFree(db, zColl);
68360   return pExpr;
68361 }
68362
68363 /*
68364 ** Return the default collation sequence for the expression pExpr. If
68365 ** there is no default collation type, return 0.
68366 */
68367 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
68368   CollSeq *pColl = 0;
68369   Expr *p = pExpr;
68370   while( ALWAYS(p) ){
68371     int op;
68372     pColl = p->pColl;
68373     if( pColl ) break;
68374     op = p->op;
68375     if( p->pTab!=0 && (
68376         op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER || op==TK_TRIGGER
68377     )){
68378       /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
68379       ** a TK_COLUMN but was previously evaluated and cached in a register */
68380       const char *zColl;
68381       int j = p->iColumn;
68382       if( j>=0 ){
68383         sqlite3 *db = pParse->db;
68384         zColl = p->pTab->aCol[j].zColl;
68385         pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
68386         pExpr->pColl = pColl;
68387       }
68388       break;
68389     }
68390     if( op!=TK_CAST && op!=TK_UPLUS ){
68391       break;
68392     }
68393     p = p->pLeft;
68394   }
68395   if( sqlite3CheckCollSeq(pParse, pColl) ){ 
68396     pColl = 0;
68397   }
68398   return pColl;
68399 }
68400
68401 /*
68402 ** pExpr is an operand of a comparison operator.  aff2 is the
68403 ** type affinity of the other operand.  This routine returns the
68404 ** type affinity that should be used for the comparison operator.
68405 */
68406 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
68407   char aff1 = sqlite3ExprAffinity(pExpr);
68408   if( aff1 && aff2 ){
68409     /* Both sides of the comparison are columns. If one has numeric
68410     ** affinity, use that. Otherwise use no affinity.
68411     */
68412     if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
68413       return SQLITE_AFF_NUMERIC;
68414     }else{
68415       return SQLITE_AFF_NONE;
68416     }
68417   }else if( !aff1 && !aff2 ){
68418     /* Neither side of the comparison is a column.  Compare the
68419     ** results directly.
68420     */
68421     return SQLITE_AFF_NONE;
68422   }else{
68423     /* One side is a column, the other is not. Use the columns affinity. */
68424     assert( aff1==0 || aff2==0 );
68425     return (aff1 + aff2);
68426   }
68427 }
68428
68429 /*
68430 ** pExpr is a comparison operator.  Return the type affinity that should
68431 ** be applied to both operands prior to doing the comparison.
68432 */
68433 static char comparisonAffinity(Expr *pExpr){
68434   char aff;
68435   assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
68436           pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
68437           pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
68438   assert( pExpr->pLeft );
68439   aff = sqlite3ExprAffinity(pExpr->pLeft);
68440   if( pExpr->pRight ){
68441     aff = sqlite3CompareAffinity(pExpr->pRight, aff);
68442   }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
68443     aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
68444   }else if( !aff ){
68445     aff = SQLITE_AFF_NONE;
68446   }
68447   return aff;
68448 }
68449
68450 /*
68451 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
68452 ** idx_affinity is the affinity of an indexed column. Return true
68453 ** if the index with affinity idx_affinity may be used to implement
68454 ** the comparison in pExpr.
68455 */
68456 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
68457   char aff = comparisonAffinity(pExpr);
68458   switch( aff ){
68459     case SQLITE_AFF_NONE:
68460       return 1;
68461     case SQLITE_AFF_TEXT:
68462       return idx_affinity==SQLITE_AFF_TEXT;
68463     default:
68464       return sqlite3IsNumericAffinity(idx_affinity);
68465   }
68466 }
68467
68468 /*
68469 ** Return the P5 value that should be used for a binary comparison
68470 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
68471 */
68472 static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
68473   u8 aff = (char)sqlite3ExprAffinity(pExpr2);
68474   aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
68475   return aff;
68476 }
68477
68478 /*
68479 ** Return a pointer to the collation sequence that should be used by
68480 ** a binary comparison operator comparing pLeft and pRight.
68481 **
68482 ** If the left hand expression has a collating sequence type, then it is
68483 ** used. Otherwise the collation sequence for the right hand expression
68484 ** is used, or the default (BINARY) if neither expression has a collating
68485 ** type.
68486 **
68487 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
68488 ** it is not considered.
68489 */
68490 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
68491   Parse *pParse, 
68492   Expr *pLeft, 
68493   Expr *pRight
68494 ){
68495   CollSeq *pColl;
68496   assert( pLeft );
68497   if( pLeft->flags & EP_ExpCollate ){
68498     assert( pLeft->pColl );
68499     pColl = pLeft->pColl;
68500   }else if( pRight && pRight->flags & EP_ExpCollate ){
68501     assert( pRight->pColl );
68502     pColl = pRight->pColl;
68503   }else{
68504     pColl = sqlite3ExprCollSeq(pParse, pLeft);
68505     if( !pColl ){
68506       pColl = sqlite3ExprCollSeq(pParse, pRight);
68507     }
68508   }
68509   return pColl;
68510 }
68511
68512 /*
68513 ** Generate code for a comparison operator.
68514 */
68515 static int codeCompare(
68516   Parse *pParse,    /* The parsing (and code generating) context */
68517   Expr *pLeft,      /* The left operand */
68518   Expr *pRight,     /* The right operand */
68519   int opcode,       /* The comparison opcode */
68520   int in1, int in2, /* Register holding operands */
68521   int dest,         /* Jump here if true.  */
68522   int jumpIfNull    /* If true, jump if either operand is NULL */
68523 ){
68524   int p5;
68525   int addr;
68526   CollSeq *p4;
68527
68528   p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
68529   p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
68530   addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
68531                            (void*)p4, P4_COLLSEQ);
68532   sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
68533   return addr;
68534 }
68535
68536 #if SQLITE_MAX_EXPR_DEPTH>0
68537 /*
68538 ** Check that argument nHeight is less than or equal to the maximum
68539 ** expression depth allowed. If it is not, leave an error message in
68540 ** pParse.
68541 */
68542 SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
68543   int rc = SQLITE_OK;
68544   int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
68545   if( nHeight>mxHeight ){
68546     sqlite3ErrorMsg(pParse, 
68547        "Expression tree is too large (maximum depth %d)", mxHeight
68548     );
68549     rc = SQLITE_ERROR;
68550   }
68551   return rc;
68552 }
68553
68554 /* The following three functions, heightOfExpr(), heightOfExprList()
68555 ** and heightOfSelect(), are used to determine the maximum height
68556 ** of any expression tree referenced by the structure passed as the
68557 ** first argument.
68558 **
68559 ** If this maximum height is greater than the current value pointed
68560 ** to by pnHeight, the second parameter, then set *pnHeight to that
68561 ** value.
68562 */
68563 static void heightOfExpr(Expr *p, int *pnHeight){
68564   if( p ){
68565     if( p->nHeight>*pnHeight ){
68566       *pnHeight = p->nHeight;
68567     }
68568   }
68569 }
68570 static void heightOfExprList(ExprList *p, int *pnHeight){
68571   if( p ){
68572     int i;
68573     for(i=0; i<p->nExpr; i++){
68574       heightOfExpr(p->a[i].pExpr, pnHeight);
68575     }
68576   }
68577 }
68578 static void heightOfSelect(Select *p, int *pnHeight){
68579   if( p ){
68580     heightOfExpr(p->pWhere, pnHeight);
68581     heightOfExpr(p->pHaving, pnHeight);
68582     heightOfExpr(p->pLimit, pnHeight);
68583     heightOfExpr(p->pOffset, pnHeight);
68584     heightOfExprList(p->pEList, pnHeight);
68585     heightOfExprList(p->pGroupBy, pnHeight);
68586     heightOfExprList(p->pOrderBy, pnHeight);
68587     heightOfSelect(p->pPrior, pnHeight);
68588   }
68589 }
68590
68591 /*
68592 ** Set the Expr.nHeight variable in the structure passed as an 
68593 ** argument. An expression with no children, Expr.pList or 
68594 ** Expr.pSelect member has a height of 1. Any other expression
68595 ** has a height equal to the maximum height of any other 
68596 ** referenced Expr plus one.
68597 */
68598 static void exprSetHeight(Expr *p){
68599   int nHeight = 0;
68600   heightOfExpr(p->pLeft, &nHeight);
68601   heightOfExpr(p->pRight, &nHeight);
68602   if( ExprHasProperty(p, EP_xIsSelect) ){
68603     heightOfSelect(p->x.pSelect, &nHeight);
68604   }else{
68605     heightOfExprList(p->x.pList, &nHeight);
68606   }
68607   p->nHeight = nHeight + 1;
68608 }
68609
68610 /*
68611 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
68612 ** the height is greater than the maximum allowed expression depth,
68613 ** leave an error in pParse.
68614 */
68615 SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
68616   exprSetHeight(p);
68617   sqlite3ExprCheckHeight(pParse, p->nHeight);
68618 }
68619
68620 /*
68621 ** Return the maximum height of any expression tree referenced
68622 ** by the select statement passed as an argument.
68623 */
68624 SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
68625   int nHeight = 0;
68626   heightOfSelect(p, &nHeight);
68627   return nHeight;
68628 }
68629 #else
68630   #define exprSetHeight(y)
68631 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
68632
68633 /*
68634 ** This routine is the core allocator for Expr nodes.
68635 **
68636 ** Construct a new expression node and return a pointer to it.  Memory
68637 ** for this node and for the pToken argument is a single allocation
68638 ** obtained from sqlite3DbMalloc().  The calling function
68639 ** is responsible for making sure the node eventually gets freed.
68640 **
68641 ** If dequote is true, then the token (if it exists) is dequoted.
68642 ** If dequote is false, no dequoting is performance.  The deQuote
68643 ** parameter is ignored if pToken is NULL or if the token does not
68644 ** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
68645 ** then the EP_DblQuoted flag is set on the expression node.
68646 **
68647 ** Special case:  If op==TK_INTEGER and pToken points to a string that
68648 ** can be translated into a 32-bit integer, then the token is not
68649 ** stored in u.zToken.  Instead, the integer values is written
68650 ** into u.iValue and the EP_IntValue flag is set.  No extra storage
68651 ** is allocated to hold the integer text and the dequote flag is ignored.
68652 */
68653 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
68654   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
68655   int op,                 /* Expression opcode */
68656   const Token *pToken,    /* Token argument.  Might be NULL */
68657   int dequote             /* True to dequote */
68658 ){
68659   Expr *pNew;
68660   int nExtra = 0;
68661   int iValue = 0;
68662
68663   if( pToken ){
68664     if( op!=TK_INTEGER || pToken->z==0
68665           || sqlite3GetInt32(pToken->z, &iValue)==0 ){
68666       nExtra = pToken->n+1;
68667     }
68668   }
68669   pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
68670   if( pNew ){
68671     pNew->op = (u8)op;
68672     pNew->iAgg = -1;
68673     if( pToken ){
68674       if( nExtra==0 ){
68675         pNew->flags |= EP_IntValue;
68676         pNew->u.iValue = iValue;
68677       }else{
68678         int c;
68679         pNew->u.zToken = (char*)&pNew[1];
68680         memcpy(pNew->u.zToken, pToken->z, pToken->n);
68681         pNew->u.zToken[pToken->n] = 0;
68682         if( dequote && nExtra>=3 
68683              && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
68684           sqlite3Dequote(pNew->u.zToken);
68685           if( c=='"' ) pNew->flags |= EP_DblQuoted;
68686         }
68687       }
68688     }
68689 #if SQLITE_MAX_EXPR_DEPTH>0
68690     pNew->nHeight = 1;
68691 #endif  
68692   }
68693   return pNew;
68694 }
68695
68696 /*
68697 ** Allocate a new expression node from a zero-terminated token that has
68698 ** already been dequoted.
68699 */
68700 SQLITE_PRIVATE Expr *sqlite3Expr(
68701   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
68702   int op,                 /* Expression opcode */
68703   const char *zToken      /* Token argument.  Might be NULL */
68704 ){
68705   Token x;
68706   x.z = zToken;
68707   x.n = zToken ? sqlite3Strlen30(zToken) : 0;
68708   return sqlite3ExprAlloc(db, op, &x, 0);
68709 }
68710
68711 /*
68712 ** Attach subtrees pLeft and pRight to the Expr node pRoot.
68713 **
68714 ** If pRoot==NULL that means that a memory allocation error has occurred.
68715 ** In that case, delete the subtrees pLeft and pRight.
68716 */
68717 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
68718   sqlite3 *db,
68719   Expr *pRoot,
68720   Expr *pLeft,
68721   Expr *pRight
68722 ){
68723   if( pRoot==0 ){
68724     assert( db->mallocFailed );
68725     sqlite3ExprDelete(db, pLeft);
68726     sqlite3ExprDelete(db, pRight);
68727   }else{
68728     if( pRight ){
68729       pRoot->pRight = pRight;
68730       if( pRight->flags & EP_ExpCollate ){
68731         pRoot->flags |= EP_ExpCollate;
68732         pRoot->pColl = pRight->pColl;
68733       }
68734     }
68735     if( pLeft ){
68736       pRoot->pLeft = pLeft;
68737       if( pLeft->flags & EP_ExpCollate ){
68738         pRoot->flags |= EP_ExpCollate;
68739         pRoot->pColl = pLeft->pColl;
68740       }
68741     }
68742     exprSetHeight(pRoot);
68743   }
68744 }
68745
68746 /*
68747 ** Allocate a Expr node which joins as many as two subtrees.
68748 **
68749 ** One or both of the subtrees can be NULL.  Return a pointer to the new
68750 ** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
68751 ** free the subtrees and return NULL.
68752 */
68753 SQLITE_PRIVATE Expr *sqlite3PExpr(
68754   Parse *pParse,          /* Parsing context */
68755   int op,                 /* Expression opcode */
68756   Expr *pLeft,            /* Left operand */
68757   Expr *pRight,           /* Right operand */
68758   const Token *pToken     /* Argument token */
68759 ){
68760   Expr *p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
68761   sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
68762   return p;
68763 }
68764
68765 /*
68766 ** Join two expressions using an AND operator.  If either expression is
68767 ** NULL, then just return the other expression.
68768 */
68769 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
68770   if( pLeft==0 ){
68771     return pRight;
68772   }else if( pRight==0 ){
68773     return pLeft;
68774   }else{
68775     Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
68776     sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
68777     return pNew;
68778   }
68779 }
68780
68781 /*
68782 ** Construct a new expression node for a function with multiple
68783 ** arguments.
68784 */
68785 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
68786   Expr *pNew;
68787   sqlite3 *db = pParse->db;
68788   assert( pToken );
68789   pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
68790   if( pNew==0 ){
68791     sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
68792     return 0;
68793   }
68794   pNew->x.pList = pList;
68795   assert( !ExprHasProperty(pNew, EP_xIsSelect) );
68796   sqlite3ExprSetHeight(pParse, pNew);
68797   return pNew;
68798 }
68799
68800 /*
68801 ** Assign a variable number to an expression that encodes a wildcard
68802 ** in the original SQL statement.  
68803 **
68804 ** Wildcards consisting of a single "?" are assigned the next sequential
68805 ** variable number.
68806 **
68807 ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
68808 ** sure "nnn" is not too be to avoid a denial of service attack when
68809 ** the SQL statement comes from an external source.
68810 **
68811 ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
68812 ** as the previous instance of the same wildcard.  Or if this is the first
68813 ** instance of the wildcard, the next sequenial variable number is
68814 ** assigned.
68815 */
68816 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
68817   sqlite3 *db = pParse->db;
68818   const char *z;
68819
68820   if( pExpr==0 ) return;
68821   assert( !ExprHasAnyProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
68822   z = pExpr->u.zToken;
68823   assert( z!=0 );
68824   assert( z[0]!=0 );
68825   if( z[1]==0 ){
68826     /* Wildcard of the form "?".  Assign the next variable number */
68827     assert( z[0]=='?' );
68828     pExpr->iColumn = (ynVar)(++pParse->nVar);
68829   }else if( z[0]=='?' ){
68830     /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
68831     ** use it as the variable number */
68832     i64 i;
68833     int bOk = 0==sqlite3Atoi64(&z[1], &i, sqlite3Strlen30(&z[1]), SQLITE_UTF8);
68834     pExpr->iColumn = (ynVar)i;
68835     testcase( i==0 );
68836     testcase( i==1 );
68837     testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
68838     testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
68839     if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
68840       sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
68841           db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
68842     }
68843     if( i>pParse->nVar ){
68844       pParse->nVar = (int)i;
68845     }
68846   }else{
68847     /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
68848     ** number as the prior appearance of the same name, or if the name
68849     ** has never appeared before, reuse the same variable number
68850     */
68851     int i;
68852     u32 n;
68853     n = sqlite3Strlen30(z);
68854     for(i=0; i<pParse->nVarExpr; i++){
68855       Expr *pE = pParse->apVarExpr[i];
68856       assert( pE!=0 );
68857       if( memcmp(pE->u.zToken, z, n)==0 && pE->u.zToken[n]==0 ){
68858         pExpr->iColumn = pE->iColumn;
68859         break;
68860       }
68861     }
68862     if( i>=pParse->nVarExpr ){
68863       pExpr->iColumn = (ynVar)(++pParse->nVar);
68864       if( pParse->nVarExpr>=pParse->nVarExprAlloc-1 ){
68865         pParse->nVarExprAlloc += pParse->nVarExprAlloc + 10;
68866         pParse->apVarExpr =
68867             sqlite3DbReallocOrFree(
68868               db,
68869               pParse->apVarExpr,
68870               pParse->nVarExprAlloc*sizeof(pParse->apVarExpr[0])
68871             );
68872       }
68873       if( !db->mallocFailed ){
68874         assert( pParse->apVarExpr!=0 );
68875         pParse->apVarExpr[pParse->nVarExpr++] = pExpr;
68876       }
68877     }
68878   } 
68879   if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
68880     sqlite3ErrorMsg(pParse, "too many SQL variables");
68881   }
68882 }
68883
68884 /*
68885 ** Recursively delete an expression tree.
68886 */
68887 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
68888   if( p==0 ) return;
68889   if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
68890     sqlite3ExprDelete(db, p->pLeft);
68891     sqlite3ExprDelete(db, p->pRight);
68892     if( !ExprHasProperty(p, EP_Reduced) && (p->flags2 & EP2_MallocedToken)!=0 ){
68893       sqlite3DbFree(db, p->u.zToken);
68894     }
68895     if( ExprHasProperty(p, EP_xIsSelect) ){
68896       sqlite3SelectDelete(db, p->x.pSelect);
68897     }else{
68898       sqlite3ExprListDelete(db, p->x.pList);
68899     }
68900   }
68901   if( !ExprHasProperty(p, EP_Static) ){
68902     sqlite3DbFree(db, p);
68903   }
68904 }
68905
68906 /*
68907 ** Return the number of bytes allocated for the expression structure 
68908 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
68909 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
68910 */
68911 static int exprStructSize(Expr *p){
68912   if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
68913   if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
68914   return EXPR_FULLSIZE;
68915 }
68916
68917 /*
68918 ** The dupedExpr*Size() routines each return the number of bytes required
68919 ** to store a copy of an expression or expression tree.  They differ in
68920 ** how much of the tree is measured.
68921 **
68922 **     dupedExprStructSize()     Size of only the Expr structure 
68923 **     dupedExprNodeSize()       Size of Expr + space for token
68924 **     dupedExprSize()           Expr + token + subtree components
68925 **
68926 ***************************************************************************
68927 **
68928 ** The dupedExprStructSize() function returns two values OR-ed together:  
68929 ** (1) the space required for a copy of the Expr structure only and 
68930 ** (2) the EP_xxx flags that indicate what the structure size should be.
68931 ** The return values is always one of:
68932 **
68933 **      EXPR_FULLSIZE
68934 **      EXPR_REDUCEDSIZE   | EP_Reduced
68935 **      EXPR_TOKENONLYSIZE | EP_TokenOnly
68936 **
68937 ** The size of the structure can be found by masking the return value
68938 ** of this routine with 0xfff.  The flags can be found by masking the
68939 ** return value with EP_Reduced|EP_TokenOnly.
68940 **
68941 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
68942 ** (unreduced) Expr objects as they or originally constructed by the parser.
68943 ** During expression analysis, extra information is computed and moved into
68944 ** later parts of teh Expr object and that extra information might get chopped
68945 ** off if the expression is reduced.  Note also that it does not work to
68946 ** make a EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
68947 ** to reduce a pristine expression tree from the parser.  The implementation
68948 ** of dupedExprStructSize() contain multiple assert() statements that attempt
68949 ** to enforce this constraint.
68950 */
68951 static int dupedExprStructSize(Expr *p, int flags){
68952   int nSize;
68953   assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
68954   if( 0==(flags&EXPRDUP_REDUCE) ){
68955     nSize = EXPR_FULLSIZE;
68956   }else{
68957     assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
68958     assert( !ExprHasProperty(p, EP_FromJoin) ); 
68959     assert( (p->flags2 & EP2_MallocedToken)==0 );
68960     assert( (p->flags2 & EP2_Irreducible)==0 );
68961     if( p->pLeft || p->pRight || p->pColl || p->x.pList ){
68962       nSize = EXPR_REDUCEDSIZE | EP_Reduced;
68963     }else{
68964       nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
68965     }
68966   }
68967   return nSize;
68968 }
68969
68970 /*
68971 ** This function returns the space in bytes required to store the copy 
68972 ** of the Expr structure and a copy of the Expr.u.zToken string (if that
68973 ** string is defined.)
68974 */
68975 static int dupedExprNodeSize(Expr *p, int flags){
68976   int nByte = dupedExprStructSize(p, flags) & 0xfff;
68977   if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
68978     nByte += sqlite3Strlen30(p->u.zToken)+1;
68979   }
68980   return ROUND8(nByte);
68981 }
68982
68983 /*
68984 ** Return the number of bytes required to create a duplicate of the 
68985 ** expression passed as the first argument. The second argument is a
68986 ** mask containing EXPRDUP_XXX flags.
68987 **
68988 ** The value returned includes space to create a copy of the Expr struct
68989 ** itself and the buffer referred to by Expr.u.zToken, if any.
68990 **
68991 ** If the EXPRDUP_REDUCE flag is set, then the return value includes 
68992 ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft 
68993 ** and Expr.pRight variables (but not for any structures pointed to or 
68994 ** descended from the Expr.x.pList or Expr.x.pSelect variables).
68995 */
68996 static int dupedExprSize(Expr *p, int flags){
68997   int nByte = 0;
68998   if( p ){
68999     nByte = dupedExprNodeSize(p, flags);
69000     if( flags&EXPRDUP_REDUCE ){
69001       nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
69002     }
69003   }
69004   return nByte;
69005 }
69006
69007 /*
69008 ** This function is similar to sqlite3ExprDup(), except that if pzBuffer 
69009 ** is not NULL then *pzBuffer is assumed to point to a buffer large enough 
69010 ** to store the copy of expression p, the copies of p->u.zToken
69011 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
69012 ** if any. Before returning, *pzBuffer is set to the first byte passed the
69013 ** portion of the buffer copied into by this function.
69014 */
69015 static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
69016   Expr *pNew = 0;                      /* Value to return */
69017   if( p ){
69018     const int isReduced = (flags&EXPRDUP_REDUCE);
69019     u8 *zAlloc;
69020     u32 staticFlag = 0;
69021
69022     assert( pzBuffer==0 || isReduced );
69023
69024     /* Figure out where to write the new Expr structure. */
69025     if( pzBuffer ){
69026       zAlloc = *pzBuffer;
69027       staticFlag = EP_Static;
69028     }else{
69029       zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
69030     }
69031     pNew = (Expr *)zAlloc;
69032
69033     if( pNew ){
69034       /* Set nNewSize to the size allocated for the structure pointed to
69035       ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
69036       ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
69037       ** by the copy of the p->u.zToken string (if any).
69038       */
69039       const unsigned nStructSize = dupedExprStructSize(p, flags);
69040       const int nNewSize = nStructSize & 0xfff;
69041       int nToken;
69042       if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
69043         nToken = sqlite3Strlen30(p->u.zToken) + 1;
69044       }else{
69045         nToken = 0;
69046       }
69047       if( isReduced ){
69048         assert( ExprHasProperty(p, EP_Reduced)==0 );
69049         memcpy(zAlloc, p, nNewSize);
69050       }else{
69051         int nSize = exprStructSize(p);
69052         memcpy(zAlloc, p, nSize);
69053         memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
69054       }
69055
69056       /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
69057       pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static);
69058       pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
69059       pNew->flags |= staticFlag;
69060
69061       /* Copy the p->u.zToken string, if any. */
69062       if( nToken ){
69063         char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
69064         memcpy(zToken, p->u.zToken, nToken);
69065       }
69066
69067       if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
69068         /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
69069         if( ExprHasProperty(p, EP_xIsSelect) ){
69070           pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
69071         }else{
69072           pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
69073         }
69074       }
69075
69076       /* Fill in pNew->pLeft and pNew->pRight. */
69077       if( ExprHasAnyProperty(pNew, EP_Reduced|EP_TokenOnly) ){
69078         zAlloc += dupedExprNodeSize(p, flags);
69079         if( ExprHasProperty(pNew, EP_Reduced) ){
69080           pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
69081           pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
69082         }
69083         if( pzBuffer ){
69084           *pzBuffer = zAlloc;
69085         }
69086       }else{
69087         pNew->flags2 = 0;
69088         if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
69089           pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
69090           pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
69091         }
69092       }
69093
69094     }
69095   }
69096   return pNew;
69097 }
69098
69099 /*
69100 ** The following group of routines make deep copies of expressions,
69101 ** expression lists, ID lists, and select statements.  The copies can
69102 ** be deleted (by being passed to their respective ...Delete() routines)
69103 ** without effecting the originals.
69104 **
69105 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
69106 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded 
69107 ** by subsequent calls to sqlite*ListAppend() routines.
69108 **
69109 ** Any tables that the SrcList might point to are not duplicated.
69110 **
69111 ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
69112 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
69113 ** truncated version of the usual Expr structure that will be stored as
69114 ** part of the in-memory representation of the database schema.
69115 */
69116 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
69117   return exprDup(db, p, flags, 0);
69118 }
69119 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
69120   ExprList *pNew;
69121   struct ExprList_item *pItem, *pOldItem;
69122   int i;
69123   if( p==0 ) return 0;
69124   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
69125   if( pNew==0 ) return 0;
69126   pNew->iECursor = 0;
69127   pNew->nExpr = pNew->nAlloc = p->nExpr;
69128   pNew->a = pItem = sqlite3DbMallocRaw(db,  p->nExpr*sizeof(p->a[0]) );
69129   if( pItem==0 ){
69130     sqlite3DbFree(db, pNew);
69131     return 0;
69132   } 
69133   pOldItem = p->a;
69134   for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
69135     Expr *pOldExpr = pOldItem->pExpr;
69136     pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
69137     pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
69138     pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
69139     pItem->sortOrder = pOldItem->sortOrder;
69140     pItem->done = 0;
69141     pItem->iCol = pOldItem->iCol;
69142     pItem->iAlias = pOldItem->iAlias;
69143   }
69144   return pNew;
69145 }
69146
69147 /*
69148 ** If cursors, triggers, views and subqueries are all omitted from
69149 ** the build, then none of the following routines, except for 
69150 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
69151 ** called with a NULL argument.
69152 */
69153 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
69154  || !defined(SQLITE_OMIT_SUBQUERY)
69155 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
69156   SrcList *pNew;
69157   int i;
69158   int nByte;
69159   if( p==0 ) return 0;
69160   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
69161   pNew = sqlite3DbMallocRaw(db, nByte );
69162   if( pNew==0 ) return 0;
69163   pNew->nSrc = pNew->nAlloc = p->nSrc;
69164   for(i=0; i<p->nSrc; i++){
69165     struct SrcList_item *pNewItem = &pNew->a[i];
69166     struct SrcList_item *pOldItem = &p->a[i];
69167     Table *pTab;
69168     pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
69169     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
69170     pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
69171     pNewItem->jointype = pOldItem->jointype;
69172     pNewItem->iCursor = pOldItem->iCursor;
69173     pNewItem->isPopulated = pOldItem->isPopulated;
69174     pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
69175     pNewItem->notIndexed = pOldItem->notIndexed;
69176     pNewItem->pIndex = pOldItem->pIndex;
69177     pTab = pNewItem->pTab = pOldItem->pTab;
69178     if( pTab ){
69179       pTab->nRef++;
69180     }
69181     pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
69182     pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
69183     pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
69184     pNewItem->colUsed = pOldItem->colUsed;
69185   }
69186   return pNew;
69187 }
69188 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
69189   IdList *pNew;
69190   int i;
69191   if( p==0 ) return 0;
69192   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
69193   if( pNew==0 ) return 0;
69194   pNew->nId = pNew->nAlloc = p->nId;
69195   pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
69196   if( pNew->a==0 ){
69197     sqlite3DbFree(db, pNew);
69198     return 0;
69199   }
69200   for(i=0; i<p->nId; i++){
69201     struct IdList_item *pNewItem = &pNew->a[i];
69202     struct IdList_item *pOldItem = &p->a[i];
69203     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
69204     pNewItem->idx = pOldItem->idx;
69205   }
69206   return pNew;
69207 }
69208 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
69209   Select *pNew;
69210   if( p==0 ) return 0;
69211   pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
69212   if( pNew==0 ) return 0;
69213   pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
69214   pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
69215   pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
69216   pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
69217   pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
69218   pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
69219   pNew->op = p->op;
69220   pNew->pPrior = sqlite3SelectDup(db, p->pPrior, flags);
69221   pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
69222   pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
69223   pNew->iLimit = 0;
69224   pNew->iOffset = 0;
69225   pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
69226   pNew->pRightmost = 0;
69227   pNew->addrOpenEphm[0] = -1;
69228   pNew->addrOpenEphm[1] = -1;
69229   pNew->addrOpenEphm[2] = -1;
69230   return pNew;
69231 }
69232 #else
69233 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
69234   assert( p==0 );
69235   return 0;
69236 }
69237 #endif
69238
69239
69240 /*
69241 ** Add a new element to the end of an expression list.  If pList is
69242 ** initially NULL, then create a new expression list.
69243 **
69244 ** If a memory allocation error occurs, the entire list is freed and
69245 ** NULL is returned.  If non-NULL is returned, then it is guaranteed
69246 ** that the new entry was successfully appended.
69247 */
69248 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
69249   Parse *pParse,          /* Parsing context */
69250   ExprList *pList,        /* List to which to append. Might be NULL */
69251   Expr *pExpr             /* Expression to be appended. Might be NULL */
69252 ){
69253   sqlite3 *db = pParse->db;
69254   if( pList==0 ){
69255     pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
69256     if( pList==0 ){
69257       goto no_mem;
69258     }
69259     assert( pList->nAlloc==0 );
69260   }
69261   if( pList->nAlloc<=pList->nExpr ){
69262     struct ExprList_item *a;
69263     int n = pList->nAlloc*2 + 4;
69264     a = sqlite3DbRealloc(db, pList->a, n*sizeof(pList->a[0]));
69265     if( a==0 ){
69266       goto no_mem;
69267     }
69268     pList->a = a;
69269     pList->nAlloc = sqlite3DbMallocSize(db, a)/sizeof(a[0]);
69270   }
69271   assert( pList->a!=0 );
69272   if( 1 ){
69273     struct ExprList_item *pItem = &pList->a[pList->nExpr++];
69274     memset(pItem, 0, sizeof(*pItem));
69275     pItem->pExpr = pExpr;
69276   }
69277   return pList;
69278
69279 no_mem:     
69280   /* Avoid leaking memory if malloc has failed. */
69281   sqlite3ExprDelete(db, pExpr);
69282   sqlite3ExprListDelete(db, pList);
69283   return 0;
69284 }
69285
69286 /*
69287 ** Set the ExprList.a[].zName element of the most recently added item
69288 ** on the expression list.
69289 **
69290 ** pList might be NULL following an OOM error.  But pName should never be
69291 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
69292 ** is set.
69293 */
69294 SQLITE_PRIVATE void sqlite3ExprListSetName(
69295   Parse *pParse,          /* Parsing context */
69296   ExprList *pList,        /* List to which to add the span. */
69297   Token *pName,           /* Name to be added */
69298   int dequote             /* True to cause the name to be dequoted */
69299 ){
69300   assert( pList!=0 || pParse->db->mallocFailed!=0 );
69301   if( pList ){
69302     struct ExprList_item *pItem;
69303     assert( pList->nExpr>0 );
69304     pItem = &pList->a[pList->nExpr-1];
69305     assert( pItem->zName==0 );
69306     pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
69307     if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
69308   }
69309 }
69310
69311 /*
69312 ** Set the ExprList.a[].zSpan element of the most recently added item
69313 ** on the expression list.
69314 **
69315 ** pList might be NULL following an OOM error.  But pSpan should never be
69316 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
69317 ** is set.
69318 */
69319 SQLITE_PRIVATE void sqlite3ExprListSetSpan(
69320   Parse *pParse,          /* Parsing context */
69321   ExprList *pList,        /* List to which to add the span. */
69322   ExprSpan *pSpan         /* The span to be added */
69323 ){
69324   sqlite3 *db = pParse->db;
69325   assert( pList!=0 || db->mallocFailed!=0 );
69326   if( pList ){
69327     struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
69328     assert( pList->nExpr>0 );
69329     assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
69330     sqlite3DbFree(db, pItem->zSpan);
69331     pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
69332                                     (int)(pSpan->zEnd - pSpan->zStart));
69333   }
69334 }
69335
69336 /*
69337 ** If the expression list pEList contains more than iLimit elements,
69338 ** leave an error message in pParse.
69339 */
69340 SQLITE_PRIVATE void sqlite3ExprListCheckLength(
69341   Parse *pParse,
69342   ExprList *pEList,
69343   const char *zObject
69344 ){
69345   int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
69346   testcase( pEList && pEList->nExpr==mx );
69347   testcase( pEList && pEList->nExpr==mx+1 );
69348   if( pEList && pEList->nExpr>mx ){
69349     sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
69350   }
69351 }
69352
69353 /*
69354 ** Delete an entire expression list.
69355 */
69356 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
69357   int i;
69358   struct ExprList_item *pItem;
69359   if( pList==0 ) return;
69360   assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
69361   assert( pList->nExpr<=pList->nAlloc );
69362   for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
69363     sqlite3ExprDelete(db, pItem->pExpr);
69364     sqlite3DbFree(db, pItem->zName);
69365     sqlite3DbFree(db, pItem->zSpan);
69366   }
69367   sqlite3DbFree(db, pList->a);
69368   sqlite3DbFree(db, pList);
69369 }
69370
69371 /*
69372 ** These routines are Walker callbacks.  Walker.u.pi is a pointer
69373 ** to an integer.  These routines are checking an expression to see
69374 ** if it is a constant.  Set *Walker.u.pi to 0 if the expression is
69375 ** not constant.
69376 **
69377 ** These callback routines are used to implement the following:
69378 **
69379 **     sqlite3ExprIsConstant()
69380 **     sqlite3ExprIsConstantNotJoin()
69381 **     sqlite3ExprIsConstantOrFunction()
69382 **
69383 */
69384 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
69385
69386   /* If pWalker->u.i is 3 then any term of the expression that comes from
69387   ** the ON or USING clauses of a join disqualifies the expression
69388   ** from being considered constant. */
69389   if( pWalker->u.i==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
69390     pWalker->u.i = 0;
69391     return WRC_Abort;
69392   }
69393
69394   switch( pExpr->op ){
69395     /* Consider functions to be constant if all their arguments are constant
69396     ** and pWalker->u.i==2 */
69397     case TK_FUNCTION:
69398       if( pWalker->u.i==2 ) return 0;
69399       /* Fall through */
69400     case TK_ID:
69401     case TK_COLUMN:
69402     case TK_AGG_FUNCTION:
69403     case TK_AGG_COLUMN:
69404       testcase( pExpr->op==TK_ID );
69405       testcase( pExpr->op==TK_COLUMN );
69406       testcase( pExpr->op==TK_AGG_FUNCTION );
69407       testcase( pExpr->op==TK_AGG_COLUMN );
69408       pWalker->u.i = 0;
69409       return WRC_Abort;
69410     default:
69411       testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
69412       testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
69413       return WRC_Continue;
69414   }
69415 }
69416 static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
69417   UNUSED_PARAMETER(NotUsed);
69418   pWalker->u.i = 0;
69419   return WRC_Abort;
69420 }
69421 static int exprIsConst(Expr *p, int initFlag){
69422   Walker w;
69423   w.u.i = initFlag;
69424   w.xExprCallback = exprNodeIsConstant;
69425   w.xSelectCallback = selectNodeIsConstant;
69426   sqlite3WalkExpr(&w, p);
69427   return w.u.i;
69428 }
69429
69430 /*
69431 ** Walk an expression tree.  Return 1 if the expression is constant
69432 ** and 0 if it involves variables or function calls.
69433 **
69434 ** For the purposes of this function, a double-quoted string (ex: "abc")
69435 ** is considered a variable but a single-quoted string (ex: 'abc') is
69436 ** a constant.
69437 */
69438 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
69439   return exprIsConst(p, 1);
69440 }
69441
69442 /*
69443 ** Walk an expression tree.  Return 1 if the expression is constant
69444 ** that does no originate from the ON or USING clauses of a join.
69445 ** Return 0 if it involves variables or function calls or terms from
69446 ** an ON or USING clause.
69447 */
69448 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
69449   return exprIsConst(p, 3);
69450 }
69451
69452 /*
69453 ** Walk an expression tree.  Return 1 if the expression is constant
69454 ** or a function call with constant arguments.  Return and 0 if there
69455 ** are any variables.
69456 **
69457 ** For the purposes of this function, a double-quoted string (ex: "abc")
69458 ** is considered a variable but a single-quoted string (ex: 'abc') is
69459 ** a constant.
69460 */
69461 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p){
69462   return exprIsConst(p, 2);
69463 }
69464
69465 /*
69466 ** If the expression p codes a constant integer that is small enough
69467 ** to fit in a 32-bit integer, return 1 and put the value of the integer
69468 ** in *pValue.  If the expression is not an integer or if it is too big
69469 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
69470 */
69471 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
69472   int rc = 0;
69473   if( p->flags & EP_IntValue ){
69474     *pValue = p->u.iValue;
69475     return 1;
69476   }
69477   switch( p->op ){
69478     case TK_INTEGER: {
69479       rc = sqlite3GetInt32(p->u.zToken, pValue);
69480       assert( rc==0 );
69481       break;
69482     }
69483     case TK_UPLUS: {
69484       rc = sqlite3ExprIsInteger(p->pLeft, pValue);
69485       break;
69486     }
69487     case TK_UMINUS: {
69488       int v;
69489       if( sqlite3ExprIsInteger(p->pLeft, &v) ){
69490         *pValue = -v;
69491         rc = 1;
69492       }
69493       break;
69494     }
69495     default: break;
69496   }
69497   if( rc ){
69498     assert( ExprHasAnyProperty(p, EP_Reduced|EP_TokenOnly)
69499                || (p->flags2 & EP2_MallocedToken)==0 );
69500     p->op = TK_INTEGER;
69501     p->flags |= EP_IntValue;
69502     p->u.iValue = *pValue;
69503   }
69504   return rc;
69505 }
69506
69507 /*
69508 ** Return FALSE if there is no chance that the expression can be NULL.
69509 **
69510 ** If the expression might be NULL or if the expression is too complex
69511 ** to tell return TRUE.  
69512 **
69513 ** This routine is used as an optimization, to skip OP_IsNull opcodes
69514 ** when we know that a value cannot be NULL.  Hence, a false positive
69515 ** (returning TRUE when in fact the expression can never be NULL) might
69516 ** be a small performance hit but is otherwise harmless.  On the other
69517 ** hand, a false negative (returning FALSE when the result could be NULL)
69518 ** will likely result in an incorrect answer.  So when in doubt, return
69519 ** TRUE.
69520 */
69521 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
69522   u8 op;
69523   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
69524   op = p->op;
69525   if( op==TK_REGISTER ) op = p->op2;
69526   switch( op ){
69527     case TK_INTEGER:
69528     case TK_STRING:
69529     case TK_FLOAT:
69530     case TK_BLOB:
69531       return 0;
69532     default:
69533       return 1;
69534   }
69535 }
69536
69537 /*
69538 ** Generate an OP_IsNull instruction that tests register iReg and jumps
69539 ** to location iDest if the value in iReg is NULL.  The value in iReg 
69540 ** was computed by pExpr.  If we can look at pExpr at compile-time and
69541 ** determine that it can never generate a NULL, then the OP_IsNull operation
69542 ** can be omitted.
69543 */
69544 SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(
69545   Vdbe *v,            /* The VDBE under construction */
69546   const Expr *pExpr,  /* Only generate OP_IsNull if this expr can be NULL */
69547   int iReg,           /* Test the value in this register for NULL */
69548   int iDest           /* Jump here if the value is null */
69549 ){
69550   if( sqlite3ExprCanBeNull(pExpr) ){
69551     sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iDest);
69552   }
69553 }
69554
69555 /*
69556 ** Return TRUE if the given expression is a constant which would be
69557 ** unchanged by OP_Affinity with the affinity given in the second
69558 ** argument.
69559 **
69560 ** This routine is used to determine if the OP_Affinity operation
69561 ** can be omitted.  When in doubt return FALSE.  A false negative
69562 ** is harmless.  A false positive, however, can result in the wrong
69563 ** answer.
69564 */
69565 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
69566   u8 op;
69567   if( aff==SQLITE_AFF_NONE ) return 1;
69568   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
69569   op = p->op;
69570   if( op==TK_REGISTER ) op = p->op2;
69571   switch( op ){
69572     case TK_INTEGER: {
69573       return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
69574     }
69575     case TK_FLOAT: {
69576       return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
69577     }
69578     case TK_STRING: {
69579       return aff==SQLITE_AFF_TEXT;
69580     }
69581     case TK_BLOB: {
69582       return 1;
69583     }
69584     case TK_COLUMN: {
69585       assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */
69586       return p->iColumn<0
69587           && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
69588     }
69589     default: {
69590       return 0;
69591     }
69592   }
69593 }
69594
69595 /*
69596 ** Return TRUE if the given string is a row-id column name.
69597 */
69598 SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
69599   if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
69600   if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
69601   if( sqlite3StrICmp(z, "OID")==0 ) return 1;
69602   return 0;
69603 }
69604
69605 /*
69606 ** Return true if we are able to the IN operator optimization on a
69607 ** query of the form
69608 **
69609 **       x IN (SELECT ...)
69610 **
69611 ** Where the SELECT... clause is as specified by the parameter to this
69612 ** routine.
69613 **
69614 ** The Select object passed in has already been preprocessed and no
69615 ** errors have been found.
69616 */
69617 #ifndef SQLITE_OMIT_SUBQUERY
69618 static int isCandidateForInOpt(Select *p){
69619   SrcList *pSrc;
69620   ExprList *pEList;
69621   Table *pTab;
69622   if( p==0 ) return 0;                   /* right-hand side of IN is SELECT */
69623   if( p->pPrior ) return 0;              /* Not a compound SELECT */
69624   if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
69625     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
69626     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
69627     return 0; /* No DISTINCT keyword and no aggregate functions */
69628   }
69629   assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */
69630   if( p->pLimit ) return 0;              /* Has no LIMIT clause */
69631   assert( p->pOffset==0 );               /* No LIMIT means no OFFSET */
69632   if( p->pWhere ) return 0;              /* Has no WHERE clause */
69633   pSrc = p->pSrc;
69634   assert( pSrc!=0 );
69635   if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
69636   if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
69637   pTab = pSrc->a[0].pTab;
69638   if( NEVER(pTab==0) ) return 0;
69639   assert( pTab->pSelect==0 );            /* FROM clause is not a view */
69640   if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
69641   pEList = p->pEList;
69642   if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
69643   if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
69644   return 1;
69645 }
69646 #endif /* SQLITE_OMIT_SUBQUERY */
69647
69648 /*
69649 ** This function is used by the implementation of the IN (...) operator.
69650 ** It's job is to find or create a b-tree structure that may be used
69651 ** either to test for membership of the (...) set or to iterate through
69652 ** its members, skipping duplicates.
69653 **
69654 ** The index of the cursor opened on the b-tree (database table, database index 
69655 ** or ephermal table) is stored in pX->iTable before this function returns.
69656 ** The returned value of this function indicates the b-tree type, as follows:
69657 **
69658 **   IN_INDEX_ROWID - The cursor was opened on a database table.
69659 **   IN_INDEX_INDEX - The cursor was opened on a database index.
69660 **   IN_INDEX_EPH -   The cursor was opened on a specially created and
69661 **                    populated epheremal table.
69662 **
69663 ** An existing b-tree may only be used if the SELECT is of the simple
69664 ** form:
69665 **
69666 **     SELECT <column> FROM <table>
69667 **
69668 ** If the prNotFound parameter is 0, then the b-tree will be used to iterate
69669 ** through the set members, skipping any duplicates. In this case an
69670 ** epheremal table must be used unless the selected <column> is guaranteed
69671 ** to be unique - either because it is an INTEGER PRIMARY KEY or it
69672 ** has a UNIQUE constraint or UNIQUE index.
69673 **
69674 ** If the prNotFound parameter is not 0, then the b-tree will be used 
69675 ** for fast set membership tests. In this case an epheremal table must 
69676 ** be used unless <column> is an INTEGER PRIMARY KEY or an index can 
69677 ** be found with <column> as its left-most column.
69678 **
69679 ** When the b-tree is being used for membership tests, the calling function
69680 ** needs to know whether or not the structure contains an SQL NULL 
69681 ** value in order to correctly evaluate expressions like "X IN (Y, Z)".
69682 ** If there is any chance that the (...) might contain a NULL value at
69683 ** runtime, then a register is allocated and the register number written
69684 ** to *prNotFound. If there is no chance that the (...) contains a
69685 ** NULL value, then *prNotFound is left unchanged.
69686 **
69687 ** If a register is allocated and its location stored in *prNotFound, then
69688 ** its initial value is NULL.  If the (...) does not remain constant
69689 ** for the duration of the query (i.e. the SELECT within the (...)
69690 ** is a correlated subquery) then the value of the allocated register is
69691 ** reset to NULL each time the subquery is rerun. This allows the
69692 ** caller to use vdbe code equivalent to the following:
69693 **
69694 **   if( register==NULL ){
69695 **     has_null = <test if data structure contains null>
69696 **     register = 1
69697 **   }
69698 **
69699 ** in order to avoid running the <test if data structure contains null>
69700 ** test more often than is necessary.
69701 */
69702 #ifndef SQLITE_OMIT_SUBQUERY
69703 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
69704   Select *p;                            /* SELECT to the right of IN operator */
69705   int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
69706   int iTab = pParse->nTab++;            /* Cursor of the RHS table */
69707   int mustBeUnique = (prNotFound==0);   /* True if RHS must be unique */
69708
69709   assert( pX->op==TK_IN );
69710
69711   /* Check to see if an existing table or index can be used to
69712   ** satisfy the query.  This is preferable to generating a new 
69713   ** ephemeral table.
69714   */
69715   p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
69716   if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){
69717     sqlite3 *db = pParse->db;              /* Database connection */
69718     Expr *pExpr = p->pEList->a[0].pExpr;   /* Expression <column> */
69719     int iCol = pExpr->iColumn;             /* Index of column <column> */
69720     Vdbe *v = sqlite3GetVdbe(pParse);      /* Virtual machine being coded */
69721     Table *pTab = p->pSrc->a[0].pTab;      /* Table <table>. */
69722     int iDb;                               /* Database idx for pTab */
69723    
69724     /* Code an OP_VerifyCookie and OP_TableLock for <table>. */
69725     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
69726     sqlite3CodeVerifySchema(pParse, iDb);
69727     sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
69728
69729     /* This function is only called from two places. In both cases the vdbe
69730     ** has already been allocated. So assume sqlite3GetVdbe() is always
69731     ** successful here.
69732     */
69733     assert(v);
69734     if( iCol<0 ){
69735       int iMem = ++pParse->nMem;
69736       int iAddr;
69737
69738       iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
69739       sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
69740
69741       sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
69742       eType = IN_INDEX_ROWID;
69743
69744       sqlite3VdbeJumpHere(v, iAddr);
69745     }else{
69746       Index *pIdx;                         /* Iterator variable */
69747
69748       /* The collation sequence used by the comparison. If an index is to
69749       ** be used in place of a temp-table, it must be ordered according
69750       ** to this collation sequence.  */
69751       CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
69752
69753       /* Check that the affinity that will be used to perform the 
69754       ** comparison is the same as the affinity of the column. If
69755       ** it is not, it is not possible to use any index.
69756       */
69757       char aff = comparisonAffinity(pX);
69758       int affinity_ok = (pTab->aCol[iCol].affinity==aff||aff==SQLITE_AFF_NONE);
69759
69760       for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
69761         if( (pIdx->aiColumn[0]==iCol)
69762          && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
69763          && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
69764         ){
69765           int iMem = ++pParse->nMem;
69766           int iAddr;
69767           char *pKey;
69768   
69769           pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
69770           iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
69771           sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
69772   
69773           sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
69774                                pKey,P4_KEYINFO_HANDOFF);
69775           VdbeComment((v, "%s", pIdx->zName));
69776           eType = IN_INDEX_INDEX;
69777
69778           sqlite3VdbeJumpHere(v, iAddr);
69779           if( prNotFound && !pTab->aCol[iCol].notNull ){
69780             *prNotFound = ++pParse->nMem;
69781           }
69782         }
69783       }
69784     }
69785   }
69786
69787   if( eType==0 ){
69788     /* Could not found an existing table or index to use as the RHS b-tree.
69789     ** We will have to generate an ephemeral table to do the job.
69790     */
69791     double savedNQueryLoop = pParse->nQueryLoop;
69792     int rMayHaveNull = 0;
69793     eType = IN_INDEX_EPH;
69794     if( prNotFound ){
69795       *prNotFound = rMayHaveNull = ++pParse->nMem;
69796     }else{
69797       testcase( pParse->nQueryLoop>(double)1 );
69798       pParse->nQueryLoop = (double)1;
69799       if( pX->pLeft->iColumn<0 && !ExprHasAnyProperty(pX, EP_xIsSelect) ){
69800         eType = IN_INDEX_ROWID;
69801       }
69802     }
69803     sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
69804     pParse->nQueryLoop = savedNQueryLoop;
69805   }else{
69806     pX->iTable = iTab;
69807   }
69808   return eType;
69809 }
69810 #endif
69811
69812 /*
69813 ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
69814 ** or IN operators.  Examples:
69815 **
69816 **     (SELECT a FROM b)          -- subquery
69817 **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
69818 **     x IN (4,5,11)              -- IN operator with list on right-hand side
69819 **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
69820 **
69821 ** The pExpr parameter describes the expression that contains the IN
69822 ** operator or subquery.
69823 **
69824 ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
69825 ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
69826 ** to some integer key column of a table B-Tree. In this case, use an
69827 ** intkey B-Tree to store the set of IN(...) values instead of the usual
69828 ** (slower) variable length keys B-Tree.
69829 **
69830 ** If rMayHaveNull is non-zero, that means that the operation is an IN
69831 ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
69832 ** Furthermore, the IN is in a WHERE clause and that we really want
69833 ** to iterate over the RHS of the IN operator in order to quickly locate
69834 ** all corresponding LHS elements.  All this routine does is initialize
69835 ** the register given by rMayHaveNull to NULL.  Calling routines will take
69836 ** care of changing this register value to non-NULL if the RHS is NULL-free.
69837 **
69838 ** If rMayHaveNull is zero, that means that the subquery is being used
69839 ** for membership testing only.  There is no need to initialize any
69840 ** registers to indicate the presense or absence of NULLs on the RHS.
69841 **
69842 ** For a SELECT or EXISTS operator, return the register that holds the
69843 ** result.  For IN operators or if an error occurs, the return value is 0.
69844 */
69845 #ifndef SQLITE_OMIT_SUBQUERY
69846 SQLITE_PRIVATE int sqlite3CodeSubselect(
69847   Parse *pParse,          /* Parsing context */
69848   Expr *pExpr,            /* The IN, SELECT, or EXISTS operator */
69849   int rMayHaveNull,       /* Register that records whether NULLs exist in RHS */
69850   int isRowid             /* If true, LHS of IN operator is a rowid */
69851 ){
69852   int testAddr = 0;                       /* One-time test address */
69853   int rReg = 0;                           /* Register storing resulting */
69854   Vdbe *v = sqlite3GetVdbe(pParse);
69855   if( NEVER(v==0) ) return 0;
69856   sqlite3ExprCachePush(pParse);
69857
69858   /* This code must be run in its entirety every time it is encountered
69859   ** if any of the following is true:
69860   **
69861   **    *  The right-hand side is a correlated subquery
69862   **    *  The right-hand side is an expression list containing variables
69863   **    *  We are inside a trigger
69864   **
69865   ** If all of the above are false, then we can run this code just once
69866   ** save the results, and reuse the same result on subsequent invocations.
69867   */
69868   if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->pTriggerTab ){
69869     int mem = ++pParse->nMem;
69870     sqlite3VdbeAddOp1(v, OP_If, mem);
69871     testAddr = sqlite3VdbeAddOp2(v, OP_Integer, 1, mem);
69872     assert( testAddr>0 || pParse->db->mallocFailed );
69873   }
69874
69875   switch( pExpr->op ){
69876     case TK_IN: {
69877       char affinity;              /* Affinity of the LHS of the IN */
69878       KeyInfo keyInfo;            /* Keyinfo for the generated table */
69879       int addr;                   /* Address of OP_OpenEphemeral instruction */
69880       Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
69881
69882       if( rMayHaveNull ){
69883         sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
69884       }
69885
69886       affinity = sqlite3ExprAffinity(pLeft);
69887
69888       /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
69889       ** expression it is handled the same way.  An ephemeral table is 
69890       ** filled with single-field index keys representing the results
69891       ** from the SELECT or the <exprlist>.
69892       **
69893       ** If the 'x' expression is a column value, or the SELECT...
69894       ** statement returns a column value, then the affinity of that
69895       ** column is used to build the index keys. If both 'x' and the
69896       ** SELECT... statement are columns, then numeric affinity is used
69897       ** if either column has NUMERIC or INTEGER affinity. If neither
69898       ** 'x' nor the SELECT... statement are columns, then numeric affinity
69899       ** is used.
69900       */
69901       pExpr->iTable = pParse->nTab++;
69902       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
69903       if( rMayHaveNull==0 ) sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
69904       memset(&keyInfo, 0, sizeof(keyInfo));
69905       keyInfo.nField = 1;
69906
69907       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
69908         /* Case 1:     expr IN (SELECT ...)
69909         **
69910         ** Generate code to write the results of the select into the temporary
69911         ** table allocated and opened above.
69912         */
69913         SelectDest dest;
69914         ExprList *pEList;
69915
69916         assert( !isRowid );
69917         sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
69918         dest.affinity = (u8)affinity;
69919         assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
69920         if( sqlite3Select(pParse, pExpr->x.pSelect, &dest) ){
69921           return 0;
69922         }
69923         pEList = pExpr->x.pSelect->pEList;
69924         if( ALWAYS(pEList!=0 && pEList->nExpr>0) ){ 
69925           keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
69926               pEList->a[0].pExpr);
69927         }
69928       }else if( ALWAYS(pExpr->x.pList!=0) ){
69929         /* Case 2:     expr IN (exprlist)
69930         **
69931         ** For each expression, build an index key from the evaluation and
69932         ** store it in the temporary table. If <expr> is a column, then use
69933         ** that columns affinity when building index keys. If <expr> is not
69934         ** a column, use numeric affinity.
69935         */
69936         int i;
69937         ExprList *pList = pExpr->x.pList;
69938         struct ExprList_item *pItem;
69939         int r1, r2, r3;
69940
69941         if( !affinity ){
69942           affinity = SQLITE_AFF_NONE;
69943         }
69944         keyInfo.aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
69945
69946         /* Loop through each expression in <exprlist>. */
69947         r1 = sqlite3GetTempReg(pParse);
69948         r2 = sqlite3GetTempReg(pParse);
69949         sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
69950         for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
69951           Expr *pE2 = pItem->pExpr;
69952           int iValToIns;
69953
69954           /* If the expression is not constant then we will need to
69955           ** disable the test that was generated above that makes sure
69956           ** this code only executes once.  Because for a non-constant
69957           ** expression we need to rerun this code each time.
69958           */
69959           if( testAddr && !sqlite3ExprIsConstant(pE2) ){
69960             sqlite3VdbeChangeToNoop(v, testAddr-1, 2);
69961             testAddr = 0;
69962           }
69963
69964           /* Evaluate the expression and insert it into the temp table */
69965           if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
69966             sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
69967           }else{
69968             r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
69969             if( isRowid ){
69970               sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
69971                                 sqlite3VdbeCurrentAddr(v)+2);
69972               sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
69973             }else{
69974               sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
69975               sqlite3ExprCacheAffinityChange(pParse, r3, 1);
69976               sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
69977             }
69978           }
69979         }
69980         sqlite3ReleaseTempReg(pParse, r1);
69981         sqlite3ReleaseTempReg(pParse, r2);
69982       }
69983       if( !isRowid ){
69984         sqlite3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO);
69985       }
69986       break;
69987     }
69988
69989     case TK_EXISTS:
69990     case TK_SELECT:
69991     default: {
69992       /* If this has to be a scalar SELECT.  Generate code to put the
69993       ** value of this select in a memory cell and record the number
69994       ** of the memory cell in iColumn.  If this is an EXISTS, write
69995       ** an integer 0 (not exists) or 1 (exists) into a memory cell
69996       ** and record that memory cell in iColumn.
69997       */
69998       Select *pSel;                         /* SELECT statement to encode */
69999       SelectDest dest;                      /* How to deal with SELECt result */
70000
70001       testcase( pExpr->op==TK_EXISTS );
70002       testcase( pExpr->op==TK_SELECT );
70003       assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
70004
70005       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
70006       pSel = pExpr->x.pSelect;
70007       sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
70008       if( pExpr->op==TK_SELECT ){
70009         dest.eDest = SRT_Mem;
70010         sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iParm);
70011         VdbeComment((v, "Init subquery result"));
70012       }else{
70013         dest.eDest = SRT_Exists;
70014         sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iParm);
70015         VdbeComment((v, "Init EXISTS result"));
70016       }
70017       sqlite3ExprDelete(pParse->db, pSel->pLimit);
70018       pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
70019                                   &sqlite3IntTokens[1]);
70020       if( sqlite3Select(pParse, pSel, &dest) ){
70021         return 0;
70022       }
70023       rReg = dest.iParm;
70024       ExprSetIrreducible(pExpr);
70025       break;
70026     }
70027   }
70028
70029   if( testAddr ){
70030     sqlite3VdbeJumpHere(v, testAddr-1);
70031   }
70032   sqlite3ExprCachePop(pParse, 1);
70033
70034   return rReg;
70035 }
70036 #endif /* SQLITE_OMIT_SUBQUERY */
70037
70038 #ifndef SQLITE_OMIT_SUBQUERY
70039 /*
70040 ** Generate code for an IN expression.
70041 **
70042 **      x IN (SELECT ...)
70043 **      x IN (value, value, ...)
70044 **
70045 ** The left-hand side (LHS) is a scalar expression.  The right-hand side (RHS)
70046 ** is an array of zero or more values.  The expression is true if the LHS is
70047 ** contained within the RHS.  The value of the expression is unknown (NULL)
70048 ** if the LHS is NULL or if the LHS is not contained within the RHS and the
70049 ** RHS contains one or more NULL values.
70050 **
70051 ** This routine generates code will jump to destIfFalse if the LHS is not 
70052 ** contained within the RHS.  If due to NULLs we cannot determine if the LHS
70053 ** is contained in the RHS then jump to destIfNull.  If the LHS is contained
70054 ** within the RHS then fall through.
70055 */
70056 static void sqlite3ExprCodeIN(
70057   Parse *pParse,        /* Parsing and code generating context */
70058   Expr *pExpr,          /* The IN expression */
70059   int destIfFalse,      /* Jump here if LHS is not contained in the RHS */
70060   int destIfNull        /* Jump here if the results are unknown due to NULLs */
70061 ){
70062   int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */
70063   char affinity;        /* Comparison affinity to use */
70064   int eType;            /* Type of the RHS */
70065   int r1;               /* Temporary use register */
70066   Vdbe *v;              /* Statement under construction */
70067
70068   /* Compute the RHS.   After this step, the table with cursor
70069   ** pExpr->iTable will contains the values that make up the RHS.
70070   */
70071   v = pParse->pVdbe;
70072   assert( v!=0 );       /* OOM detected prior to this routine */
70073   VdbeNoopComment((v, "begin IN expr"));
70074   eType = sqlite3FindInIndex(pParse, pExpr, &rRhsHasNull);
70075
70076   /* Figure out the affinity to use to create a key from the results
70077   ** of the expression. affinityStr stores a static string suitable for
70078   ** P4 of OP_MakeRecord.
70079   */
70080   affinity = comparisonAffinity(pExpr);
70081
70082   /* Code the LHS, the <expr> from "<expr> IN (...)".
70083   */
70084   sqlite3ExprCachePush(pParse);
70085   r1 = sqlite3GetTempReg(pParse);
70086   sqlite3ExprCode(pParse, pExpr->pLeft, r1);
70087
70088   /* If the LHS is NULL, then the result is either false or NULL depending
70089   ** on whether the RHS is empty or not, respectively.
70090   */
70091   if( destIfNull==destIfFalse ){
70092     /* Shortcut for the common case where the false and NULL outcomes are
70093     ** the same. */
70094     sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull);
70095   }else{
70096     int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1);
70097     sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
70098     sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
70099     sqlite3VdbeJumpHere(v, addr1);
70100   }
70101
70102   if( eType==IN_INDEX_ROWID ){
70103     /* In this case, the RHS is the ROWID of table b-tree
70104     */
70105     sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse);
70106     sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
70107   }else{
70108     /* In this case, the RHS is an index b-tree.
70109     */
70110     sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
70111
70112     /* If the set membership test fails, then the result of the 
70113     ** "x IN (...)" expression must be either 0 or NULL. If the set
70114     ** contains no NULL values, then the result is 0. If the set 
70115     ** contains one or more NULL values, then the result of the
70116     ** expression is also NULL.
70117     */
70118     if( rRhsHasNull==0 || destIfFalse==destIfNull ){
70119       /* This branch runs if it is known at compile time that the RHS
70120       ** cannot contain NULL values. This happens as the result
70121       ** of a "NOT NULL" constraint in the database schema.
70122       **
70123       ** Also run this branch if NULL is equivalent to FALSE
70124       ** for this particular IN operator.
70125       */
70126       sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
70127
70128     }else{
70129       /* In this branch, the RHS of the IN might contain a NULL and
70130       ** the presence of a NULL on the RHS makes a difference in the
70131       ** outcome.
70132       */
70133       int j1, j2, j3;
70134
70135       /* First check to see if the LHS is contained in the RHS.  If so,
70136       ** then the presence of NULLs in the RHS does not matter, so jump
70137       ** over all of the code that follows.
70138       */
70139       j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
70140
70141       /* Here we begin generating code that runs if the LHS is not
70142       ** contained within the RHS.  Generate additional code that
70143       ** tests the RHS for NULLs.  If the RHS contains a NULL then
70144       ** jump to destIfNull.  If there are no NULLs in the RHS then
70145       ** jump to destIfFalse.
70146       */
70147       j2 = sqlite3VdbeAddOp1(v, OP_NotNull, rRhsHasNull);
70148       j3 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, rRhsHasNull, 1);
70149       sqlite3VdbeAddOp2(v, OP_Integer, -1, rRhsHasNull);
70150       sqlite3VdbeJumpHere(v, j3);
70151       sqlite3VdbeAddOp2(v, OP_AddImm, rRhsHasNull, 1);
70152       sqlite3VdbeJumpHere(v, j2);
70153
70154       /* Jump to the appropriate target depending on whether or not
70155       ** the RHS contains a NULL
70156       */
70157       sqlite3VdbeAddOp2(v, OP_If, rRhsHasNull, destIfNull);
70158       sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
70159
70160       /* The OP_Found at the top of this branch jumps here when true, 
70161       ** causing the overall IN expression evaluation to fall through.
70162       */
70163       sqlite3VdbeJumpHere(v, j1);
70164     }
70165   }
70166   sqlite3ReleaseTempReg(pParse, r1);
70167   sqlite3ExprCachePop(pParse, 1);
70168   VdbeComment((v, "end IN expr"));
70169 }
70170 #endif /* SQLITE_OMIT_SUBQUERY */
70171
70172 /*
70173 ** Duplicate an 8-byte value
70174 */
70175 static char *dup8bytes(Vdbe *v, const char *in){
70176   char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
70177   if( out ){
70178     memcpy(out, in, 8);
70179   }
70180   return out;
70181 }
70182
70183 #ifndef SQLITE_OMIT_FLOATING_POINT
70184 /*
70185 ** Generate an instruction that will put the floating point
70186 ** value described by z[0..n-1] into register iMem.
70187 **
70188 ** The z[] string will probably not be zero-terminated.  But the 
70189 ** z[n] character is guaranteed to be something that does not look
70190 ** like the continuation of the number.
70191 */
70192 static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
70193   if( ALWAYS(z!=0) ){
70194     double value;
70195     char *zV;
70196     sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
70197     assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
70198     if( negateFlag ) value = -value;
70199     zV = dup8bytes(v, (char*)&value);
70200     sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
70201   }
70202 }
70203 #endif
70204
70205
70206 /*
70207 ** Generate an instruction that will put the integer describe by
70208 ** text z[0..n-1] into register iMem.
70209 **
70210 ** Expr.u.zToken is always UTF8 and zero-terminated.
70211 */
70212 static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
70213   Vdbe *v = pParse->pVdbe;
70214   if( pExpr->flags & EP_IntValue ){
70215     int i = pExpr->u.iValue;
70216     if( negFlag ) i = -i;
70217     sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
70218   }else{
70219     int c;
70220     i64 value;
70221     const char *z = pExpr->u.zToken;
70222     assert( z!=0 );
70223     c = sqlite3Atoi64(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
70224     if( c==0 || (c==2 && negFlag) ){
70225       char *zV;
70226       if( negFlag ){ value = -value; }
70227       zV = dup8bytes(v, (char*)&value);
70228       sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
70229     }else{
70230 #ifdef SQLITE_OMIT_FLOATING_POINT
70231       sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
70232 #else
70233       codeReal(v, z, negFlag, iMem);
70234 #endif
70235     }
70236   }
70237 }
70238
70239 /*
70240 ** Clear a cache entry.
70241 */
70242 static void cacheEntryClear(Parse *pParse, struct yColCache *p){
70243   if( p->tempReg ){
70244     if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
70245       pParse->aTempReg[pParse->nTempReg++] = p->iReg;
70246     }
70247     p->tempReg = 0;
70248   }
70249 }
70250
70251
70252 /*
70253 ** Record in the column cache that a particular column from a
70254 ** particular table is stored in a particular register.
70255 */
70256 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
70257   int i;
70258   int minLru;
70259   int idxLru;
70260   struct yColCache *p;
70261
70262   assert( iReg>0 );  /* Register numbers are always positive */
70263   assert( iCol>=-1 && iCol<32768 );  /* Finite column numbers */
70264
70265   /* The SQLITE_ColumnCache flag disables the column cache.  This is used
70266   ** for testing only - to verify that SQLite always gets the same answer
70267   ** with and without the column cache.
70268   */
70269   if( pParse->db->flags & SQLITE_ColumnCache ) return;
70270
70271   /* First replace any existing entry.
70272   **
70273   ** Actually, the way the column cache is currently used, we are guaranteed
70274   ** that the object will never already be in cache.  Verify this guarantee.
70275   */
70276 #ifndef NDEBUG
70277   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
70278 #if 0 /* This code wold remove the entry from the cache if it existed */
70279     if( p->iReg && p->iTable==iTab && p->iColumn==iCol ){
70280       cacheEntryClear(pParse, p);
70281       p->iLevel = pParse->iCacheLevel;
70282       p->iReg = iReg;
70283       p->lru = pParse->iCacheCnt++;
70284       return;
70285     }
70286 #endif
70287     assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
70288   }
70289 #endif
70290
70291   /* Find an empty slot and replace it */
70292   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
70293     if( p->iReg==0 ){
70294       p->iLevel = pParse->iCacheLevel;
70295       p->iTable = iTab;
70296       p->iColumn = iCol;
70297       p->iReg = iReg;
70298       p->tempReg = 0;
70299       p->lru = pParse->iCacheCnt++;
70300       return;
70301     }
70302   }
70303
70304   /* Replace the last recently used */
70305   minLru = 0x7fffffff;
70306   idxLru = -1;
70307   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
70308     if( p->lru<minLru ){
70309       idxLru = i;
70310       minLru = p->lru;
70311     }
70312   }
70313   if( ALWAYS(idxLru>=0) ){
70314     p = &pParse->aColCache[idxLru];
70315     p->iLevel = pParse->iCacheLevel;
70316     p->iTable = iTab;
70317     p->iColumn = iCol;
70318     p->iReg = iReg;
70319     p->tempReg = 0;
70320     p->lru = pParse->iCacheCnt++;
70321     return;
70322   }
70323 }
70324
70325 /*
70326 ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
70327 ** Purge the range of registers from the column cache.
70328 */
70329 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
70330   int i;
70331   int iLast = iReg + nReg - 1;
70332   struct yColCache *p;
70333   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
70334     int r = p->iReg;
70335     if( r>=iReg && r<=iLast ){
70336       cacheEntryClear(pParse, p);
70337       p->iReg = 0;
70338     }
70339   }
70340 }
70341
70342 /*
70343 ** Remember the current column cache context.  Any new entries added
70344 ** added to the column cache after this call are removed when the
70345 ** corresponding pop occurs.
70346 */
70347 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
70348   pParse->iCacheLevel++;
70349 }
70350
70351 /*
70352 ** Remove from the column cache any entries that were added since the
70353 ** the previous N Push operations.  In other words, restore the cache
70354 ** to the state it was in N Pushes ago.
70355 */
70356 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse, int N){
70357   int i;
70358   struct yColCache *p;
70359   assert( N>0 );
70360   assert( pParse->iCacheLevel>=N );
70361   pParse->iCacheLevel -= N;
70362   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
70363     if( p->iReg && p->iLevel>pParse->iCacheLevel ){
70364       cacheEntryClear(pParse, p);
70365       p->iReg = 0;
70366     }
70367   }
70368 }
70369
70370 /*
70371 ** When a cached column is reused, make sure that its register is
70372 ** no longer available as a temp register.  ticket #3879:  that same
70373 ** register might be in the cache in multiple places, so be sure to
70374 ** get them all.
70375 */
70376 static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
70377   int i;
70378   struct yColCache *p;
70379   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
70380     if( p->iReg==iReg ){
70381       p->tempReg = 0;
70382     }
70383   }
70384 }
70385
70386 /*
70387 ** Generate code to extract the value of the iCol-th column of a table.
70388 */
70389 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
70390   Vdbe *v,        /* The VDBE under construction */
70391   Table *pTab,    /* The table containing the value */
70392   int iTabCur,    /* The cursor for this table */
70393   int iCol,       /* Index of the column to extract */
70394   int regOut      /* Extract the valud into this register */
70395 ){
70396   if( iCol<0 || iCol==pTab->iPKey ){
70397     sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
70398   }else{
70399     int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
70400     sqlite3VdbeAddOp3(v, op, iTabCur, iCol, regOut);
70401   }
70402   if( iCol>=0 ){
70403     sqlite3ColumnDefault(v, pTab, iCol, regOut);
70404   }
70405 }
70406
70407 /*
70408 ** Generate code that will extract the iColumn-th column from
70409 ** table pTab and store the column value in a register.  An effort
70410 ** is made to store the column value in register iReg, but this is
70411 ** not guaranteed.  The location of the column value is returned.
70412 **
70413 ** There must be an open cursor to pTab in iTable when this routine
70414 ** is called.  If iColumn<0 then code is generated that extracts the rowid.
70415 */
70416 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
70417   Parse *pParse,   /* Parsing and code generating context */
70418   Table *pTab,     /* Description of the table we are reading from */
70419   int iColumn,     /* Index of the table column */
70420   int iTable,      /* The cursor pointing to the table */
70421   int iReg         /* Store results here */
70422 ){
70423   Vdbe *v = pParse->pVdbe;
70424   int i;
70425   struct yColCache *p;
70426
70427   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
70428     if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
70429       p->lru = pParse->iCacheCnt++;
70430       sqlite3ExprCachePinRegister(pParse, p->iReg);
70431       return p->iReg;
70432     }
70433   }  
70434   assert( v!=0 );
70435   sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
70436   sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
70437   return iReg;
70438 }
70439
70440 /*
70441 ** Clear all column cache entries.
70442 */
70443 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
70444   int i;
70445   struct yColCache *p;
70446
70447   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
70448     if( p->iReg ){
70449       cacheEntryClear(pParse, p);
70450       p->iReg = 0;
70451     }
70452   }
70453 }
70454
70455 /*
70456 ** Record the fact that an affinity change has occurred on iCount
70457 ** registers starting with iStart.
70458 */
70459 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
70460   sqlite3ExprCacheRemove(pParse, iStart, iCount);
70461 }
70462
70463 /*
70464 ** Generate code to move content from registers iFrom...iFrom+nReg-1
70465 ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
70466 */
70467 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
70468   int i;
70469   struct yColCache *p;
70470   if( NEVER(iFrom==iTo) ) return;
70471   sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
70472   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
70473     int x = p->iReg;
70474     if( x>=iFrom && x<iFrom+nReg ){
70475       p->iReg += iTo-iFrom;
70476     }
70477   }
70478 }
70479
70480 /*
70481 ** Generate code to copy content from registers iFrom...iFrom+nReg-1
70482 ** over to iTo..iTo+nReg-1.
70483 */
70484 SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, int iFrom, int iTo, int nReg){
70485   int i;
70486   if( NEVER(iFrom==iTo) ) return;
70487   for(i=0; i<nReg; i++){
70488     sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, iFrom+i, iTo+i);
70489   }
70490 }
70491
70492 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
70493 /*
70494 ** Return true if any register in the range iFrom..iTo (inclusive)
70495 ** is used as part of the column cache.
70496 **
70497 ** This routine is used within assert() and testcase() macros only
70498 ** and does not appear in a normal build.
70499 */
70500 static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
70501   int i;
70502   struct yColCache *p;
70503   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
70504     int r = p->iReg;
70505     if( r>=iFrom && r<=iTo ) return 1;    /*NO_TEST*/
70506   }
70507   return 0;
70508 }
70509 #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
70510
70511 /*
70512 ** Generate code into the current Vdbe to evaluate the given
70513 ** expression.  Attempt to store the results in register "target".
70514 ** Return the register where results are stored.
70515 **
70516 ** With this routine, there is no guarantee that results will
70517 ** be stored in target.  The result might be stored in some other
70518 ** register if it is convenient to do so.  The calling function
70519 ** must check the return code and move the results to the desired
70520 ** register.
70521 */
70522 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
70523   Vdbe *v = pParse->pVdbe;  /* The VM under construction */
70524   int op;                   /* The opcode being coded */
70525   int inReg = target;       /* Results stored in register inReg */
70526   int regFree1 = 0;         /* If non-zero free this temporary register */
70527   int regFree2 = 0;         /* If non-zero free this temporary register */
70528   int r1, r2, r3, r4;       /* Various register numbers */
70529   sqlite3 *db = pParse->db; /* The database connection */
70530
70531   assert( target>0 && target<=pParse->nMem );
70532   if( v==0 ){
70533     assert( pParse->db->mallocFailed );
70534     return 0;
70535   }
70536
70537   if( pExpr==0 ){
70538     op = TK_NULL;
70539   }else{
70540     op = pExpr->op;
70541   }
70542   switch( op ){
70543     case TK_AGG_COLUMN: {
70544       AggInfo *pAggInfo = pExpr->pAggInfo;
70545       struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
70546       if( !pAggInfo->directMode ){
70547         assert( pCol->iMem>0 );
70548         inReg = pCol->iMem;
70549         break;
70550       }else if( pAggInfo->useSortingIdx ){
70551         sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdx,
70552                               pCol->iSorterColumn, target);
70553         break;
70554       }
70555       /* Otherwise, fall thru into the TK_COLUMN case */
70556     }
70557     case TK_COLUMN: {
70558       if( pExpr->iTable<0 ){
70559         /* This only happens when coding check constraints */
70560         assert( pParse->ckBase>0 );
70561         inReg = pExpr->iColumn + pParse->ckBase;
70562       }else{
70563         inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
70564                                  pExpr->iColumn, pExpr->iTable, target);
70565       }
70566       break;
70567     }
70568     case TK_INTEGER: {
70569       codeInteger(pParse, pExpr, 0, target);
70570       break;
70571     }
70572 #ifndef SQLITE_OMIT_FLOATING_POINT
70573     case TK_FLOAT: {
70574       assert( !ExprHasProperty(pExpr, EP_IntValue) );
70575       codeReal(v, pExpr->u.zToken, 0, target);
70576       break;
70577     }
70578 #endif
70579     case TK_STRING: {
70580       assert( !ExprHasProperty(pExpr, EP_IntValue) );
70581       sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
70582       break;
70583     }
70584     case TK_NULL: {
70585       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
70586       break;
70587     }
70588 #ifndef SQLITE_OMIT_BLOB_LITERAL
70589     case TK_BLOB: {
70590       int n;
70591       const char *z;
70592       char *zBlob;
70593       assert( !ExprHasProperty(pExpr, EP_IntValue) );
70594       assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
70595       assert( pExpr->u.zToken[1]=='\'' );
70596       z = &pExpr->u.zToken[2];
70597       n = sqlite3Strlen30(z) - 1;
70598       assert( z[n]=='\'' );
70599       zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
70600       sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
70601       break;
70602     }
70603 #endif
70604     case TK_VARIABLE: {
70605       assert( !ExprHasProperty(pExpr, EP_IntValue) );
70606       assert( pExpr->u.zToken!=0 );
70607       assert( pExpr->u.zToken[0]!=0 );
70608       sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
70609       if( pExpr->u.zToken[1]!=0 ){
70610         sqlite3VdbeChangeP4(v, -1, pExpr->u.zToken, 0);
70611       }
70612       break;
70613     }
70614     case TK_REGISTER: {
70615       inReg = pExpr->iTable;
70616       break;
70617     }
70618     case TK_AS: {
70619       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
70620       break;
70621     }
70622 #ifndef SQLITE_OMIT_CAST
70623     case TK_CAST: {
70624       /* Expressions of the form:   CAST(pLeft AS token) */
70625       int aff, to_op;
70626       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
70627       assert( !ExprHasProperty(pExpr, EP_IntValue) );
70628       aff = sqlite3AffinityType(pExpr->u.zToken);
70629       to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
70630       assert( to_op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );
70631       assert( to_op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );
70632       assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
70633       assert( to_op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );
70634       assert( to_op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );
70635       testcase( to_op==OP_ToText );
70636       testcase( to_op==OP_ToBlob );
70637       testcase( to_op==OP_ToNumeric );
70638       testcase( to_op==OP_ToInt );
70639       testcase( to_op==OP_ToReal );
70640       if( inReg!=target ){
70641         sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
70642         inReg = target;
70643       }
70644       sqlite3VdbeAddOp1(v, to_op, inReg);
70645       testcase( usedAsColumnCache(pParse, inReg, inReg) );
70646       sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
70647       break;
70648     }
70649 #endif /* SQLITE_OMIT_CAST */
70650     case TK_LT:
70651     case TK_LE:
70652     case TK_GT:
70653     case TK_GE:
70654     case TK_NE:
70655     case TK_EQ: {
70656       assert( TK_LT==OP_Lt );
70657       assert( TK_LE==OP_Le );
70658       assert( TK_GT==OP_Gt );
70659       assert( TK_GE==OP_Ge );
70660       assert( TK_EQ==OP_Eq );
70661       assert( TK_NE==OP_Ne );
70662       testcase( op==TK_LT );
70663       testcase( op==TK_LE );
70664       testcase( op==TK_GT );
70665       testcase( op==TK_GE );
70666       testcase( op==TK_EQ );
70667       testcase( op==TK_NE );
70668       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
70669       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
70670       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
70671                   r1, r2, inReg, SQLITE_STOREP2);
70672       testcase( regFree1==0 );
70673       testcase( regFree2==0 );
70674       break;
70675     }
70676     case TK_IS:
70677     case TK_ISNOT: {
70678       testcase( op==TK_IS );
70679       testcase( op==TK_ISNOT );
70680       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
70681       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
70682       op = (op==TK_IS) ? TK_EQ : TK_NE;
70683       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
70684                   r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
70685       testcase( regFree1==0 );
70686       testcase( regFree2==0 );
70687       break;
70688     }
70689     case TK_AND:
70690     case TK_OR:
70691     case TK_PLUS:
70692     case TK_STAR:
70693     case TK_MINUS:
70694     case TK_REM:
70695     case TK_BITAND:
70696     case TK_BITOR:
70697     case TK_SLASH:
70698     case TK_LSHIFT:
70699     case TK_RSHIFT: 
70700     case TK_CONCAT: {
70701       assert( TK_AND==OP_And );
70702       assert( TK_OR==OP_Or );
70703       assert( TK_PLUS==OP_Add );
70704       assert( TK_MINUS==OP_Subtract );
70705       assert( TK_REM==OP_Remainder );
70706       assert( TK_BITAND==OP_BitAnd );
70707       assert( TK_BITOR==OP_BitOr );
70708       assert( TK_SLASH==OP_Divide );
70709       assert( TK_LSHIFT==OP_ShiftLeft );
70710       assert( TK_RSHIFT==OP_ShiftRight );
70711       assert( TK_CONCAT==OP_Concat );
70712       testcase( op==TK_AND );
70713       testcase( op==TK_OR );
70714       testcase( op==TK_PLUS );
70715       testcase( op==TK_MINUS );
70716       testcase( op==TK_REM );
70717       testcase( op==TK_BITAND );
70718       testcase( op==TK_BITOR );
70719       testcase( op==TK_SLASH );
70720       testcase( op==TK_LSHIFT );
70721       testcase( op==TK_RSHIFT );
70722       testcase( op==TK_CONCAT );
70723       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
70724       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
70725       sqlite3VdbeAddOp3(v, op, r2, r1, target);
70726       testcase( regFree1==0 );
70727       testcase( regFree2==0 );
70728       break;
70729     }
70730     case TK_UMINUS: {
70731       Expr *pLeft = pExpr->pLeft;
70732       assert( pLeft );
70733       if( pLeft->op==TK_INTEGER ){
70734         codeInteger(pParse, pLeft, 1, target);
70735 #ifndef SQLITE_OMIT_FLOATING_POINT
70736       }else if( pLeft->op==TK_FLOAT ){
70737         assert( !ExprHasProperty(pExpr, EP_IntValue) );
70738         codeReal(v, pLeft->u.zToken, 1, target);
70739 #endif
70740       }else{
70741         regFree1 = r1 = sqlite3GetTempReg(pParse);
70742         sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
70743         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
70744         sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
70745         testcase( regFree2==0 );
70746       }
70747       inReg = target;
70748       break;
70749     }
70750     case TK_BITNOT:
70751     case TK_NOT: {
70752       assert( TK_BITNOT==OP_BitNot );
70753       assert( TK_NOT==OP_Not );
70754       testcase( op==TK_BITNOT );
70755       testcase( op==TK_NOT );
70756       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
70757       testcase( regFree1==0 );
70758       inReg = target;
70759       sqlite3VdbeAddOp2(v, op, r1, inReg);
70760       break;
70761     }
70762     case TK_ISNULL:
70763     case TK_NOTNULL: {
70764       int addr;
70765       assert( TK_ISNULL==OP_IsNull );
70766       assert( TK_NOTNULL==OP_NotNull );
70767       testcase( op==TK_ISNULL );
70768       testcase( op==TK_NOTNULL );
70769       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
70770       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
70771       testcase( regFree1==0 );
70772       addr = sqlite3VdbeAddOp1(v, op, r1);
70773       sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
70774       sqlite3VdbeJumpHere(v, addr);
70775       break;
70776     }
70777     case TK_AGG_FUNCTION: {
70778       AggInfo *pInfo = pExpr->pAggInfo;
70779       if( pInfo==0 ){
70780         assert( !ExprHasProperty(pExpr, EP_IntValue) );
70781         sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
70782       }else{
70783         inReg = pInfo->aFunc[pExpr->iAgg].iMem;
70784       }
70785       break;
70786     }
70787     case TK_CONST_FUNC:
70788     case TK_FUNCTION: {
70789       ExprList *pFarg;       /* List of function arguments */
70790       int nFarg;             /* Number of function arguments */
70791       FuncDef *pDef;         /* The function definition object */
70792       int nId;               /* Length of the function name in bytes */
70793       const char *zId;       /* The function name */
70794       int constMask = 0;     /* Mask of function arguments that are constant */
70795       int i;                 /* Loop counter */
70796       u8 enc = ENC(db);      /* The text encoding used by this database */
70797       CollSeq *pColl = 0;    /* A collating sequence */
70798
70799       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
70800       testcase( op==TK_CONST_FUNC );
70801       testcase( op==TK_FUNCTION );
70802       if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
70803         pFarg = 0;
70804       }else{
70805         pFarg = pExpr->x.pList;
70806       }
70807       nFarg = pFarg ? pFarg->nExpr : 0;
70808       assert( !ExprHasProperty(pExpr, EP_IntValue) );
70809       zId = pExpr->u.zToken;
70810       nId = sqlite3Strlen30(zId);
70811       pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
70812       if( pDef==0 ){
70813         sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
70814         break;
70815       }
70816
70817       /* Attempt a direct implementation of the built-in COALESCE() and
70818       ** IFNULL() functions.  This avoids unnecessary evalation of
70819       ** arguments past the first non-NULL argument.
70820       */
70821       if( pDef->flags & SQLITE_FUNC_COALESCE ){
70822         int endCoalesce = sqlite3VdbeMakeLabel(v);
70823         assert( nFarg>=2 );
70824         sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
70825         for(i=1; i<nFarg; i++){
70826           sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
70827           sqlite3ExprCacheRemove(pParse, target, 1);
70828           sqlite3ExprCachePush(pParse);
70829           sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
70830           sqlite3ExprCachePop(pParse, 1);
70831         }
70832         sqlite3VdbeResolveLabel(v, endCoalesce);
70833         break;
70834       }
70835
70836
70837       if( pFarg ){
70838         r1 = sqlite3GetTempRange(pParse, nFarg);
70839         sqlite3ExprCachePush(pParse);     /* Ticket 2ea2425d34be */
70840         sqlite3ExprCodeExprList(pParse, pFarg, r1, 1);
70841         sqlite3ExprCachePop(pParse, 1);   /* Ticket 2ea2425d34be */
70842       }else{
70843         r1 = 0;
70844       }
70845 #ifndef SQLITE_OMIT_VIRTUALTABLE
70846       /* Possibly overload the function if the first argument is
70847       ** a virtual table column.
70848       **
70849       ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
70850       ** second argument, not the first, as the argument to test to
70851       ** see if it is a column in a virtual table.  This is done because
70852       ** the left operand of infix functions (the operand we want to
70853       ** control overloading) ends up as the second argument to the
70854       ** function.  The expression "A glob B" is equivalent to 
70855       ** "glob(B,A).  We want to use the A in "A glob B" to test
70856       ** for function overloading.  But we use the B term in "glob(B,A)".
70857       */
70858       if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
70859         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
70860       }else if( nFarg>0 ){
70861         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
70862       }
70863 #endif
70864       for(i=0; i<nFarg; i++){
70865         if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
70866           constMask |= (1<<i);
70867         }
70868         if( (pDef->flags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
70869           pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
70870         }
70871       }
70872       if( pDef->flags & SQLITE_FUNC_NEEDCOLL ){
70873         if( !pColl ) pColl = db->pDfltColl; 
70874         sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
70875       }
70876       sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
70877                         (char*)pDef, P4_FUNCDEF);
70878       sqlite3VdbeChangeP5(v, (u8)nFarg);
70879       if( nFarg ){
70880         sqlite3ReleaseTempRange(pParse, r1, nFarg);
70881       }
70882       break;
70883     }
70884 #ifndef SQLITE_OMIT_SUBQUERY
70885     case TK_EXISTS:
70886     case TK_SELECT: {
70887       testcase( op==TK_EXISTS );
70888       testcase( op==TK_SELECT );
70889       inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
70890       break;
70891     }
70892     case TK_IN: {
70893       int destIfFalse = sqlite3VdbeMakeLabel(v);
70894       int destIfNull = sqlite3VdbeMakeLabel(v);
70895       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
70896       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
70897       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
70898       sqlite3VdbeResolveLabel(v, destIfFalse);
70899       sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
70900       sqlite3VdbeResolveLabel(v, destIfNull);
70901       break;
70902     }
70903 #endif /* SQLITE_OMIT_SUBQUERY */
70904
70905
70906     /*
70907     **    x BETWEEN y AND z
70908     **
70909     ** This is equivalent to
70910     **
70911     **    x>=y AND x<=z
70912     **
70913     ** X is stored in pExpr->pLeft.
70914     ** Y is stored in pExpr->pList->a[0].pExpr.
70915     ** Z is stored in pExpr->pList->a[1].pExpr.
70916     */
70917     case TK_BETWEEN: {
70918       Expr *pLeft = pExpr->pLeft;
70919       struct ExprList_item *pLItem = pExpr->x.pList->a;
70920       Expr *pRight = pLItem->pExpr;
70921
70922       r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
70923       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
70924       testcase( regFree1==0 );
70925       testcase( regFree2==0 );
70926       r3 = sqlite3GetTempReg(pParse);
70927       r4 = sqlite3GetTempReg(pParse);
70928       codeCompare(pParse, pLeft, pRight, OP_Ge,
70929                   r1, r2, r3, SQLITE_STOREP2);
70930       pLItem++;
70931       pRight = pLItem->pExpr;
70932       sqlite3ReleaseTempReg(pParse, regFree2);
70933       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
70934       testcase( regFree2==0 );
70935       codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
70936       sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
70937       sqlite3ReleaseTempReg(pParse, r3);
70938       sqlite3ReleaseTempReg(pParse, r4);
70939       break;
70940     }
70941     case TK_UPLUS: {
70942       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
70943       break;
70944     }
70945
70946     case TK_TRIGGER: {
70947       /* If the opcode is TK_TRIGGER, then the expression is a reference
70948       ** to a column in the new.* or old.* pseudo-tables available to
70949       ** trigger programs. In this case Expr.iTable is set to 1 for the
70950       ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
70951       ** is set to the column of the pseudo-table to read, or to -1 to
70952       ** read the rowid field.
70953       **
70954       ** The expression is implemented using an OP_Param opcode. The p1
70955       ** parameter is set to 0 for an old.rowid reference, or to (i+1)
70956       ** to reference another column of the old.* pseudo-table, where 
70957       ** i is the index of the column. For a new.rowid reference, p1 is
70958       ** set to (n+1), where n is the number of columns in each pseudo-table.
70959       ** For a reference to any other column in the new.* pseudo-table, p1
70960       ** is set to (n+2+i), where n and i are as defined previously. For
70961       ** example, if the table on which triggers are being fired is
70962       ** declared as:
70963       **
70964       **   CREATE TABLE t1(a, b);
70965       **
70966       ** Then p1 is interpreted as follows:
70967       **
70968       **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
70969       **   p1==1   ->    old.a         p1==4   ->    new.a
70970       **   p1==2   ->    old.b         p1==5   ->    new.b       
70971       */
70972       Table *pTab = pExpr->pTab;
70973       int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
70974
70975       assert( pExpr->iTable==0 || pExpr->iTable==1 );
70976       assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
70977       assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
70978       assert( p1>=0 && p1<(pTab->nCol*2+2) );
70979
70980       sqlite3VdbeAddOp2(v, OP_Param, p1, target);
70981       VdbeComment((v, "%s.%s -> $%d",
70982         (pExpr->iTable ? "new" : "old"),
70983         (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
70984         target
70985       ));
70986
70987 #ifndef SQLITE_OMIT_FLOATING_POINT
70988       /* If the column has REAL affinity, it may currently be stored as an
70989       ** integer. Use OP_RealAffinity to make sure it is really real.  */
70990       if( pExpr->iColumn>=0 
70991        && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
70992       ){
70993         sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
70994       }
70995 #endif
70996       break;
70997     }
70998
70999
71000     /*
71001     ** Form A:
71002     **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
71003     **
71004     ** Form B:
71005     **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
71006     **
71007     ** Form A is can be transformed into the equivalent form B as follows:
71008     **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
71009     **        WHEN x=eN THEN rN ELSE y END
71010     **
71011     ** X (if it exists) is in pExpr->pLeft.
71012     ** Y is in pExpr->pRight.  The Y is also optional.  If there is no
71013     ** ELSE clause and no other term matches, then the result of the
71014     ** exprssion is NULL.
71015     ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
71016     **
71017     ** The result of the expression is the Ri for the first matching Ei,
71018     ** or if there is no matching Ei, the ELSE term Y, or if there is
71019     ** no ELSE term, NULL.
71020     */
71021     default: assert( op==TK_CASE ); {
71022       int endLabel;                     /* GOTO label for end of CASE stmt */
71023       int nextCase;                     /* GOTO label for next WHEN clause */
71024       int nExpr;                        /* 2x number of WHEN terms */
71025       int i;                            /* Loop counter */
71026       ExprList *pEList;                 /* List of WHEN terms */
71027       struct ExprList_item *aListelem;  /* Array of WHEN terms */
71028       Expr opCompare;                   /* The X==Ei expression */
71029       Expr cacheX;                      /* Cached expression X */
71030       Expr *pX;                         /* The X expression */
71031       Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
71032       VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
71033
71034       assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
71035       assert((pExpr->x.pList->nExpr % 2) == 0);
71036       assert(pExpr->x.pList->nExpr > 0);
71037       pEList = pExpr->x.pList;
71038       aListelem = pEList->a;
71039       nExpr = pEList->nExpr;
71040       endLabel = sqlite3VdbeMakeLabel(v);
71041       if( (pX = pExpr->pLeft)!=0 ){
71042         cacheX = *pX;
71043         testcase( pX->op==TK_COLUMN );
71044         testcase( pX->op==TK_REGISTER );
71045         cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, &regFree1);
71046         testcase( regFree1==0 );
71047         cacheX.op = TK_REGISTER;
71048         opCompare.op = TK_EQ;
71049         opCompare.pLeft = &cacheX;
71050         pTest = &opCompare;
71051         /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
71052         ** The value in regFree1 might get SCopy-ed into the file result.
71053         ** So make sure that the regFree1 register is not reused for other
71054         ** purposes and possibly overwritten.  */
71055         regFree1 = 0;
71056       }
71057       for(i=0; i<nExpr; i=i+2){
71058         sqlite3ExprCachePush(pParse);
71059         if( pX ){
71060           assert( pTest!=0 );
71061           opCompare.pRight = aListelem[i].pExpr;
71062         }else{
71063           pTest = aListelem[i].pExpr;
71064         }
71065         nextCase = sqlite3VdbeMakeLabel(v);
71066         testcase( pTest->op==TK_COLUMN );
71067         sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
71068         testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
71069         testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
71070         sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
71071         sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
71072         sqlite3ExprCachePop(pParse, 1);
71073         sqlite3VdbeResolveLabel(v, nextCase);
71074       }
71075       if( pExpr->pRight ){
71076         sqlite3ExprCachePush(pParse);
71077         sqlite3ExprCode(pParse, pExpr->pRight, target);
71078         sqlite3ExprCachePop(pParse, 1);
71079       }else{
71080         sqlite3VdbeAddOp2(v, OP_Null, 0, target);
71081       }
71082       assert( db->mallocFailed || pParse->nErr>0 
71083            || pParse->iCacheLevel==iCacheLevel );
71084       sqlite3VdbeResolveLabel(v, endLabel);
71085       break;
71086     }
71087 #ifndef SQLITE_OMIT_TRIGGER
71088     case TK_RAISE: {
71089       assert( pExpr->affinity==OE_Rollback 
71090            || pExpr->affinity==OE_Abort
71091            || pExpr->affinity==OE_Fail
71092            || pExpr->affinity==OE_Ignore
71093       );
71094       if( !pParse->pTriggerTab ){
71095         sqlite3ErrorMsg(pParse,
71096                        "RAISE() may only be used within a trigger-program");
71097         return 0;
71098       }
71099       if( pExpr->affinity==OE_Abort ){
71100         sqlite3MayAbort(pParse);
71101       }
71102       assert( !ExprHasProperty(pExpr, EP_IntValue) );
71103       if( pExpr->affinity==OE_Ignore ){
71104         sqlite3VdbeAddOp4(
71105             v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
71106       }else{
71107         sqlite3HaltConstraint(pParse, pExpr->affinity, pExpr->u.zToken, 0);
71108       }
71109
71110       break;
71111     }
71112 #endif
71113   }
71114   sqlite3ReleaseTempReg(pParse, regFree1);
71115   sqlite3ReleaseTempReg(pParse, regFree2);
71116   return inReg;
71117 }
71118
71119 /*
71120 ** Generate code to evaluate an expression and store the results
71121 ** into a register.  Return the register number where the results
71122 ** are stored.
71123 **
71124 ** If the register is a temporary register that can be deallocated,
71125 ** then write its number into *pReg.  If the result register is not
71126 ** a temporary, then set *pReg to zero.
71127 */
71128 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
71129   int r1 = sqlite3GetTempReg(pParse);
71130   int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
71131   if( r2==r1 ){
71132     *pReg = r1;
71133   }else{
71134     sqlite3ReleaseTempReg(pParse, r1);
71135     *pReg = 0;
71136   }
71137   return r2;
71138 }
71139
71140 /*
71141 ** Generate code that will evaluate expression pExpr and store the
71142 ** results in register target.  The results are guaranteed to appear
71143 ** in register target.
71144 */
71145 SQLITE_PRIVATE int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
71146   int inReg;
71147
71148   assert( target>0 && target<=pParse->nMem );
71149   if( pExpr && pExpr->op==TK_REGISTER ){
71150     sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
71151   }else{
71152     inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
71153     assert( pParse->pVdbe || pParse->db->mallocFailed );
71154     if( inReg!=target && pParse->pVdbe ){
71155       sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
71156     }
71157   }
71158   return target;
71159 }
71160
71161 /*
71162 ** Generate code that evalutes the given expression and puts the result
71163 ** in register target.
71164 **
71165 ** Also make a copy of the expression results into another "cache" register
71166 ** and modify the expression so that the next time it is evaluated,
71167 ** the result is a copy of the cache register.
71168 **
71169 ** This routine is used for expressions that are used multiple 
71170 ** times.  They are evaluated once and the results of the expression
71171 ** are reused.
71172 */
71173 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
71174   Vdbe *v = pParse->pVdbe;
71175   int inReg;
71176   inReg = sqlite3ExprCode(pParse, pExpr, target);
71177   assert( target>0 );
71178   /* This routine is called for terms to INSERT or UPDATE.  And the only
71179   ** other place where expressions can be converted into TK_REGISTER is
71180   ** in WHERE clause processing.  So as currently implemented, there is
71181   ** no way for a TK_REGISTER to exist here.  But it seems prudent to
71182   ** keep the ALWAYS() in case the conditions above change with future
71183   ** modifications or enhancements. */
71184   if( ALWAYS(pExpr->op!=TK_REGISTER) ){  
71185     int iMem;
71186     iMem = ++pParse->nMem;
71187     sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
71188     pExpr->iTable = iMem;
71189     pExpr->op2 = pExpr->op;
71190     pExpr->op = TK_REGISTER;
71191   }
71192   return inReg;
71193 }
71194
71195 /*
71196 ** Return TRUE if pExpr is an constant expression that is appropriate
71197 ** for factoring out of a loop.  Appropriate expressions are:
71198 **
71199 **    *  Any expression that evaluates to two or more opcodes.
71200 **
71201 **    *  Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null, 
71202 **       or OP_Variable that does not need to be placed in a 
71203 **       specific register.
71204 **
71205 ** There is no point in factoring out single-instruction constant
71206 ** expressions that need to be placed in a particular register.  
71207 ** We could factor them out, but then we would end up adding an
71208 ** OP_SCopy instruction to move the value into the correct register
71209 ** later.  We might as well just use the original instruction and
71210 ** avoid the OP_SCopy.
71211 */
71212 static int isAppropriateForFactoring(Expr *p){
71213   if( !sqlite3ExprIsConstantNotJoin(p) ){
71214     return 0;  /* Only constant expressions are appropriate for factoring */
71215   }
71216   if( (p->flags & EP_FixedDest)==0 ){
71217     return 1;  /* Any constant without a fixed destination is appropriate */
71218   }
71219   while( p->op==TK_UPLUS ) p = p->pLeft;
71220   switch( p->op ){
71221 #ifndef SQLITE_OMIT_BLOB_LITERAL
71222     case TK_BLOB:
71223 #endif
71224     case TK_VARIABLE:
71225     case TK_INTEGER:
71226     case TK_FLOAT:
71227     case TK_NULL:
71228     case TK_STRING: {
71229       testcase( p->op==TK_BLOB );
71230       testcase( p->op==TK_VARIABLE );
71231       testcase( p->op==TK_INTEGER );
71232       testcase( p->op==TK_FLOAT );
71233       testcase( p->op==TK_NULL );
71234       testcase( p->op==TK_STRING );
71235       /* Single-instruction constants with a fixed destination are
71236       ** better done in-line.  If we factor them, they will just end
71237       ** up generating an OP_SCopy to move the value to the destination
71238       ** register. */
71239       return 0;
71240     }
71241     case TK_UMINUS: {
71242       if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
71243         return 0;
71244       }
71245       break;
71246     }
71247     default: {
71248       break;
71249     }
71250   }
71251   return 1;
71252 }
71253
71254 /*
71255 ** If pExpr is a constant expression that is appropriate for
71256 ** factoring out of a loop, then evaluate the expression
71257 ** into a register and convert the expression into a TK_REGISTER
71258 ** expression.
71259 */
71260 static int evalConstExpr(Walker *pWalker, Expr *pExpr){
71261   Parse *pParse = pWalker->pParse;
71262   switch( pExpr->op ){
71263     case TK_IN:
71264     case TK_REGISTER: {
71265       return WRC_Prune;
71266     }
71267     case TK_FUNCTION:
71268     case TK_AGG_FUNCTION:
71269     case TK_CONST_FUNC: {
71270       /* The arguments to a function have a fixed destination.
71271       ** Mark them this way to avoid generated unneeded OP_SCopy
71272       ** instructions. 
71273       */
71274       ExprList *pList = pExpr->x.pList;
71275       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
71276       if( pList ){
71277         int i = pList->nExpr;
71278         struct ExprList_item *pItem = pList->a;
71279         for(; i>0; i--, pItem++){
71280           if( ALWAYS(pItem->pExpr) ) pItem->pExpr->flags |= EP_FixedDest;
71281         }
71282       }
71283       break;
71284     }
71285   }
71286   if( isAppropriateForFactoring(pExpr) ){
71287     int r1 = ++pParse->nMem;
71288     int r2;
71289     r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
71290     if( NEVER(r1!=r2) ) sqlite3ReleaseTempReg(pParse, r1);
71291     pExpr->op2 = pExpr->op;
71292     pExpr->op = TK_REGISTER;
71293     pExpr->iTable = r2;
71294     return WRC_Prune;
71295   }
71296   return WRC_Continue;
71297 }
71298
71299 /*
71300 ** Preevaluate constant subexpressions within pExpr and store the
71301 ** results in registers.  Modify pExpr so that the constant subexpresions
71302 ** are TK_REGISTER opcodes that refer to the precomputed values.
71303 */
71304 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
71305   Walker w;
71306   w.xExprCallback = evalConstExpr;
71307   w.xSelectCallback = 0;
71308   w.pParse = pParse;
71309   sqlite3WalkExpr(&w, pExpr);
71310 }
71311
71312
71313 /*
71314 ** Generate code that pushes the value of every element of the given
71315 ** expression list into a sequence of registers beginning at target.
71316 **
71317 ** Return the number of elements evaluated.
71318 */
71319 SQLITE_PRIVATE int sqlite3ExprCodeExprList(
71320   Parse *pParse,     /* Parsing context */
71321   ExprList *pList,   /* The expression list to be coded */
71322   int target,        /* Where to write results */
71323   int doHardCopy     /* Make a hard copy of every element */
71324 ){
71325   struct ExprList_item *pItem;
71326   int i, n;
71327   assert( pList!=0 );
71328   assert( target>0 );
71329   assert( pParse->pVdbe!=0 );  /* Never gets this far otherwise */
71330   n = pList->nExpr;
71331   for(pItem=pList->a, i=0; i<n; i++, pItem++){
71332     Expr *pExpr = pItem->pExpr;
71333     int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
71334     if( inReg!=target+i ){
71335       sqlite3VdbeAddOp2(pParse->pVdbe, doHardCopy ? OP_Copy : OP_SCopy,
71336                         inReg, target+i);
71337     }
71338   }
71339   return n;
71340 }
71341
71342 /*
71343 ** Generate code for a BETWEEN operator.
71344 **
71345 **    x BETWEEN y AND z
71346 **
71347 ** The above is equivalent to 
71348 **
71349 **    x>=y AND x<=z
71350 **
71351 ** Code it as such, taking care to do the common subexpression
71352 ** elementation of x.
71353 */
71354 static void exprCodeBetween(
71355   Parse *pParse,    /* Parsing and code generating context */
71356   Expr *pExpr,      /* The BETWEEN expression */
71357   int dest,         /* Jump here if the jump is taken */
71358   int jumpIfTrue,   /* Take the jump if the BETWEEN is true */
71359   int jumpIfNull    /* Take the jump if the BETWEEN is NULL */
71360 ){
71361   Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */
71362   Expr compLeft;    /* The  x>=y  term */
71363   Expr compRight;   /* The  x<=z  term */
71364   Expr exprX;       /* The  x  subexpression */
71365   int regFree1 = 0; /* Temporary use register */
71366
71367   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
71368   exprX = *pExpr->pLeft;
71369   exprAnd.op = TK_AND;
71370   exprAnd.pLeft = &compLeft;
71371   exprAnd.pRight = &compRight;
71372   compLeft.op = TK_GE;
71373   compLeft.pLeft = &exprX;
71374   compLeft.pRight = pExpr->x.pList->a[0].pExpr;
71375   compRight.op = TK_LE;
71376   compRight.pLeft = &exprX;
71377   compRight.pRight = pExpr->x.pList->a[1].pExpr;
71378   exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
71379   exprX.op = TK_REGISTER;
71380   if( jumpIfTrue ){
71381     sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
71382   }else{
71383     sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
71384   }
71385   sqlite3ReleaseTempReg(pParse, regFree1);
71386
71387   /* Ensure adequate test coverage */
71388   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
71389   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
71390   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
71391   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
71392   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
71393   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
71394   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
71395   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
71396 }
71397
71398 /*
71399 ** Generate code for a boolean expression such that a jump is made
71400 ** to the label "dest" if the expression is true but execution
71401 ** continues straight thru if the expression is false.
71402 **
71403 ** If the expression evaluates to NULL (neither true nor false), then
71404 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
71405 **
71406 ** This code depends on the fact that certain token values (ex: TK_EQ)
71407 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
71408 ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
71409 ** the make process cause these values to align.  Assert()s in the code
71410 ** below verify that the numbers are aligned correctly.
71411 */
71412 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
71413   Vdbe *v = pParse->pVdbe;
71414   int op = 0;
71415   int regFree1 = 0;
71416   int regFree2 = 0;
71417   int r1, r2;
71418
71419   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
71420   if( NEVER(v==0) )     return;  /* Existance of VDBE checked by caller */
71421   if( NEVER(pExpr==0) ) return;  /* No way this can happen */
71422   op = pExpr->op;
71423   switch( op ){
71424     case TK_AND: {
71425       int d2 = sqlite3VdbeMakeLabel(v);
71426       testcase( jumpIfNull==0 );
71427       sqlite3ExprCachePush(pParse);
71428       sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
71429       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
71430       sqlite3VdbeResolveLabel(v, d2);
71431       sqlite3ExprCachePop(pParse, 1);
71432       break;
71433     }
71434     case TK_OR: {
71435       testcase( jumpIfNull==0 );
71436       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
71437       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
71438       break;
71439     }
71440     case TK_NOT: {
71441       testcase( jumpIfNull==0 );
71442       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
71443       break;
71444     }
71445     case TK_LT:
71446     case TK_LE:
71447     case TK_GT:
71448     case TK_GE:
71449     case TK_NE:
71450     case TK_EQ: {
71451       assert( TK_LT==OP_Lt );
71452       assert( TK_LE==OP_Le );
71453       assert( TK_GT==OP_Gt );
71454       assert( TK_GE==OP_Ge );
71455       assert( TK_EQ==OP_Eq );
71456       assert( TK_NE==OP_Ne );
71457       testcase( op==TK_LT );
71458       testcase( op==TK_LE );
71459       testcase( op==TK_GT );
71460       testcase( op==TK_GE );
71461       testcase( op==TK_EQ );
71462       testcase( op==TK_NE );
71463       testcase( jumpIfNull==0 );
71464       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
71465       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
71466       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
71467                   r1, r2, dest, jumpIfNull);
71468       testcase( regFree1==0 );
71469       testcase( regFree2==0 );
71470       break;
71471     }
71472     case TK_IS:
71473     case TK_ISNOT: {
71474       testcase( op==TK_IS );
71475       testcase( op==TK_ISNOT );
71476       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
71477       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
71478       op = (op==TK_IS) ? TK_EQ : TK_NE;
71479       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
71480                   r1, r2, dest, SQLITE_NULLEQ);
71481       testcase( regFree1==0 );
71482       testcase( regFree2==0 );
71483       break;
71484     }
71485     case TK_ISNULL:
71486     case TK_NOTNULL: {
71487       assert( TK_ISNULL==OP_IsNull );
71488       assert( TK_NOTNULL==OP_NotNull );
71489       testcase( op==TK_ISNULL );
71490       testcase( op==TK_NOTNULL );
71491       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
71492       sqlite3VdbeAddOp2(v, op, r1, dest);
71493       testcase( regFree1==0 );
71494       break;
71495     }
71496     case TK_BETWEEN: {
71497       testcase( jumpIfNull==0 );
71498       exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
71499       break;
71500     }
71501     case TK_IN: {
71502       int destIfFalse = sqlite3VdbeMakeLabel(v);
71503       int destIfNull = jumpIfNull ? dest : destIfFalse;
71504       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
71505       sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
71506       sqlite3VdbeResolveLabel(v, destIfFalse);
71507       break;
71508     }
71509     default: {
71510       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
71511       sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
71512       testcase( regFree1==0 );
71513       testcase( jumpIfNull==0 );
71514       break;
71515     }
71516   }
71517   sqlite3ReleaseTempReg(pParse, regFree1);
71518   sqlite3ReleaseTempReg(pParse, regFree2);  
71519 }
71520
71521 /*
71522 ** Generate code for a boolean expression such that a jump is made
71523 ** to the label "dest" if the expression is false but execution
71524 ** continues straight thru if the expression is true.
71525 **
71526 ** If the expression evaluates to NULL (neither true nor false) then
71527 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
71528 ** is 0.
71529 */
71530 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
71531   Vdbe *v = pParse->pVdbe;
71532   int op = 0;
71533   int regFree1 = 0;
71534   int regFree2 = 0;
71535   int r1, r2;
71536
71537   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
71538   if( NEVER(v==0) ) return; /* Existance of VDBE checked by caller */
71539   if( pExpr==0 )    return;
71540
71541   /* The value of pExpr->op and op are related as follows:
71542   **
71543   **       pExpr->op            op
71544   **       ---------          ----------
71545   **       TK_ISNULL          OP_NotNull
71546   **       TK_NOTNULL         OP_IsNull
71547   **       TK_NE              OP_Eq
71548   **       TK_EQ              OP_Ne
71549   **       TK_GT              OP_Le
71550   **       TK_LE              OP_Gt
71551   **       TK_GE              OP_Lt
71552   **       TK_LT              OP_Ge
71553   **
71554   ** For other values of pExpr->op, op is undefined and unused.
71555   ** The value of TK_ and OP_ constants are arranged such that we
71556   ** can compute the mapping above using the following expression.
71557   ** Assert()s verify that the computation is correct.
71558   */
71559   op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
71560
71561   /* Verify correct alignment of TK_ and OP_ constants
71562   */
71563   assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
71564   assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
71565   assert( pExpr->op!=TK_NE || op==OP_Eq );
71566   assert( pExpr->op!=TK_EQ || op==OP_Ne );
71567   assert( pExpr->op!=TK_LT || op==OP_Ge );
71568   assert( pExpr->op!=TK_LE || op==OP_Gt );
71569   assert( pExpr->op!=TK_GT || op==OP_Le );
71570   assert( pExpr->op!=TK_GE || op==OP_Lt );
71571
71572   switch( pExpr->op ){
71573     case TK_AND: {
71574       testcase( jumpIfNull==0 );
71575       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
71576       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
71577       break;
71578     }
71579     case TK_OR: {
71580       int d2 = sqlite3VdbeMakeLabel(v);
71581       testcase( jumpIfNull==0 );
71582       sqlite3ExprCachePush(pParse);
71583       sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
71584       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
71585       sqlite3VdbeResolveLabel(v, d2);
71586       sqlite3ExprCachePop(pParse, 1);
71587       break;
71588     }
71589     case TK_NOT: {
71590       testcase( jumpIfNull==0 );
71591       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
71592       break;
71593     }
71594     case TK_LT:
71595     case TK_LE:
71596     case TK_GT:
71597     case TK_GE:
71598     case TK_NE:
71599     case TK_EQ: {
71600       testcase( op==TK_LT );
71601       testcase( op==TK_LE );
71602       testcase( op==TK_GT );
71603       testcase( op==TK_GE );
71604       testcase( op==TK_EQ );
71605       testcase( op==TK_NE );
71606       testcase( jumpIfNull==0 );
71607       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
71608       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
71609       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
71610                   r1, r2, dest, jumpIfNull);
71611       testcase( regFree1==0 );
71612       testcase( regFree2==0 );
71613       break;
71614     }
71615     case TK_IS:
71616     case TK_ISNOT: {
71617       testcase( pExpr->op==TK_IS );
71618       testcase( pExpr->op==TK_ISNOT );
71619       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
71620       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
71621       op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
71622       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
71623                   r1, r2, dest, SQLITE_NULLEQ);
71624       testcase( regFree1==0 );
71625       testcase( regFree2==0 );
71626       break;
71627     }
71628     case TK_ISNULL:
71629     case TK_NOTNULL: {
71630       testcase( op==TK_ISNULL );
71631       testcase( op==TK_NOTNULL );
71632       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
71633       sqlite3VdbeAddOp2(v, op, r1, dest);
71634       testcase( regFree1==0 );
71635       break;
71636     }
71637     case TK_BETWEEN: {
71638       testcase( jumpIfNull==0 );
71639       exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
71640       break;
71641     }
71642     case TK_IN: {
71643       if( jumpIfNull ){
71644         sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
71645       }else{
71646         int destIfNull = sqlite3VdbeMakeLabel(v);
71647         sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
71648         sqlite3VdbeResolveLabel(v, destIfNull);
71649       }
71650       break;
71651     }
71652     default: {
71653       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
71654       sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
71655       testcase( regFree1==0 );
71656       testcase( jumpIfNull==0 );
71657       break;
71658     }
71659   }
71660   sqlite3ReleaseTempReg(pParse, regFree1);
71661   sqlite3ReleaseTempReg(pParse, regFree2);
71662 }
71663
71664 /*
71665 ** Do a deep comparison of two expression trees.  Return 0 if the two
71666 ** expressions are completely identical.  Return 1 if they differ only
71667 ** by a COLLATE operator at the top level.  Return 2 if there are differences
71668 ** other than the top-level COLLATE operator.
71669 **
71670 ** Sometimes this routine will return 2 even if the two expressions
71671 ** really are equivalent.  If we cannot prove that the expressions are
71672 ** identical, we return 2 just to be safe.  So if this routine
71673 ** returns 2, then you do not really know for certain if the two
71674 ** expressions are the same.  But if you get a 0 or 1 return, then you
71675 ** can be sure the expressions are the same.  In the places where
71676 ** this routine is used, it does not hurt to get an extra 2 - that
71677 ** just might result in some slightly slower code.  But returning
71678 ** an incorrect 0 or 1 could lead to a malfunction.
71679 */
71680 SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB){
71681   if( pA==0||pB==0 ){
71682     return pB==pA ? 0 : 2;
71683   }
71684   assert( !ExprHasAnyProperty(pA, EP_TokenOnly|EP_Reduced) );
71685   assert( !ExprHasAnyProperty(pB, EP_TokenOnly|EP_Reduced) );
71686   if( ExprHasProperty(pA, EP_xIsSelect) || ExprHasProperty(pB, EP_xIsSelect) ){
71687     return 2;
71688   }
71689   if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
71690   if( pA->op!=pB->op ) return 2;
71691   if( sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 2;
71692   if( sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 2;
71693   if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList) ) return 2;
71694   if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 2;
71695   if( ExprHasProperty(pA, EP_IntValue) ){
71696     if( !ExprHasProperty(pB, EP_IntValue) || pA->u.iValue!=pB->u.iValue ){
71697       return 2;
71698     }
71699   }else if( pA->op!=TK_COLUMN && pA->u.zToken ){
71700     if( ExprHasProperty(pB, EP_IntValue) || NEVER(pB->u.zToken==0) ) return 2;
71701     if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ){
71702       return 2;
71703     }
71704   }
71705   if( (pA->flags & EP_ExpCollate)!=(pB->flags & EP_ExpCollate) ) return 1;
71706   if( (pA->flags & EP_ExpCollate)!=0 && pA->pColl!=pB->pColl ) return 2;
71707   return 0;
71708 }
71709
71710 /*
71711 ** Compare two ExprList objects.  Return 0 if they are identical and 
71712 ** non-zero if they differ in any way.
71713 **
71714 ** This routine might return non-zero for equivalent ExprLists.  The
71715 ** only consequence will be disabled optimizations.  But this routine
71716 ** must never return 0 if the two ExprList objects are different, or
71717 ** a malfunction will result.
71718 **
71719 ** Two NULL pointers are considered to be the same.  But a NULL pointer
71720 ** always differs from a non-NULL pointer.
71721 */
71722 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB){
71723   int i;
71724   if( pA==0 && pB==0 ) return 0;
71725   if( pA==0 || pB==0 ) return 1;
71726   if( pA->nExpr!=pB->nExpr ) return 1;
71727   for(i=0; i<pA->nExpr; i++){
71728     Expr *pExprA = pA->a[i].pExpr;
71729     Expr *pExprB = pB->a[i].pExpr;
71730     if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
71731     if( sqlite3ExprCompare(pExprA, pExprB) ) return 1;
71732   }
71733   return 0;
71734 }
71735
71736 /*
71737 ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
71738 ** the new element.  Return a negative number if malloc fails.
71739 */
71740 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
71741   int i;
71742   pInfo->aCol = sqlite3ArrayAllocate(
71743        db,
71744        pInfo->aCol,
71745        sizeof(pInfo->aCol[0]),
71746        3,
71747        &pInfo->nColumn,
71748        &pInfo->nColumnAlloc,
71749        &i
71750   );
71751   return i;
71752 }    
71753
71754 /*
71755 ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
71756 ** the new element.  Return a negative number if malloc fails.
71757 */
71758 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
71759   int i;
71760   pInfo->aFunc = sqlite3ArrayAllocate(
71761        db, 
71762        pInfo->aFunc,
71763        sizeof(pInfo->aFunc[0]),
71764        3,
71765        &pInfo->nFunc,
71766        &pInfo->nFuncAlloc,
71767        &i
71768   );
71769   return i;
71770 }    
71771
71772 /*
71773 ** This is the xExprCallback for a tree walker.  It is used to
71774 ** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
71775 ** for additional information.
71776 */
71777 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
71778   int i;
71779   NameContext *pNC = pWalker->u.pNC;
71780   Parse *pParse = pNC->pParse;
71781   SrcList *pSrcList = pNC->pSrcList;
71782   AggInfo *pAggInfo = pNC->pAggInfo;
71783
71784   switch( pExpr->op ){
71785     case TK_AGG_COLUMN:
71786     case TK_COLUMN: {
71787       testcase( pExpr->op==TK_AGG_COLUMN );
71788       testcase( pExpr->op==TK_COLUMN );
71789       /* Check to see if the column is in one of the tables in the FROM
71790       ** clause of the aggregate query */
71791       if( ALWAYS(pSrcList!=0) ){
71792         struct SrcList_item *pItem = pSrcList->a;
71793         for(i=0; i<pSrcList->nSrc; i++, pItem++){
71794           struct AggInfo_col *pCol;
71795           assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
71796           if( pExpr->iTable==pItem->iCursor ){
71797             /* If we reach this point, it means that pExpr refers to a table
71798             ** that is in the FROM clause of the aggregate query.  
71799             **
71800             ** Make an entry for the column in pAggInfo->aCol[] if there
71801             ** is not an entry there already.
71802             */
71803             int k;
71804             pCol = pAggInfo->aCol;
71805             for(k=0; k<pAggInfo->nColumn; k++, pCol++){
71806               if( pCol->iTable==pExpr->iTable &&
71807                   pCol->iColumn==pExpr->iColumn ){
71808                 break;
71809               }
71810             }
71811             if( (k>=pAggInfo->nColumn)
71812              && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0 
71813             ){
71814               pCol = &pAggInfo->aCol[k];
71815               pCol->pTab = pExpr->pTab;
71816               pCol->iTable = pExpr->iTable;
71817               pCol->iColumn = pExpr->iColumn;
71818               pCol->iMem = ++pParse->nMem;
71819               pCol->iSorterColumn = -1;
71820               pCol->pExpr = pExpr;
71821               if( pAggInfo->pGroupBy ){
71822                 int j, n;
71823                 ExprList *pGB = pAggInfo->pGroupBy;
71824                 struct ExprList_item *pTerm = pGB->a;
71825                 n = pGB->nExpr;
71826                 for(j=0; j<n; j++, pTerm++){
71827                   Expr *pE = pTerm->pExpr;
71828                   if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
71829                       pE->iColumn==pExpr->iColumn ){
71830                     pCol->iSorterColumn = j;
71831                     break;
71832                   }
71833                 }
71834               }
71835               if( pCol->iSorterColumn<0 ){
71836                 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
71837               }
71838             }
71839             /* There is now an entry for pExpr in pAggInfo->aCol[] (either
71840             ** because it was there before or because we just created it).
71841             ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
71842             ** pAggInfo->aCol[] entry.
71843             */
71844             ExprSetIrreducible(pExpr);
71845             pExpr->pAggInfo = pAggInfo;
71846             pExpr->op = TK_AGG_COLUMN;
71847             pExpr->iAgg = (i16)k;
71848             break;
71849           } /* endif pExpr->iTable==pItem->iCursor */
71850         } /* end loop over pSrcList */
71851       }
71852       return WRC_Prune;
71853     }
71854     case TK_AGG_FUNCTION: {
71855       /* The pNC->nDepth==0 test causes aggregate functions in subqueries
71856       ** to be ignored */
71857       if( pNC->nDepth==0 ){
71858         /* Check to see if pExpr is a duplicate of another aggregate 
71859         ** function that is already in the pAggInfo structure
71860         */
71861         struct AggInfo_func *pItem = pAggInfo->aFunc;
71862         for(i=0; i<pAggInfo->nFunc; i++, pItem++){
71863           if( sqlite3ExprCompare(pItem->pExpr, pExpr)==0 ){
71864             break;
71865           }
71866         }
71867         if( i>=pAggInfo->nFunc ){
71868           /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
71869           */
71870           u8 enc = ENC(pParse->db);
71871           i = addAggInfoFunc(pParse->db, pAggInfo);
71872           if( i>=0 ){
71873             assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
71874             pItem = &pAggInfo->aFunc[i];
71875             pItem->pExpr = pExpr;
71876             pItem->iMem = ++pParse->nMem;
71877             assert( !ExprHasProperty(pExpr, EP_IntValue) );
71878             pItem->pFunc = sqlite3FindFunction(pParse->db,
71879                    pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
71880                    pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
71881             if( pExpr->flags & EP_Distinct ){
71882               pItem->iDistinct = pParse->nTab++;
71883             }else{
71884               pItem->iDistinct = -1;
71885             }
71886           }
71887         }
71888         /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
71889         */
71890         assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
71891         ExprSetIrreducible(pExpr);
71892         pExpr->iAgg = (i16)i;
71893         pExpr->pAggInfo = pAggInfo;
71894         return WRC_Prune;
71895       }
71896     }
71897   }
71898   return WRC_Continue;
71899 }
71900 static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
71901   NameContext *pNC = pWalker->u.pNC;
71902   if( pNC->nDepth==0 ){
71903     pNC->nDepth++;
71904     sqlite3WalkSelect(pWalker, pSelect);
71905     pNC->nDepth--;
71906     return WRC_Prune;
71907   }else{
71908     return WRC_Continue;
71909   }
71910 }
71911
71912 /*
71913 ** Analyze the given expression looking for aggregate functions and
71914 ** for variables that need to be added to the pParse->aAgg[] array.
71915 ** Make additional entries to the pParse->aAgg[] array as necessary.
71916 **
71917 ** This routine should only be called after the expression has been
71918 ** analyzed by sqlite3ResolveExprNames().
71919 */
71920 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
71921   Walker w;
71922   w.xExprCallback = analyzeAggregate;
71923   w.xSelectCallback = analyzeAggregatesInSelect;
71924   w.u.pNC = pNC;
71925   assert( pNC->pSrcList!=0 );
71926   sqlite3WalkExpr(&w, pExpr);
71927 }
71928
71929 /*
71930 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
71931 ** expression list.  Return the number of errors.
71932 **
71933 ** If an error is found, the analysis is cut short.
71934 */
71935 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
71936   struct ExprList_item *pItem;
71937   int i;
71938   if( pList ){
71939     for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
71940       sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
71941     }
71942   }
71943 }
71944
71945 /*
71946 ** Allocate a single new register for use to hold some intermediate result.
71947 */
71948 SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
71949   if( pParse->nTempReg==0 ){
71950     return ++pParse->nMem;
71951   }
71952   return pParse->aTempReg[--pParse->nTempReg];
71953 }
71954
71955 /*
71956 ** Deallocate a register, making available for reuse for some other
71957 ** purpose.
71958 **
71959 ** If a register is currently being used by the column cache, then
71960 ** the dallocation is deferred until the column cache line that uses
71961 ** the register becomes stale.
71962 */
71963 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
71964   if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
71965     int i;
71966     struct yColCache *p;
71967     for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
71968       if( p->iReg==iReg ){
71969         p->tempReg = 1;
71970         return;
71971       }
71972     }
71973     pParse->aTempReg[pParse->nTempReg++] = iReg;
71974   }
71975 }
71976
71977 /*
71978 ** Allocate or deallocate a block of nReg consecutive registers
71979 */
71980 SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
71981   int i, n;
71982   i = pParse->iRangeReg;
71983   n = pParse->nRangeReg;
71984   if( nReg<=n ){
71985     assert( !usedAsColumnCache(pParse, i, i+n-1) );
71986     pParse->iRangeReg += nReg;
71987     pParse->nRangeReg -= nReg;
71988   }else{
71989     i = pParse->nMem+1;
71990     pParse->nMem += nReg;
71991   }
71992   return i;
71993 }
71994 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
71995   sqlite3ExprCacheRemove(pParse, iReg, nReg);
71996   if( nReg>pParse->nRangeReg ){
71997     pParse->nRangeReg = nReg;
71998     pParse->iRangeReg = iReg;
71999   }
72000 }
72001
72002 /************** End of expr.c ************************************************/
72003 /************** Begin file alter.c *******************************************/
72004 /*
72005 ** 2005 February 15
72006 **
72007 ** The author disclaims copyright to this source code.  In place of
72008 ** a legal notice, here is a blessing:
72009 **
72010 **    May you do good and not evil.
72011 **    May you find forgiveness for yourself and forgive others.
72012 **    May you share freely, never taking more than you give.
72013 **
72014 *************************************************************************
72015 ** This file contains C code routines that used to generate VDBE code
72016 ** that implements the ALTER TABLE command.
72017 */
72018
72019 /*
72020 ** The code in this file only exists if we are not omitting the
72021 ** ALTER TABLE logic from the build.
72022 */
72023 #ifndef SQLITE_OMIT_ALTERTABLE
72024
72025
72026 /*
72027 ** This function is used by SQL generated to implement the 
72028 ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
72029 ** CREATE INDEX command. The second is a table name. The table name in 
72030 ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
72031 ** argument and the result returned. Examples:
72032 **
72033 ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
72034 **     -> 'CREATE TABLE def(a, b, c)'
72035 **
72036 ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
72037 **     -> 'CREATE INDEX i ON def(a, b, c)'
72038 */
72039 static void renameTableFunc(
72040   sqlite3_context *context,
72041   int NotUsed,
72042   sqlite3_value **argv
72043 ){
72044   unsigned char const *zSql = sqlite3_value_text(argv[0]);
72045   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
72046
72047   int token;
72048   Token tname;
72049   unsigned char const *zCsr = zSql;
72050   int len = 0;
72051   char *zRet;
72052
72053   sqlite3 *db = sqlite3_context_db_handle(context);
72054
72055   UNUSED_PARAMETER(NotUsed);
72056
72057   /* The principle used to locate the table name in the CREATE TABLE 
72058   ** statement is that the table name is the first non-space token that
72059   ** is immediately followed by a TK_LP or TK_USING token.
72060   */
72061   if( zSql ){
72062     do {
72063       if( !*zCsr ){
72064         /* Ran out of input before finding an opening bracket. Return NULL. */
72065         return;
72066       }
72067
72068       /* Store the token that zCsr points to in tname. */
72069       tname.z = (char*)zCsr;
72070       tname.n = len;
72071
72072       /* Advance zCsr to the next token. Store that token type in 'token',
72073       ** and its length in 'len' (to be used next iteration of this loop).
72074       */
72075       do {
72076         zCsr += len;
72077         len = sqlite3GetToken(zCsr, &token);
72078       } while( token==TK_SPACE );
72079       assert( len>0 );
72080     } while( token!=TK_LP && token!=TK_USING );
72081
72082     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql, 
72083        zTableName, tname.z+tname.n);
72084     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
72085   }
72086 }
72087
72088 /*
72089 ** This C function implements an SQL user function that is used by SQL code
72090 ** generated by the ALTER TABLE ... RENAME command to modify the definition
72091 ** of any foreign key constraints that use the table being renamed as the 
72092 ** parent table. It is passed three arguments:
72093 **
72094 **   1) The complete text of the CREATE TABLE statement being modified,
72095 **   2) The old name of the table being renamed, and
72096 **   3) The new name of the table being renamed.
72097 **
72098 ** It returns the new CREATE TABLE statement. For example:
72099 **
72100 **   sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
72101 **       -> 'CREATE TABLE t1(a REFERENCES t3)'
72102 */
72103 #ifndef SQLITE_OMIT_FOREIGN_KEY
72104 static void renameParentFunc(
72105   sqlite3_context *context,
72106   int NotUsed,
72107   sqlite3_value **argv
72108 ){
72109   sqlite3 *db = sqlite3_context_db_handle(context);
72110   char *zOutput = 0;
72111   char *zResult;
72112   unsigned char const *zInput = sqlite3_value_text(argv[0]);
72113   unsigned char const *zOld = sqlite3_value_text(argv[1]);
72114   unsigned char const *zNew = sqlite3_value_text(argv[2]);
72115
72116   unsigned const char *z;         /* Pointer to token */
72117   int n;                          /* Length of token z */
72118   int token;                      /* Type of token */
72119
72120   UNUSED_PARAMETER(NotUsed);
72121   for(z=zInput; *z; z=z+n){
72122     n = sqlite3GetToken(z, &token);
72123     if( token==TK_REFERENCES ){
72124       char *zParent;
72125       do {
72126         z += n;
72127         n = sqlite3GetToken(z, &token);
72128       }while( token==TK_SPACE );
72129
72130       zParent = sqlite3DbStrNDup(db, (const char *)z, n);
72131       if( zParent==0 ) break;
72132       sqlite3Dequote(zParent);
72133       if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
72134         char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"", 
72135             (zOutput?zOutput:""), z-zInput, zInput, (const char *)zNew
72136         );
72137         sqlite3DbFree(db, zOutput);
72138         zOutput = zOut;
72139         zInput = &z[n];
72140       }
72141       sqlite3DbFree(db, zParent);
72142     }
72143   }
72144
72145   zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput), 
72146   sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
72147   sqlite3DbFree(db, zOutput);
72148 }
72149 #endif
72150
72151 #ifndef SQLITE_OMIT_TRIGGER
72152 /* This function is used by SQL generated to implement the
72153 ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER 
72154 ** statement. The second is a table name. The table name in the CREATE 
72155 ** TRIGGER statement is replaced with the third argument and the result 
72156 ** returned. This is analagous to renameTableFunc() above, except for CREATE
72157 ** TRIGGER, not CREATE INDEX and CREATE TABLE.
72158 */
72159 static void renameTriggerFunc(
72160   sqlite3_context *context,
72161   int NotUsed,
72162   sqlite3_value **argv
72163 ){
72164   unsigned char const *zSql = sqlite3_value_text(argv[0]);
72165   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
72166
72167   int token;
72168   Token tname;
72169   int dist = 3;
72170   unsigned char const *zCsr = zSql;
72171   int len = 0;
72172   char *zRet;
72173   sqlite3 *db = sqlite3_context_db_handle(context);
72174
72175   UNUSED_PARAMETER(NotUsed);
72176
72177   /* The principle used to locate the table name in the CREATE TRIGGER 
72178   ** statement is that the table name is the first token that is immediatedly
72179   ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
72180   ** of TK_WHEN, TK_BEGIN or TK_FOR.
72181   */
72182   if( zSql ){
72183     do {
72184
72185       if( !*zCsr ){
72186         /* Ran out of input before finding the table name. Return NULL. */
72187         return;
72188       }
72189
72190       /* Store the token that zCsr points to in tname. */
72191       tname.z = (char*)zCsr;
72192       tname.n = len;
72193
72194       /* Advance zCsr to the next token. Store that token type in 'token',
72195       ** and its length in 'len' (to be used next iteration of this loop).
72196       */
72197       do {
72198         zCsr += len;
72199         len = sqlite3GetToken(zCsr, &token);
72200       }while( token==TK_SPACE );
72201       assert( len>0 );
72202
72203       /* Variable 'dist' stores the number of tokens read since the most
72204       ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN 
72205       ** token is read and 'dist' equals 2, the condition stated above
72206       ** to be met.
72207       **
72208       ** Note that ON cannot be a database, table or column name, so
72209       ** there is no need to worry about syntax like 
72210       ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
72211       */
72212       dist++;
72213       if( token==TK_DOT || token==TK_ON ){
72214         dist = 0;
72215       }
72216     } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
72217
72218     /* Variable tname now contains the token that is the old table-name
72219     ** in the CREATE TRIGGER statement.
72220     */
72221     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql, 
72222        zTableName, tname.z+tname.n);
72223     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
72224   }
72225 }
72226 #endif   /* !SQLITE_OMIT_TRIGGER */
72227
72228 /*
72229 ** Register built-in functions used to help implement ALTER TABLE
72230 */
72231 SQLITE_PRIVATE void sqlite3AlterFunctions(void){
72232   static SQLITE_WSD FuncDef aAlterTableFuncs[] = {
72233     FUNCTION(sqlite_rename_table,   2, 0, 0, renameTableFunc),
72234 #ifndef SQLITE_OMIT_TRIGGER
72235     FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
72236 #endif
72237 #ifndef SQLITE_OMIT_FOREIGN_KEY
72238     FUNCTION(sqlite_rename_parent,  3, 0, 0, renameParentFunc),
72239 #endif
72240   };
72241   int i;
72242   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
72243   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAlterTableFuncs);
72244
72245   for(i=0; i<ArraySize(aAlterTableFuncs); i++){
72246     sqlite3FuncDefInsert(pHash, &aFunc[i]);
72247   }
72248 }
72249
72250 /*
72251 ** This function is used to create the text of expressions of the form:
72252 **
72253 **   name=<constant1> OR name=<constant2> OR ...
72254 **
72255 ** If argument zWhere is NULL, then a pointer string containing the text 
72256 ** "name=<constant>" is returned, where <constant> is the quoted version
72257 ** of the string passed as argument zConstant. The returned buffer is
72258 ** allocated using sqlite3DbMalloc(). It is the responsibility of the
72259 ** caller to ensure that it is eventually freed.
72260 **
72261 ** If argument zWhere is not NULL, then the string returned is 
72262 ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
72263 ** In this case zWhere is passed to sqlite3DbFree() before returning.
72264 ** 
72265 */
72266 static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
72267   char *zNew;
72268   if( !zWhere ){
72269     zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
72270   }else{
72271     zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
72272     sqlite3DbFree(db, zWhere);
72273   }
72274   return zNew;
72275 }
72276
72277 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
72278 /*
72279 ** Generate the text of a WHERE expression which can be used to select all
72280 ** tables that have foreign key constraints that refer to table pTab (i.e.
72281 ** constraints for which pTab is the parent table) from the sqlite_master
72282 ** table.
72283 */
72284 static char *whereForeignKeys(Parse *pParse, Table *pTab){
72285   FKey *p;
72286   char *zWhere = 0;
72287   for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
72288     zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
72289   }
72290   return zWhere;
72291 }
72292 #endif
72293
72294 /*
72295 ** Generate the text of a WHERE expression which can be used to select all
72296 ** temporary triggers on table pTab from the sqlite_temp_master table. If
72297 ** table pTab has no temporary triggers, or is itself stored in the 
72298 ** temporary database, NULL is returned.
72299 */
72300 static char *whereTempTriggers(Parse *pParse, Table *pTab){
72301   Trigger *pTrig;
72302   char *zWhere = 0;
72303   const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
72304
72305   /* If the table is not located in the temp-db (in which case NULL is 
72306   ** returned, loop through the tables list of triggers. For each trigger
72307   ** that is not part of the temp-db schema, add a clause to the WHERE 
72308   ** expression being built up in zWhere.
72309   */
72310   if( pTab->pSchema!=pTempSchema ){
72311     sqlite3 *db = pParse->db;
72312     for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
72313       if( pTrig->pSchema==pTempSchema ){
72314         zWhere = whereOrName(db, zWhere, pTrig->zName);
72315       }
72316     }
72317   }
72318   if( zWhere ){
72319     char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
72320     sqlite3DbFree(pParse->db, zWhere);
72321     zWhere = zNew;
72322   }
72323   return zWhere;
72324 }
72325
72326 /*
72327 ** Generate code to drop and reload the internal representation of table
72328 ** pTab from the database, including triggers and temporary triggers.
72329 ** Argument zName is the name of the table in the database schema at
72330 ** the time the generated code is executed. This can be different from
72331 ** pTab->zName if this function is being called to code part of an 
72332 ** "ALTER TABLE RENAME TO" statement.
72333 */
72334 static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
72335   Vdbe *v;
72336   char *zWhere;
72337   int iDb;                   /* Index of database containing pTab */
72338 #ifndef SQLITE_OMIT_TRIGGER
72339   Trigger *pTrig;
72340 #endif
72341
72342   v = sqlite3GetVdbe(pParse);
72343   if( NEVER(v==0) ) return;
72344   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
72345   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
72346   assert( iDb>=0 );
72347
72348 #ifndef SQLITE_OMIT_TRIGGER
72349   /* Drop any table triggers from the internal schema. */
72350   for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
72351     int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
72352     assert( iTrigDb==iDb || iTrigDb==1 );
72353     sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
72354   }
72355 #endif
72356
72357   /* Drop the table and index from the internal schema.  */
72358   sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
72359
72360   /* Reload the table, index and permanent trigger schemas. */
72361   zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
72362   if( !zWhere ) return;
72363   sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
72364
72365 #ifndef SQLITE_OMIT_TRIGGER
72366   /* Now, if the table is not stored in the temp database, reload any temp 
72367   ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined. 
72368   */
72369   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
72370     sqlite3VdbeAddOp4(v, OP_ParseSchema, 1, 0, 0, zWhere, P4_DYNAMIC);
72371   }
72372 #endif
72373 }
72374
72375 /*
72376 ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy" 
72377 ** command. 
72378 */
72379 SQLITE_PRIVATE void sqlite3AlterRenameTable(
72380   Parse *pParse,            /* Parser context. */
72381   SrcList *pSrc,            /* The table to rename. */
72382   Token *pName              /* The new table name. */
72383 ){
72384   int iDb;                  /* Database that contains the table */
72385   char *zDb;                /* Name of database iDb */
72386   Table *pTab;              /* Table being renamed */
72387   char *zName = 0;          /* NULL-terminated version of pName */ 
72388   sqlite3 *db = pParse->db; /* Database connection */
72389   int nTabName;             /* Number of UTF-8 characters in zTabName */
72390   const char *zTabName;     /* Original name of the table */
72391   Vdbe *v;
72392 #ifndef SQLITE_OMIT_TRIGGER
72393   char *zWhere = 0;         /* Where clause to locate temp triggers */
72394 #endif
72395   VTable *pVTab = 0;        /* Non-zero if this is a v-tab with an xRename() */
72396   int savedDbFlags;         /* Saved value of db->flags */
72397
72398   savedDbFlags = db->flags;  
72399   if( NEVER(db->mallocFailed) ) goto exit_rename_table;
72400   assert( pSrc->nSrc==1 );
72401   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
72402
72403   pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
72404   if( !pTab ) goto exit_rename_table;
72405   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
72406   zDb = db->aDb[iDb].zName;
72407   db->flags |= SQLITE_PreferBuiltin;
72408
72409   /* Get a NULL terminated version of the new table name. */
72410   zName = sqlite3NameFromToken(db, pName);
72411   if( !zName ) goto exit_rename_table;
72412
72413   /* Check that a table or index named 'zName' does not already exist
72414   ** in database iDb. If so, this is an error.
72415   */
72416   if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
72417     sqlite3ErrorMsg(pParse, 
72418         "there is already another table or index with this name: %s", zName);
72419     goto exit_rename_table;
72420   }
72421
72422   /* Make sure it is not a system table being altered, or a reserved name
72423   ** that the table is being renamed to.
72424   */
72425   if( sqlite3Strlen30(pTab->zName)>6 
72426    && 0==sqlite3StrNICmp(pTab->zName, "sqlite_", 7)
72427   ){
72428     sqlite3ErrorMsg(pParse, "table %s may not be altered", pTab->zName);
72429     goto exit_rename_table;
72430   }
72431   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
72432     goto exit_rename_table;
72433   }
72434
72435 #ifndef SQLITE_OMIT_VIEW
72436   if( pTab->pSelect ){
72437     sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
72438     goto exit_rename_table;
72439   }
72440 #endif
72441
72442 #ifndef SQLITE_OMIT_AUTHORIZATION
72443   /* Invoke the authorization callback. */
72444   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
72445     goto exit_rename_table;
72446   }
72447 #endif
72448
72449 #ifndef SQLITE_OMIT_VIRTUALTABLE
72450   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
72451     goto exit_rename_table;
72452   }
72453   if( IsVirtual(pTab) ){
72454     pVTab = sqlite3GetVTable(db, pTab);
72455     if( pVTab->pVtab->pModule->xRename==0 ){
72456       pVTab = 0;
72457     }
72458   }
72459 #endif
72460
72461   /* Begin a transaction and code the VerifyCookie for database iDb. 
72462   ** Then modify the schema cookie (since the ALTER TABLE modifies the
72463   ** schema). Open a statement transaction if the table is a virtual
72464   ** table.
72465   */
72466   v = sqlite3GetVdbe(pParse);
72467   if( v==0 ){
72468     goto exit_rename_table;
72469   }
72470   sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
72471   sqlite3ChangeCookie(pParse, iDb);
72472
72473   /* If this is a virtual table, invoke the xRename() function if
72474   ** one is defined. The xRename() callback will modify the names
72475   ** of any resources used by the v-table implementation (including other
72476   ** SQLite tables) that are identified by the name of the virtual table.
72477   */
72478 #ifndef SQLITE_OMIT_VIRTUALTABLE
72479   if( pVTab ){
72480     int i = ++pParse->nMem;
72481     sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
72482     sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
72483     sqlite3MayAbort(pParse);
72484   }
72485 #endif
72486
72487   /* figure out how many UTF-8 characters are in zName */
72488   zTabName = pTab->zName;
72489   nTabName = sqlite3Utf8CharLen(zTabName, -1);
72490
72491 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
72492   if( db->flags&SQLITE_ForeignKeys ){
72493     /* If foreign-key support is enabled, rewrite the CREATE TABLE 
72494     ** statements corresponding to all child tables of foreign key constraints
72495     ** for which the renamed table is the parent table.  */
72496     if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
72497       sqlite3NestedParse(pParse, 
72498           "UPDATE \"%w\".%s SET "
72499               "sql = sqlite_rename_parent(sql, %Q, %Q) "
72500               "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
72501       sqlite3DbFree(db, zWhere);
72502     }
72503   }
72504 #endif
72505
72506   /* Modify the sqlite_master table to use the new table name. */
72507   sqlite3NestedParse(pParse,
72508       "UPDATE %Q.%s SET "
72509 #ifdef SQLITE_OMIT_TRIGGER
72510           "sql = sqlite_rename_table(sql, %Q), "
72511 #else
72512           "sql = CASE "
72513             "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
72514             "ELSE sqlite_rename_table(sql, %Q) END, "
72515 #endif
72516           "tbl_name = %Q, "
72517           "name = CASE "
72518             "WHEN type='table' THEN %Q "
72519             "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
72520              "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
72521             "ELSE name END "
72522       "WHERE tbl_name=%Q AND "
72523           "(type='table' OR type='index' OR type='trigger');", 
72524       zDb, SCHEMA_TABLE(iDb), zName, zName, zName, 
72525 #ifndef SQLITE_OMIT_TRIGGER
72526       zName,
72527 #endif
72528       zName, nTabName, zTabName
72529   );
72530
72531 #ifndef SQLITE_OMIT_AUTOINCREMENT
72532   /* If the sqlite_sequence table exists in this database, then update 
72533   ** it with the new table name.
72534   */
72535   if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
72536     sqlite3NestedParse(pParse,
72537         "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
72538         zDb, zName, pTab->zName);
72539   }
72540 #endif
72541
72542 #ifndef SQLITE_OMIT_TRIGGER
72543   /* If there are TEMP triggers on this table, modify the sqlite_temp_master
72544   ** table. Don't do this if the table being ALTERed is itself located in
72545   ** the temp database.
72546   */
72547   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
72548     sqlite3NestedParse(pParse, 
72549         "UPDATE sqlite_temp_master SET "
72550             "sql = sqlite_rename_trigger(sql, %Q), "
72551             "tbl_name = %Q "
72552             "WHERE %s;", zName, zName, zWhere);
72553     sqlite3DbFree(db, zWhere);
72554   }
72555 #endif
72556
72557 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
72558   if( db->flags&SQLITE_ForeignKeys ){
72559     FKey *p;
72560     for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
72561       Table *pFrom = p->pFrom;
72562       if( pFrom!=pTab ){
72563         reloadTableSchema(pParse, p->pFrom, pFrom->zName);
72564       }
72565     }
72566   }
72567 #endif
72568
72569   /* Drop and reload the internal table schema. */
72570   reloadTableSchema(pParse, pTab, zName);
72571
72572 exit_rename_table:
72573   sqlite3SrcListDelete(db, pSrc);
72574   sqlite3DbFree(db, zName);
72575   db->flags = savedDbFlags;
72576 }
72577
72578
72579 /*
72580 ** Generate code to make sure the file format number is at least minFormat.
72581 ** The generated code will increase the file format number if necessary.
72582 */
72583 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
72584   Vdbe *v;
72585   v = sqlite3GetVdbe(pParse);
72586   /* The VDBE should have been allocated before this routine is called.
72587   ** If that allocation failed, we would have quit before reaching this
72588   ** point */
72589   if( ALWAYS(v) ){
72590     int r1 = sqlite3GetTempReg(pParse);
72591     int r2 = sqlite3GetTempReg(pParse);
72592     int j1;
72593     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
72594     sqlite3VdbeUsesBtree(v, iDb);
72595     sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
72596     j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
72597     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
72598     sqlite3VdbeJumpHere(v, j1);
72599     sqlite3ReleaseTempReg(pParse, r1);
72600     sqlite3ReleaseTempReg(pParse, r2);
72601   }
72602 }
72603
72604 /*
72605 ** This function is called after an "ALTER TABLE ... ADD" statement
72606 ** has been parsed. Argument pColDef contains the text of the new
72607 ** column definition.
72608 **
72609 ** The Table structure pParse->pNewTable was extended to include
72610 ** the new column during parsing.
72611 */
72612 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
72613   Table *pNew;              /* Copy of pParse->pNewTable */
72614   Table *pTab;              /* Table being altered */
72615   int iDb;                  /* Database number */
72616   const char *zDb;          /* Database name */
72617   const char *zTab;         /* Table name */
72618   char *zCol;               /* Null-terminated column definition */
72619   Column *pCol;             /* The new column */
72620   Expr *pDflt;              /* Default value for the new column */
72621   sqlite3 *db;              /* The database connection; */
72622
72623   db = pParse->db;
72624   if( pParse->nErr || db->mallocFailed ) return;
72625   pNew = pParse->pNewTable;
72626   assert( pNew );
72627
72628   assert( sqlite3BtreeHoldsAllMutexes(db) );
72629   iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
72630   zDb = db->aDb[iDb].zName;
72631   zTab = &pNew->zName[16];  /* Skip the "sqlite_altertab_" prefix on the name */
72632   pCol = &pNew->aCol[pNew->nCol-1];
72633   pDflt = pCol->pDflt;
72634   pTab = sqlite3FindTable(db, zTab, zDb);
72635   assert( pTab );
72636
72637 #ifndef SQLITE_OMIT_AUTHORIZATION
72638   /* Invoke the authorization callback. */
72639   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
72640     return;
72641   }
72642 #endif
72643
72644   /* If the default value for the new column was specified with a 
72645   ** literal NULL, then set pDflt to 0. This simplifies checking
72646   ** for an SQL NULL default below.
72647   */
72648   if( pDflt && pDflt->op==TK_NULL ){
72649     pDflt = 0;
72650   }
72651
72652   /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
72653   ** If there is a NOT NULL constraint, then the default value for the
72654   ** column must not be NULL.
72655   */
72656   if( pCol->isPrimKey ){
72657     sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
72658     return;
72659   }
72660   if( pNew->pIndex ){
72661     sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
72662     return;
72663   }
72664   if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
72665     sqlite3ErrorMsg(pParse, 
72666         "Cannot add a REFERENCES column with non-NULL default value");
72667     return;
72668   }
72669   if( pCol->notNull && !pDflt ){
72670     sqlite3ErrorMsg(pParse, 
72671         "Cannot add a NOT NULL column with default value NULL");
72672     return;
72673   }
72674
72675   /* Ensure the default expression is something that sqlite3ValueFromExpr()
72676   ** can handle (i.e. not CURRENT_TIME etc.)
72677   */
72678   if( pDflt ){
72679     sqlite3_value *pVal;
72680     if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
72681       db->mallocFailed = 1;
72682       return;
72683     }
72684     if( !pVal ){
72685       sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
72686       return;
72687     }
72688     sqlite3ValueFree(pVal);
72689   }
72690
72691   /* Modify the CREATE TABLE statement. */
72692   zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
72693   if( zCol ){
72694     char *zEnd = &zCol[pColDef->n-1];
72695     int savedDbFlags = db->flags;
72696     while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
72697       *zEnd-- = '\0';
72698     }
72699     db->flags |= SQLITE_PreferBuiltin;
72700     sqlite3NestedParse(pParse, 
72701         "UPDATE \"%w\".%s SET "
72702           "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
72703         "WHERE type = 'table' AND name = %Q", 
72704       zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
72705       zTab
72706     );
72707     sqlite3DbFree(db, zCol);
72708     db->flags = savedDbFlags;
72709   }
72710
72711   /* If the default value of the new column is NULL, then set the file
72712   ** format to 2. If the default value of the new column is not NULL,
72713   ** the file format becomes 3.
72714   */
72715   sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
72716
72717   /* Reload the schema of the modified table. */
72718   reloadTableSchema(pParse, pTab, pTab->zName);
72719 }
72720
72721 /*
72722 ** This function is called by the parser after the table-name in
72723 ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument 
72724 ** pSrc is the full-name of the table being altered.
72725 **
72726 ** This routine makes a (partial) copy of the Table structure
72727 ** for the table being altered and sets Parse.pNewTable to point
72728 ** to it. Routines called by the parser as the column definition
72729 ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to 
72730 ** the copy. The copy of the Table structure is deleted by tokenize.c 
72731 ** after parsing is finished.
72732 **
72733 ** Routine sqlite3AlterFinishAddColumn() will be called to complete
72734 ** coding the "ALTER TABLE ... ADD" statement.
72735 */
72736 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
72737   Table *pNew;
72738   Table *pTab;
72739   Vdbe *v;
72740   int iDb;
72741   int i;
72742   int nAlloc;
72743   sqlite3 *db = pParse->db;
72744
72745   /* Look up the table being altered. */
72746   assert( pParse->pNewTable==0 );
72747   assert( sqlite3BtreeHoldsAllMutexes(db) );
72748   if( db->mallocFailed ) goto exit_begin_add_column;
72749   pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
72750   if( !pTab ) goto exit_begin_add_column;
72751
72752 #ifndef SQLITE_OMIT_VIRTUALTABLE
72753   if( IsVirtual(pTab) ){
72754     sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
72755     goto exit_begin_add_column;
72756   }
72757 #endif
72758
72759   /* Make sure this is not an attempt to ALTER a view. */
72760   if( pTab->pSelect ){
72761     sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
72762     goto exit_begin_add_column;
72763   }
72764
72765   assert( pTab->addColOffset>0 );
72766   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
72767
72768   /* Put a copy of the Table struct in Parse.pNewTable for the
72769   ** sqlite3AddColumn() function and friends to modify.  But modify
72770   ** the name by adding an "sqlite_altertab_" prefix.  By adding this
72771   ** prefix, we insure that the name will not collide with an existing
72772   ** table because user table are not allowed to have the "sqlite_"
72773   ** prefix on their name.
72774   */
72775   pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
72776   if( !pNew ) goto exit_begin_add_column;
72777   pParse->pNewTable = pNew;
72778   pNew->nRef = 1;
72779   pNew->nCol = pTab->nCol;
72780   assert( pNew->nCol>0 );
72781   nAlloc = (((pNew->nCol-1)/8)*8)+8;
72782   assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
72783   pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
72784   pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
72785   if( !pNew->aCol || !pNew->zName ){
72786     db->mallocFailed = 1;
72787     goto exit_begin_add_column;
72788   }
72789   memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
72790   for(i=0; i<pNew->nCol; i++){
72791     Column *pCol = &pNew->aCol[i];
72792     pCol->zName = sqlite3DbStrDup(db, pCol->zName);
72793     pCol->zColl = 0;
72794     pCol->zType = 0;
72795     pCol->pDflt = 0;
72796     pCol->zDflt = 0;
72797   }
72798   pNew->pSchema = db->aDb[iDb].pSchema;
72799   pNew->addColOffset = pTab->addColOffset;
72800   pNew->nRef = 1;
72801
72802   /* Begin a transaction and increment the schema cookie.  */
72803   sqlite3BeginWriteOperation(pParse, 0, iDb);
72804   v = sqlite3GetVdbe(pParse);
72805   if( !v ) goto exit_begin_add_column;
72806   sqlite3ChangeCookie(pParse, iDb);
72807
72808 exit_begin_add_column:
72809   sqlite3SrcListDelete(db, pSrc);
72810   return;
72811 }
72812 #endif  /* SQLITE_ALTER_TABLE */
72813
72814 /************** End of alter.c ***********************************************/
72815 /************** Begin file analyze.c *****************************************/
72816 /*
72817 ** 2005 July 8
72818 **
72819 ** The author disclaims copyright to this source code.  In place of
72820 ** a legal notice, here is a blessing:
72821 **
72822 **    May you do good and not evil.
72823 **    May you find forgiveness for yourself and forgive others.
72824 **    May you share freely, never taking more than you give.
72825 **
72826 *************************************************************************
72827 ** This file contains code associated with the ANALYZE command.
72828 */
72829 #ifndef SQLITE_OMIT_ANALYZE
72830
72831 /*
72832 ** This routine generates code that opens the sqlite_stat1 table for
72833 ** writing with cursor iStatCur. If the library was built with the
72834 ** SQLITE_ENABLE_STAT2 macro defined, then the sqlite_stat2 table is
72835 ** opened for writing using cursor (iStatCur+1)
72836 **
72837 ** If the sqlite_stat1 tables does not previously exist, it is created.
72838 ** Similarly, if the sqlite_stat2 table does not exist and the library
72839 ** is compiled with SQLITE_ENABLE_STAT2 defined, it is created. 
72840 **
72841 ** Argument zWhere may be a pointer to a buffer containing a table name,
72842 ** or it may be a NULL pointer. If it is not NULL, then all entries in
72843 ** the sqlite_stat1 and (if applicable) sqlite_stat2 tables associated
72844 ** with the named table are deleted. If zWhere==0, then code is generated
72845 ** to delete all stat table entries.
72846 */
72847 static void openStatTable(
72848   Parse *pParse,          /* Parsing context */
72849   int iDb,                /* The database we are looking in */
72850   int iStatCur,           /* Open the sqlite_stat1 table on this cursor */
72851   const char *zWhere      /* Delete entries associated with this table */
72852 ){
72853   static const struct {
72854     const char *zName;
72855     const char *zCols;
72856   } aTable[] = {
72857     { "sqlite_stat1", "tbl,idx,stat" },
72858 #ifdef SQLITE_ENABLE_STAT2
72859     { "sqlite_stat2", "tbl,idx,sampleno,sample" },
72860 #endif
72861   };
72862
72863   int aRoot[] = {0, 0};
72864   u8 aCreateTbl[] = {0, 0};
72865
72866   int i;
72867   sqlite3 *db = pParse->db;
72868   Db *pDb;
72869   Vdbe *v = sqlite3GetVdbe(pParse);
72870   if( v==0 ) return;
72871   assert( sqlite3BtreeHoldsAllMutexes(db) );
72872   assert( sqlite3VdbeDb(v)==db );
72873   pDb = &db->aDb[iDb];
72874
72875   for(i=0; i<ArraySize(aTable); i++){
72876     const char *zTab = aTable[i].zName;
72877     Table *pStat;
72878     if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
72879       /* The sqlite_stat[12] table does not exist. Create it. Note that a 
72880       ** side-effect of the CREATE TABLE statement is to leave the rootpage 
72881       ** of the new table in register pParse->regRoot. This is important 
72882       ** because the OpenWrite opcode below will be needing it. */
72883       sqlite3NestedParse(pParse,
72884           "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
72885       );
72886       aRoot[i] = pParse->regRoot;
72887       aCreateTbl[i] = 1;
72888     }else{
72889       /* The table already exists. If zWhere is not NULL, delete all entries 
72890       ** associated with the table zWhere. If zWhere is NULL, delete the
72891       ** entire contents of the table. */
72892       aRoot[i] = pStat->tnum;
72893       sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
72894       if( zWhere ){
72895         sqlite3NestedParse(pParse,
72896            "DELETE FROM %Q.%s WHERE tbl=%Q", pDb->zName, zTab, zWhere
72897         );
72898       }else{
72899         /* The sqlite_stat[12] table already exists.  Delete all rows. */
72900         sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
72901       }
72902     }
72903   }
72904
72905   /* Open the sqlite_stat[12] tables for writing. */
72906   for(i=0; i<ArraySize(aTable); i++){
72907     sqlite3VdbeAddOp3(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb);
72908     sqlite3VdbeChangeP4(v, -1, (char *)3, P4_INT32);
72909     sqlite3VdbeChangeP5(v, aCreateTbl[i]);
72910   }
72911 }
72912
72913 /*
72914 ** Generate code to do an analysis of all indices associated with
72915 ** a single table.
72916 */
72917 static void analyzeOneTable(
72918   Parse *pParse,   /* Parser context */
72919   Table *pTab,     /* Table whose indices are to be analyzed */
72920   int iStatCur,    /* Index of VdbeCursor that writes the sqlite_stat1 table */
72921   int iMem         /* Available memory locations begin here */
72922 ){
72923   sqlite3 *db = pParse->db;    /* Database handle */
72924   Index *pIdx;                 /* An index to being analyzed */
72925   int iIdxCur;                 /* Cursor open on index being analyzed */
72926   Vdbe *v;                     /* The virtual machine being built up */
72927   int i;                       /* Loop counter */
72928   int topOfLoop;               /* The top of the loop */
72929   int endOfLoop;               /* The end of the loop */
72930   int addr = 0;                /* The address of an instruction */
72931   int jZeroRows = 0;           /* Jump from here if number of rows is zero */
72932   int iDb;                     /* Index of database containing pTab */
72933   int regTabname = iMem++;     /* Register containing table name */
72934   int regIdxname = iMem++;     /* Register containing index name */
72935   int regSampleno = iMem++;    /* Register containing next sample number */
72936   int regCol = iMem++;         /* Content of a column analyzed table */
72937   int regRec = iMem++;         /* Register holding completed record */
72938   int regTemp = iMem++;        /* Temporary use register */
72939   int regRowid = iMem++;       /* Rowid for the inserted record */
72940
72941 #ifdef SQLITE_ENABLE_STAT2
72942   int regTemp2 = iMem++;       /* Temporary use register */
72943   int regSamplerecno = iMem++; /* Index of next sample to record */
72944   int regRecno = iMem++;       /* Current sample index */
72945   int regLast = iMem++;        /* Index of last sample to record */
72946   int regFirst = iMem++;       /* Index of first sample to record */
72947 #endif
72948
72949   v = sqlite3GetVdbe(pParse);
72950   if( v==0 || NEVER(pTab==0) ){
72951     return;
72952   }
72953   if( pTab->tnum==0 ){
72954     /* Do not gather statistics on views or virtual tables */
72955     return;
72956   }
72957   if( memcmp(pTab->zName, "sqlite_", 7)==0 ){
72958     /* Do not gather statistics on system tables */
72959     return;
72960   }
72961   assert( sqlite3BtreeHoldsAllMutexes(db) );
72962   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
72963   assert( iDb>=0 );
72964 #ifndef SQLITE_OMIT_AUTHORIZATION
72965   if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
72966       db->aDb[iDb].zName ) ){
72967     return;
72968   }
72969 #endif
72970
72971   /* Establish a read-lock on the table at the shared-cache level. */
72972   sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
72973
72974   iIdxCur = pParse->nTab++;
72975   sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
72976   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
72977     int nCol = pIdx->nColumn;
72978     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
72979
72980     if( iMem+1+(nCol*2)>pParse->nMem ){
72981       pParse->nMem = iMem+1+(nCol*2);
72982     }
72983
72984     /* Open a cursor to the index to be analyzed. */
72985     assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
72986     sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb,
72987         (char *)pKey, P4_KEYINFO_HANDOFF);
72988     VdbeComment((v, "%s", pIdx->zName));
72989
72990     /* Populate the register containing the index name. */
72991     sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, pIdx->zName, 0);
72992
72993 #ifdef SQLITE_ENABLE_STAT2
72994
72995     /* If this iteration of the loop is generating code to analyze the
72996     ** first index in the pTab->pIndex list, then register regLast has
72997     ** not been populated. In this case populate it now.  */
72998     if( pTab->pIndex==pIdx ){
72999       sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES, regSamplerecno);
73000       sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES*2-1, regTemp);
73001       sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES*2, regTemp2);
73002
73003       sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regLast);
73004       sqlite3VdbeAddOp2(v, OP_Null, 0, regFirst);
73005       addr = sqlite3VdbeAddOp3(v, OP_Lt, regSamplerecno, 0, regLast);
73006       sqlite3VdbeAddOp3(v, OP_Divide, regTemp2, regLast, regFirst);
73007       sqlite3VdbeAddOp3(v, OP_Multiply, regLast, regTemp, regLast);
73008       sqlite3VdbeAddOp2(v, OP_AddImm, regLast, SQLITE_INDEX_SAMPLES*2-2);
73009       sqlite3VdbeAddOp3(v, OP_Divide,  regTemp2, regLast, regLast);
73010       sqlite3VdbeJumpHere(v, addr);
73011     }
73012
73013     /* Zero the regSampleno and regRecno registers. */
73014     sqlite3VdbeAddOp2(v, OP_Integer, 0, regSampleno);
73015     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRecno);
73016     sqlite3VdbeAddOp2(v, OP_Copy, regFirst, regSamplerecno);
73017 #endif
73018
73019     /* The block of memory cells initialized here is used as follows.
73020     **
73021     **    iMem:                
73022     **        The total number of rows in the table.
73023     **
73024     **    iMem+1 .. iMem+nCol: 
73025     **        Number of distinct entries in index considering the 
73026     **        left-most N columns only, where N is between 1 and nCol, 
73027     **        inclusive.
73028     **
73029     **    iMem+nCol+1 .. Mem+2*nCol:  
73030     **        Previous value of indexed columns, from left to right.
73031     **
73032     ** Cells iMem through iMem+nCol are initialized to 0. The others are 
73033     ** initialized to contain an SQL NULL.
73034     */
73035     for(i=0; i<=nCol; i++){
73036       sqlite3VdbeAddOp2(v, OP_Integer, 0, iMem+i);
73037     }
73038     for(i=0; i<nCol; i++){
73039       sqlite3VdbeAddOp2(v, OP_Null, 0, iMem+nCol+i+1);
73040     }
73041
73042     /* Start the analysis loop. This loop runs through all the entries in
73043     ** the index b-tree.  */
73044     endOfLoop = sqlite3VdbeMakeLabel(v);
73045     sqlite3VdbeAddOp2(v, OP_Rewind, iIdxCur, endOfLoop);
73046     topOfLoop = sqlite3VdbeCurrentAddr(v);
73047     sqlite3VdbeAddOp2(v, OP_AddImm, iMem, 1);
73048
73049     for(i=0; i<nCol; i++){
73050       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regCol);
73051 #ifdef SQLITE_ENABLE_STAT2
73052       if( i==0 ){
73053         /* Check if the record that cursor iIdxCur points to contains a
73054         ** value that should be stored in the sqlite_stat2 table. If so,
73055         ** store it.  */
73056         int ne = sqlite3VdbeAddOp3(v, OP_Ne, regRecno, 0, regSamplerecno);
73057         assert( regTabname+1==regIdxname 
73058              && regTabname+2==regSampleno
73059              && regTabname+3==regCol
73060         );
73061         sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
73062         sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 4, regRec, "aaab", 0);
73063         sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regRowid);
73064         sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regRec, regRowid);
73065
73066         /* Calculate new values for regSamplerecno and regSampleno.
73067         **
73068         **   sampleno = sampleno + 1
73069         **   samplerecno = samplerecno+(remaining records)/(remaining samples)
73070         */
73071         sqlite3VdbeAddOp2(v, OP_AddImm, regSampleno, 1);
73072         sqlite3VdbeAddOp3(v, OP_Subtract, regRecno, regLast, regTemp);
73073         sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
73074         sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES, regTemp2);
73075         sqlite3VdbeAddOp3(v, OP_Subtract, regSampleno, regTemp2, regTemp2);
73076         sqlite3VdbeAddOp3(v, OP_Divide, regTemp2, regTemp, regTemp);
73077         sqlite3VdbeAddOp3(v, OP_Add, regSamplerecno, regTemp, regSamplerecno);
73078
73079         sqlite3VdbeJumpHere(v, ne);
73080         sqlite3VdbeAddOp2(v, OP_AddImm, regRecno, 1);
73081       }
73082 #endif
73083
73084       sqlite3VdbeAddOp3(v, OP_Ne, regCol, 0, iMem+nCol+i+1);
73085       /**** TODO:  add collating sequence *****/
73086       sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
73087     }
73088     if( db->mallocFailed ){
73089       /* If a malloc failure has occurred, then the result of the expression 
73090       ** passed as the second argument to the call to sqlite3VdbeJumpHere() 
73091       ** below may be negative. Which causes an assert() to fail (or an
73092       ** out-of-bounds write if SQLITE_DEBUG is not defined).  */
73093       return;
73094     }
73095     sqlite3VdbeAddOp2(v, OP_Goto, 0, endOfLoop);
73096     for(i=0; i<nCol; i++){
73097       sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-(nCol*2));
73098       sqlite3VdbeAddOp2(v, OP_AddImm, iMem+i+1, 1);
73099       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, iMem+nCol+i+1);
73100     }
73101
73102     /* End of the analysis loop. */
73103     sqlite3VdbeResolveLabel(v, endOfLoop);
73104     sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, topOfLoop);
73105     sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
73106
73107     /* Store the results in sqlite_stat1.
73108     **
73109     ** The result is a single row of the sqlite_stat1 table.  The first
73110     ** two columns are the names of the table and index.  The third column
73111     ** is a string composed of a list of integer statistics about the
73112     ** index.  The first integer in the list is the total number of entries
73113     ** in the index.  There is one additional integer in the list for each
73114     ** column of the table.  This additional integer is a guess of how many
73115     ** rows of the table the index will select.  If D is the count of distinct
73116     ** values and K is the total number of rows, then the integer is computed
73117     ** as:
73118     **
73119     **        I = (K+D-1)/D
73120     **
73121     ** If K==0 then no entry is made into the sqlite_stat1 table.  
73122     ** If K>0 then it is always the case the D>0 so division by zero
73123     ** is never possible.
73124     */
73125     sqlite3VdbeAddOp2(v, OP_SCopy, iMem, regSampleno);
73126     if( jZeroRows==0 ){
73127       jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, iMem);
73128     }
73129     for(i=0; i<nCol; i++){
73130       sqlite3VdbeAddOp4(v, OP_String8, 0, regTemp, 0, " ", 0);
73131       sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regSampleno, regSampleno);
73132       sqlite3VdbeAddOp3(v, OP_Add, iMem, iMem+i+1, regTemp);
73133       sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
73134       sqlite3VdbeAddOp3(v, OP_Divide, iMem+i+1, regTemp, regTemp);
73135       sqlite3VdbeAddOp1(v, OP_ToInt, regTemp);
73136       sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regSampleno, regSampleno);
73137     }
73138     sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
73139     sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regRowid);
73140     sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regRowid);
73141     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
73142   }
73143
73144   /* If the table has no indices, create a single sqlite_stat1 entry
73145   ** containing NULL as the index name and the row count as the content.
73146   */
73147   if( pTab->pIndex==0 ){
73148     sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pTab->tnum, iDb);
73149     VdbeComment((v, "%s", pTab->zName));
73150     sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regSampleno);
73151     sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
73152   }else{
73153     assert( jZeroRows>0 );
73154     addr = sqlite3VdbeAddOp0(v, OP_Goto);
73155     sqlite3VdbeJumpHere(v, jZeroRows);
73156   }
73157   sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
73158   sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
73159   sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regRowid);
73160   sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regRowid);
73161   sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
73162   if( pParse->nMem<regRec ) pParse->nMem = regRec;
73163   if( jZeroRows ){
73164     sqlite3VdbeJumpHere(v, addr);
73165   }
73166 }
73167
73168 /*
73169 ** Generate code that will cause the most recent index analysis to
73170 ** be loaded into internal hash tables where is can be used.
73171 */
73172 static void loadAnalysis(Parse *pParse, int iDb){
73173   Vdbe *v = sqlite3GetVdbe(pParse);
73174   if( v ){
73175     sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
73176   }
73177 }
73178
73179 /*
73180 ** Generate code that will do an analysis of an entire database
73181 */
73182 static void analyzeDatabase(Parse *pParse, int iDb){
73183   sqlite3 *db = pParse->db;
73184   Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */
73185   HashElem *k;
73186   int iStatCur;
73187   int iMem;
73188
73189   sqlite3BeginWriteOperation(pParse, 0, iDb);
73190   iStatCur = pParse->nTab;
73191   pParse->nTab += 2;
73192   openStatTable(pParse, iDb, iStatCur, 0);
73193   iMem = pParse->nMem+1;
73194   for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
73195     Table *pTab = (Table*)sqliteHashData(k);
73196     analyzeOneTable(pParse, pTab, iStatCur, iMem);
73197   }
73198   loadAnalysis(pParse, iDb);
73199 }
73200
73201 /*
73202 ** Generate code that will do an analysis of a single table in
73203 ** a database.
73204 */
73205 static void analyzeTable(Parse *pParse, Table *pTab){
73206   int iDb;
73207   int iStatCur;
73208
73209   assert( pTab!=0 );
73210   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
73211   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
73212   sqlite3BeginWriteOperation(pParse, 0, iDb);
73213   iStatCur = pParse->nTab;
73214   pParse->nTab += 2;
73215   openStatTable(pParse, iDb, iStatCur, pTab->zName);
73216   analyzeOneTable(pParse, pTab, iStatCur, pParse->nMem+1);
73217   loadAnalysis(pParse, iDb);
73218 }
73219
73220 /*
73221 ** Generate code for the ANALYZE command.  The parser calls this routine
73222 ** when it recognizes an ANALYZE command.
73223 **
73224 **        ANALYZE                            -- 1
73225 **        ANALYZE  <database>                -- 2
73226 **        ANALYZE  ?<database>.?<tablename>  -- 3
73227 **
73228 ** Form 1 causes all indices in all attached databases to be analyzed.
73229 ** Form 2 analyzes all indices the single database named.
73230 ** Form 3 analyzes all indices associated with the named table.
73231 */
73232 SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
73233   sqlite3 *db = pParse->db;
73234   int iDb;
73235   int i;
73236   char *z, *zDb;
73237   Table *pTab;
73238   Token *pTableName;
73239
73240   /* Read the database schema. If an error occurs, leave an error message
73241   ** and code in pParse and return NULL. */
73242   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
73243   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
73244     return;
73245   }
73246
73247   assert( pName2!=0 || pName1==0 );
73248   if( pName1==0 ){
73249     /* Form 1:  Analyze everything */
73250     for(i=0; i<db->nDb; i++){
73251       if( i==1 ) continue;  /* Do not analyze the TEMP database */
73252       analyzeDatabase(pParse, i);
73253     }
73254   }else if( pName2->n==0 ){
73255     /* Form 2:  Analyze the database or table named */
73256     iDb = sqlite3FindDb(db, pName1);
73257     if( iDb>=0 ){
73258       analyzeDatabase(pParse, iDb);
73259     }else{
73260       z = sqlite3NameFromToken(db, pName1);
73261       if( z ){
73262         pTab = sqlite3LocateTable(pParse, 0, z, 0);
73263         sqlite3DbFree(db, z);
73264         if( pTab ){
73265           analyzeTable(pParse, pTab);
73266         }
73267       }
73268     }
73269   }else{
73270     /* Form 3: Analyze the fully qualified table name */
73271     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
73272     if( iDb>=0 ){
73273       zDb = db->aDb[iDb].zName;
73274       z = sqlite3NameFromToken(db, pTableName);
73275       if( z ){
73276         pTab = sqlite3LocateTable(pParse, 0, z, zDb);
73277         sqlite3DbFree(db, z);
73278         if( pTab ){
73279           analyzeTable(pParse, pTab);
73280         }
73281       }
73282     }   
73283   }
73284 }
73285
73286 /*
73287 ** Used to pass information from the analyzer reader through to the
73288 ** callback routine.
73289 */
73290 typedef struct analysisInfo analysisInfo;
73291 struct analysisInfo {
73292   sqlite3 *db;
73293   const char *zDatabase;
73294 };
73295
73296 /*
73297 ** This callback is invoked once for each index when reading the
73298 ** sqlite_stat1 table.  
73299 **
73300 **     argv[0] = name of the table
73301 **     argv[1] = name of the index (might be NULL)
73302 **     argv[2] = results of analysis - on integer for each column
73303 **
73304 ** Entries for which argv[1]==NULL simply record the number of rows in
73305 ** the table.
73306 */
73307 static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
73308   analysisInfo *pInfo = (analysisInfo*)pData;
73309   Index *pIndex;
73310   Table *pTable;
73311   int i, c, n;
73312   unsigned int v;
73313   const char *z;
73314
73315   assert( argc==3 );
73316   UNUSED_PARAMETER2(NotUsed, argc);
73317
73318   if( argv==0 || argv[0]==0 || argv[2]==0 ){
73319     return 0;
73320   }
73321   pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
73322   if( pTable==0 ){
73323     return 0;
73324   }
73325   if( argv[1] ){
73326     pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
73327   }else{
73328     pIndex = 0;
73329   }
73330   n = pIndex ? pIndex->nColumn : 0;
73331   z = argv[2];
73332   for(i=0; *z && i<=n; i++){
73333     v = 0;
73334     while( (c=z[0])>='0' && c<='9' ){
73335       v = v*10 + c - '0';
73336       z++;
73337     }
73338     if( i==0 ) pTable->nRowEst = v;
73339     if( pIndex==0 ) break;
73340     pIndex->aiRowEst[i] = v;
73341     if( *z==' ' ) z++;
73342   }
73343   return 0;
73344 }
73345
73346 /*
73347 ** If the Index.aSample variable is not NULL, delete the aSample[] array
73348 ** and its contents.
73349 */
73350 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
73351 #ifdef SQLITE_ENABLE_STAT2
73352   if( pIdx->aSample ){
73353     int j;
73354     for(j=0; j<SQLITE_INDEX_SAMPLES; j++){
73355       IndexSample *p = &pIdx->aSample[j];
73356       if( p->eType==SQLITE_TEXT || p->eType==SQLITE_BLOB ){
73357         sqlite3DbFree(db, p->u.z);
73358       }
73359     }
73360     sqlite3DbFree(db, pIdx->aSample);
73361   }
73362 #else
73363   UNUSED_PARAMETER(db);
73364   UNUSED_PARAMETER(pIdx);
73365 #endif
73366 }
73367
73368 /*
73369 ** Load the content of the sqlite_stat1 and sqlite_stat2 tables. The
73370 ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
73371 ** arrays. The contents of sqlite_stat2 are used to populate the
73372 ** Index.aSample[] arrays.
73373 **
73374 ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
73375 ** is returned. In this case, even if SQLITE_ENABLE_STAT2 was defined 
73376 ** during compilation and the sqlite_stat2 table is present, no data is 
73377 ** read from it.
73378 **
73379 ** If SQLITE_ENABLE_STAT2 was defined during compilation and the 
73380 ** sqlite_stat2 table is not present in the database, SQLITE_ERROR is
73381 ** returned. However, in this case, data is read from the sqlite_stat1
73382 ** table (if it is present) before returning.
73383 **
73384 ** If an OOM error occurs, this function always sets db->mallocFailed.
73385 ** This means if the caller does not care about other errors, the return
73386 ** code may be ignored.
73387 */
73388 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
73389   analysisInfo sInfo;
73390   HashElem *i;
73391   char *zSql;
73392   int rc;
73393
73394   assert( iDb>=0 && iDb<db->nDb );
73395   assert( db->aDb[iDb].pBt!=0 );
73396   assert( sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
73397
73398   /* Clear any prior statistics */
73399   for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
73400     Index *pIdx = sqliteHashData(i);
73401     sqlite3DefaultRowEst(pIdx);
73402     sqlite3DeleteIndexSamples(db, pIdx);
73403     pIdx->aSample = 0;
73404   }
73405
73406   /* Check to make sure the sqlite_stat1 table exists */
73407   sInfo.db = db;
73408   sInfo.zDatabase = db->aDb[iDb].zName;
73409   if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
73410     return SQLITE_ERROR;
73411   }
73412
73413   /* Load new statistics out of the sqlite_stat1 table */
73414   zSql = sqlite3MPrintf(db, 
73415       "SELECT tbl, idx, stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
73416   if( zSql==0 ){
73417     rc = SQLITE_NOMEM;
73418   }else{
73419     rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
73420     sqlite3DbFree(db, zSql);
73421   }
73422
73423
73424   /* Load the statistics from the sqlite_stat2 table. */
73425 #ifdef SQLITE_ENABLE_STAT2
73426   if( rc==SQLITE_OK && !sqlite3FindTable(db, "sqlite_stat2", sInfo.zDatabase) ){
73427     rc = SQLITE_ERROR;
73428   }
73429   if( rc==SQLITE_OK ){
73430     sqlite3_stmt *pStmt = 0;
73431
73432     zSql = sqlite3MPrintf(db, 
73433         "SELECT idx,sampleno,sample FROM %Q.sqlite_stat2", sInfo.zDatabase);
73434     if( !zSql ){
73435       rc = SQLITE_NOMEM;
73436     }else{
73437       rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
73438       sqlite3DbFree(db, zSql);
73439     }
73440
73441     if( rc==SQLITE_OK ){
73442       while( sqlite3_step(pStmt)==SQLITE_ROW ){
73443         char *zIndex = (char *)sqlite3_column_text(pStmt, 0);
73444         Index *pIdx = sqlite3FindIndex(db, zIndex, sInfo.zDatabase);
73445         if( pIdx ){
73446           int iSample = sqlite3_column_int(pStmt, 1);
73447           if( iSample<SQLITE_INDEX_SAMPLES && iSample>=0 ){
73448             int eType = sqlite3_column_type(pStmt, 2);
73449
73450             if( pIdx->aSample==0 ){
73451               static const int sz = sizeof(IndexSample)*SQLITE_INDEX_SAMPLES;
73452               pIdx->aSample = (IndexSample *)sqlite3DbMallocRaw(0, sz);
73453               if( pIdx->aSample==0 ){
73454                 db->mallocFailed = 1;
73455                 break;
73456               }
73457               memset(pIdx->aSample, 0, sz);
73458             }
73459
73460             assert( pIdx->aSample );
73461             {
73462               IndexSample *pSample = &pIdx->aSample[iSample];
73463               pSample->eType = (u8)eType;
73464               if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
73465                 pSample->u.r = sqlite3_column_double(pStmt, 2);
73466               }else if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
73467                 const char *z = (const char *)(
73468                     (eType==SQLITE_BLOB) ?
73469                     sqlite3_column_blob(pStmt, 2):
73470                     sqlite3_column_text(pStmt, 2)
73471                 );
73472                 int n = sqlite3_column_bytes(pStmt, 2);
73473                 if( n>24 ){
73474                   n = 24;
73475                 }
73476                 pSample->nByte = (u8)n;
73477                 if( n < 1){
73478                   pSample->u.z = 0;
73479                 }else{
73480                   pSample->u.z = sqlite3DbStrNDup(0, z, n);
73481                   if( pSample->u.z==0 ){
73482                     db->mallocFailed = 1;
73483                     break;
73484                   }
73485                 }
73486               }
73487             }
73488           }
73489         }
73490       }
73491       rc = sqlite3_finalize(pStmt);
73492     }
73493   }
73494 #endif
73495
73496   if( rc==SQLITE_NOMEM ){
73497     db->mallocFailed = 1;
73498   }
73499   return rc;
73500 }
73501
73502
73503 #endif /* SQLITE_OMIT_ANALYZE */
73504
73505 /************** End of analyze.c *********************************************/
73506 /************** Begin file attach.c ******************************************/
73507 /*
73508 ** 2003 April 6
73509 **
73510 ** The author disclaims copyright to this source code.  In place of
73511 ** a legal notice, here is a blessing:
73512 **
73513 **    May you do good and not evil.
73514 **    May you find forgiveness for yourself and forgive others.
73515 **    May you share freely, never taking more than you give.
73516 **
73517 *************************************************************************
73518 ** This file contains code used to implement the ATTACH and DETACH commands.
73519 */
73520
73521 #ifndef SQLITE_OMIT_ATTACH
73522 /*
73523 ** Resolve an expression that was part of an ATTACH or DETACH statement. This
73524 ** is slightly different from resolving a normal SQL expression, because simple
73525 ** identifiers are treated as strings, not possible column names or aliases.
73526 **
73527 ** i.e. if the parser sees:
73528 **
73529 **     ATTACH DATABASE abc AS def
73530 **
73531 ** it treats the two expressions as literal strings 'abc' and 'def' instead of
73532 ** looking for columns of the same name.
73533 **
73534 ** This only applies to the root node of pExpr, so the statement:
73535 **
73536 **     ATTACH DATABASE abc||def AS 'db2'
73537 **
73538 ** will fail because neither abc or def can be resolved.
73539 */
73540 static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
73541 {
73542   int rc = SQLITE_OK;
73543   if( pExpr ){
73544     if( pExpr->op!=TK_ID ){
73545       rc = sqlite3ResolveExprNames(pName, pExpr);
73546       if( rc==SQLITE_OK && !sqlite3ExprIsConstant(pExpr) ){
73547         sqlite3ErrorMsg(pName->pParse, "invalid name: \"%s\"", pExpr->u.zToken);
73548         return SQLITE_ERROR;
73549       }
73550     }else{
73551       pExpr->op = TK_STRING;
73552     }
73553   }
73554   return rc;
73555 }
73556
73557 /*
73558 ** An SQL user-function registered to do the work of an ATTACH statement. The
73559 ** three arguments to the function come directly from an attach statement:
73560 **
73561 **     ATTACH DATABASE x AS y KEY z
73562 **
73563 **     SELECT sqlite_attach(x, y, z)
73564 **
73565 ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
73566 ** third argument.
73567 */
73568 static void attachFunc(
73569   sqlite3_context *context,
73570   int NotUsed,
73571   sqlite3_value **argv
73572 ){
73573   int i;
73574   int rc = 0;
73575   sqlite3 *db = sqlite3_context_db_handle(context);
73576   const char *zName;
73577   const char *zFile;
73578   Db *aNew;
73579   char *zErrDyn = 0;
73580
73581   UNUSED_PARAMETER(NotUsed);
73582
73583   zFile = (const char *)sqlite3_value_text(argv[0]);
73584   zName = (const char *)sqlite3_value_text(argv[1]);
73585   if( zFile==0 ) zFile = "";
73586   if( zName==0 ) zName = "";
73587
73588   /* Check for the following errors:
73589   **
73590   **     * Too many attached databases,
73591   **     * Transaction currently open
73592   **     * Specified database name already being used.
73593   */
73594   if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
73595     zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d", 
73596       db->aLimit[SQLITE_LIMIT_ATTACHED]
73597     );
73598     goto attach_error;
73599   }
73600   if( !db->autoCommit ){
73601     zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
73602     goto attach_error;
73603   }
73604   for(i=0; i<db->nDb; i++){
73605     char *z = db->aDb[i].zName;
73606     assert( z && zName );
73607     if( sqlite3StrICmp(z, zName)==0 ){
73608       zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
73609       goto attach_error;
73610     }
73611   }
73612
73613   /* Allocate the new entry in the db->aDb[] array and initialise the schema
73614   ** hash tables.
73615   */
73616   if( db->aDb==db->aDbStatic ){
73617     aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
73618     if( aNew==0 ) return;
73619     memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
73620   }else{
73621     aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
73622     if( aNew==0 ) return;
73623   }
73624   db->aDb = aNew;
73625   aNew = &db->aDb[db->nDb];
73626   memset(aNew, 0, sizeof(*aNew));
73627
73628   /* Open the database file. If the btree is successfully opened, use
73629   ** it to obtain the database schema. At this point the schema may
73630   ** or may not be initialised.
73631   */
73632   rc = sqlite3BtreeOpen(zFile, db, &aNew->pBt, 0,
73633                         db->openFlags | SQLITE_OPEN_MAIN_DB);
73634   db->nDb++;
73635   if( rc==SQLITE_CONSTRAINT ){
73636     rc = SQLITE_ERROR;
73637     zErrDyn = sqlite3MPrintf(db, "database is already attached");
73638   }else if( rc==SQLITE_OK ){
73639     Pager *pPager;
73640     aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
73641     if( !aNew->pSchema ){
73642       rc = SQLITE_NOMEM;
73643     }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
73644       zErrDyn = sqlite3MPrintf(db, 
73645         "attached databases must use the same text encoding as main database");
73646       rc = SQLITE_ERROR;
73647     }
73648     pPager = sqlite3BtreePager(aNew->pBt);
73649     sqlite3PagerLockingMode(pPager, db->dfltLockMode);
73650     sqlite3BtreeSecureDelete(aNew->pBt,
73651                              sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
73652   }
73653   aNew->safety_level = 3;
73654   aNew->zName = sqlite3DbStrDup(db, zName);
73655   if( rc==SQLITE_OK && aNew->zName==0 ){
73656     rc = SQLITE_NOMEM;
73657   }
73658
73659
73660 #ifdef SQLITE_HAS_CODEC
73661   if( rc==SQLITE_OK ){
73662     extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
73663     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
73664     int nKey;
73665     char *zKey;
73666     int t = sqlite3_value_type(argv[2]);
73667     switch( t ){
73668       case SQLITE_INTEGER:
73669       case SQLITE_FLOAT:
73670         zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
73671         rc = SQLITE_ERROR;
73672         break;
73673         
73674       case SQLITE_TEXT:
73675       case SQLITE_BLOB:
73676         nKey = sqlite3_value_bytes(argv[2]);
73677         zKey = (char *)sqlite3_value_blob(argv[2]);
73678         rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
73679         break;
73680
73681       case SQLITE_NULL:
73682         /* No key specified.  Use the key from the main database */
73683         sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
73684         rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
73685         break;
73686     }
73687   }
73688 #endif
73689
73690   /* If the file was opened successfully, read the schema for the new database.
73691   ** If this fails, or if opening the file failed, then close the file and 
73692   ** remove the entry from the db->aDb[] array. i.e. put everything back the way
73693   ** we found it.
73694   */
73695   if( rc==SQLITE_OK ){
73696     sqlite3BtreeEnterAll(db);
73697     rc = sqlite3Init(db, &zErrDyn);
73698     sqlite3BtreeLeaveAll(db);
73699   }
73700   if( rc ){
73701     int iDb = db->nDb - 1;
73702     assert( iDb>=2 );
73703     if( db->aDb[iDb].pBt ){
73704       sqlite3BtreeClose(db->aDb[iDb].pBt);
73705       db->aDb[iDb].pBt = 0;
73706       db->aDb[iDb].pSchema = 0;
73707     }
73708     sqlite3ResetInternalSchema(db, 0);
73709     db->nDb = iDb;
73710     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
73711       db->mallocFailed = 1;
73712       sqlite3DbFree(db, zErrDyn);
73713       zErrDyn = sqlite3MPrintf(db, "out of memory");
73714     }else if( zErrDyn==0 ){
73715       zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
73716     }
73717     goto attach_error;
73718   }
73719   
73720   return;
73721
73722 attach_error:
73723   /* Return an error if we get here */
73724   if( zErrDyn ){
73725     sqlite3_result_error(context, zErrDyn, -1);
73726     sqlite3DbFree(db, zErrDyn);
73727   }
73728   if( rc ) sqlite3_result_error_code(context, rc);
73729 }
73730
73731 /*
73732 ** An SQL user-function registered to do the work of an DETACH statement. The
73733 ** three arguments to the function come directly from a detach statement:
73734 **
73735 **     DETACH DATABASE x
73736 **
73737 **     SELECT sqlite_detach(x)
73738 */
73739 static void detachFunc(
73740   sqlite3_context *context,
73741   int NotUsed,
73742   sqlite3_value **argv
73743 ){
73744   const char *zName = (const char *)sqlite3_value_text(argv[0]);
73745   sqlite3 *db = sqlite3_context_db_handle(context);
73746   int i;
73747   Db *pDb = 0;
73748   char zErr[128];
73749
73750   UNUSED_PARAMETER(NotUsed);
73751
73752   if( zName==0 ) zName = "";
73753   for(i=0; i<db->nDb; i++){
73754     pDb = &db->aDb[i];
73755     if( pDb->pBt==0 ) continue;
73756     if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
73757   }
73758
73759   if( i>=db->nDb ){
73760     sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
73761     goto detach_error;
73762   }
73763   if( i<2 ){
73764     sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
73765     goto detach_error;
73766   }
73767   if( !db->autoCommit ){
73768     sqlite3_snprintf(sizeof(zErr), zErr,
73769                      "cannot DETACH database within transaction");
73770     goto detach_error;
73771   }
73772   if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
73773     sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
73774     goto detach_error;
73775   }
73776
73777   sqlite3BtreeClose(pDb->pBt);
73778   pDb->pBt = 0;
73779   pDb->pSchema = 0;
73780   sqlite3ResetInternalSchema(db, 0);
73781   return;
73782
73783 detach_error:
73784   sqlite3_result_error(context, zErr, -1);
73785 }
73786
73787 /*
73788 ** This procedure generates VDBE code for a single invocation of either the
73789 ** sqlite_detach() or sqlite_attach() SQL user functions.
73790 */
73791 static void codeAttach(
73792   Parse *pParse,       /* The parser context */
73793   int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
73794   FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
73795   Expr *pAuthArg,      /* Expression to pass to authorization callback */
73796   Expr *pFilename,     /* Name of database file */
73797   Expr *pDbname,       /* Name of the database to use internally */
73798   Expr *pKey           /* Database key for encryption extension */
73799 ){
73800   int rc;
73801   NameContext sName;
73802   Vdbe *v;
73803   sqlite3* db = pParse->db;
73804   int regArgs;
73805
73806   memset(&sName, 0, sizeof(NameContext));
73807   sName.pParse = pParse;
73808
73809   if( 
73810       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
73811       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
73812       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
73813   ){
73814     pParse->nErr++;
73815     goto attach_end;
73816   }
73817
73818 #ifndef SQLITE_OMIT_AUTHORIZATION
73819   if( pAuthArg ){
73820     char *zAuthArg = pAuthArg->u.zToken;
73821     if( NEVER(zAuthArg==0) ){
73822       goto attach_end;
73823     }
73824     rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
73825     if(rc!=SQLITE_OK ){
73826       goto attach_end;
73827     }
73828   }
73829 #endif /* SQLITE_OMIT_AUTHORIZATION */
73830
73831
73832   v = sqlite3GetVdbe(pParse);
73833   regArgs = sqlite3GetTempRange(pParse, 4);
73834   sqlite3ExprCode(pParse, pFilename, regArgs);
73835   sqlite3ExprCode(pParse, pDbname, regArgs+1);
73836   sqlite3ExprCode(pParse, pKey, regArgs+2);
73837
73838   assert( v || db->mallocFailed );
73839   if( v ){
73840     sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
73841     assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
73842     sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
73843     sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
73844
73845     /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
73846     ** statement only). For DETACH, set it to false (expire all existing
73847     ** statements).
73848     */
73849     sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
73850   }
73851   
73852 attach_end:
73853   sqlite3ExprDelete(db, pFilename);
73854   sqlite3ExprDelete(db, pDbname);
73855   sqlite3ExprDelete(db, pKey);
73856 }
73857
73858 /*
73859 ** Called by the parser to compile a DETACH statement.
73860 **
73861 **     DETACH pDbname
73862 */
73863 SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
73864   static const FuncDef detach_func = {
73865     1,                /* nArg */
73866     SQLITE_UTF8,      /* iPrefEnc */
73867     0,                /* flags */
73868     0,                /* pUserData */
73869     0,                /* pNext */
73870     detachFunc,       /* xFunc */
73871     0,                /* xStep */
73872     0,                /* xFinalize */
73873     "sqlite_detach",  /* zName */
73874     0,                /* pHash */
73875     0                 /* pDestructor */
73876   };
73877   codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
73878 }
73879
73880 /*
73881 ** Called by the parser to compile an ATTACH statement.
73882 **
73883 **     ATTACH p AS pDbname KEY pKey
73884 */
73885 SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
73886   static const FuncDef attach_func = {
73887     3,                /* nArg */
73888     SQLITE_UTF8,      /* iPrefEnc */
73889     0,                /* flags */
73890     0,                /* pUserData */
73891     0,                /* pNext */
73892     attachFunc,       /* xFunc */
73893     0,                /* xStep */
73894     0,                /* xFinalize */
73895     "sqlite_attach",  /* zName */
73896     0,                /* pHash */
73897     0                 /* pDestructor */
73898   };
73899   codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
73900 }
73901 #endif /* SQLITE_OMIT_ATTACH */
73902
73903 /*
73904 ** Initialize a DbFixer structure.  This routine must be called prior
73905 ** to passing the structure to one of the sqliteFixAAAA() routines below.
73906 **
73907 ** The return value indicates whether or not fixation is required.  TRUE
73908 ** means we do need to fix the database references, FALSE means we do not.
73909 */
73910 SQLITE_PRIVATE int sqlite3FixInit(
73911   DbFixer *pFix,      /* The fixer to be initialized */
73912   Parse *pParse,      /* Error messages will be written here */
73913   int iDb,            /* This is the database that must be used */
73914   const char *zType,  /* "view", "trigger", or "index" */
73915   const Token *pName  /* Name of the view, trigger, or index */
73916 ){
73917   sqlite3 *db;
73918
73919   if( NEVER(iDb<0) || iDb==1 ) return 0;
73920   db = pParse->db;
73921   assert( db->nDb>iDb );
73922   pFix->pParse = pParse;
73923   pFix->zDb = db->aDb[iDb].zName;
73924   pFix->zType = zType;
73925   pFix->pName = pName;
73926   return 1;
73927 }
73928
73929 /*
73930 ** The following set of routines walk through the parse tree and assign
73931 ** a specific database to all table references where the database name
73932 ** was left unspecified in the original SQL statement.  The pFix structure
73933 ** must have been initialized by a prior call to sqlite3FixInit().
73934 **
73935 ** These routines are used to make sure that an index, trigger, or
73936 ** view in one database does not refer to objects in a different database.
73937 ** (Exception: indices, triggers, and views in the TEMP database are
73938 ** allowed to refer to anything.)  If a reference is explicitly made
73939 ** to an object in a different database, an error message is added to
73940 ** pParse->zErrMsg and these routines return non-zero.  If everything
73941 ** checks out, these routines return 0.
73942 */
73943 SQLITE_PRIVATE int sqlite3FixSrcList(
73944   DbFixer *pFix,       /* Context of the fixation */
73945   SrcList *pList       /* The Source list to check and modify */
73946 ){
73947   int i;
73948   const char *zDb;
73949   struct SrcList_item *pItem;
73950
73951   if( NEVER(pList==0) ) return 0;
73952   zDb = pFix->zDb;
73953   for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
73954     if( pItem->zDatabase==0 ){
73955       pItem->zDatabase = sqlite3DbStrDup(pFix->pParse->db, zDb);
73956     }else if( sqlite3StrICmp(pItem->zDatabase,zDb)!=0 ){
73957       sqlite3ErrorMsg(pFix->pParse,
73958          "%s %T cannot reference objects in database %s",
73959          pFix->zType, pFix->pName, pItem->zDatabase);
73960       return 1;
73961     }
73962 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
73963     if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
73964     if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
73965 #endif
73966   }
73967   return 0;
73968 }
73969 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
73970 SQLITE_PRIVATE int sqlite3FixSelect(
73971   DbFixer *pFix,       /* Context of the fixation */
73972   Select *pSelect      /* The SELECT statement to be fixed to one database */
73973 ){
73974   while( pSelect ){
73975     if( sqlite3FixExprList(pFix, pSelect->pEList) ){
73976       return 1;
73977     }
73978     if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
73979       return 1;
73980     }
73981     if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
73982       return 1;
73983     }
73984     if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
73985       return 1;
73986     }
73987     pSelect = pSelect->pPrior;
73988   }
73989   return 0;
73990 }
73991 SQLITE_PRIVATE int sqlite3FixExpr(
73992   DbFixer *pFix,     /* Context of the fixation */
73993   Expr *pExpr        /* The expression to be fixed to one database */
73994 ){
73995   while( pExpr ){
73996     if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ) break;
73997     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
73998       if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
73999     }else{
74000       if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
74001     }
74002     if( sqlite3FixExpr(pFix, pExpr->pRight) ){
74003       return 1;
74004     }
74005     pExpr = pExpr->pLeft;
74006   }
74007   return 0;
74008 }
74009 SQLITE_PRIVATE int sqlite3FixExprList(
74010   DbFixer *pFix,     /* Context of the fixation */
74011   ExprList *pList    /* The expression to be fixed to one database */
74012 ){
74013   int i;
74014   struct ExprList_item *pItem;
74015   if( pList==0 ) return 0;
74016   for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
74017     if( sqlite3FixExpr(pFix, pItem->pExpr) ){
74018       return 1;
74019     }
74020   }
74021   return 0;
74022 }
74023 #endif
74024
74025 #ifndef SQLITE_OMIT_TRIGGER
74026 SQLITE_PRIVATE int sqlite3FixTriggerStep(
74027   DbFixer *pFix,     /* Context of the fixation */
74028   TriggerStep *pStep /* The trigger step be fixed to one database */
74029 ){
74030   while( pStep ){
74031     if( sqlite3FixSelect(pFix, pStep->pSelect) ){
74032       return 1;
74033     }
74034     if( sqlite3FixExpr(pFix, pStep->pWhere) ){
74035       return 1;
74036     }
74037     if( sqlite3FixExprList(pFix, pStep->pExprList) ){
74038       return 1;
74039     }
74040     pStep = pStep->pNext;
74041   }
74042   return 0;
74043 }
74044 #endif
74045
74046 /************** End of attach.c **********************************************/
74047 /************** Begin file auth.c ********************************************/
74048 /*
74049 ** 2003 January 11
74050 **
74051 ** The author disclaims copyright to this source code.  In place of
74052 ** a legal notice, here is a blessing:
74053 **
74054 **    May you do good and not evil.
74055 **    May you find forgiveness for yourself and forgive others.
74056 **    May you share freely, never taking more than you give.
74057 **
74058 *************************************************************************
74059 ** This file contains code used to implement the sqlite3_set_authorizer()
74060 ** API.  This facility is an optional feature of the library.  Embedded
74061 ** systems that do not need this facility may omit it by recompiling
74062 ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
74063 */
74064
74065 /*
74066 ** All of the code in this file may be omitted by defining a single
74067 ** macro.
74068 */
74069 #ifndef SQLITE_OMIT_AUTHORIZATION
74070
74071 /*
74072 ** Set or clear the access authorization function.
74073 **
74074 ** The access authorization function is be called during the compilation
74075 ** phase to verify that the user has read and/or write access permission on
74076 ** various fields of the database.  The first argument to the auth function
74077 ** is a copy of the 3rd argument to this routine.  The second argument
74078 ** to the auth function is one of these constants:
74079 **
74080 **       SQLITE_CREATE_INDEX
74081 **       SQLITE_CREATE_TABLE
74082 **       SQLITE_CREATE_TEMP_INDEX
74083 **       SQLITE_CREATE_TEMP_TABLE
74084 **       SQLITE_CREATE_TEMP_TRIGGER
74085 **       SQLITE_CREATE_TEMP_VIEW
74086 **       SQLITE_CREATE_TRIGGER
74087 **       SQLITE_CREATE_VIEW
74088 **       SQLITE_DELETE
74089 **       SQLITE_DROP_INDEX
74090 **       SQLITE_DROP_TABLE
74091 **       SQLITE_DROP_TEMP_INDEX
74092 **       SQLITE_DROP_TEMP_TABLE
74093 **       SQLITE_DROP_TEMP_TRIGGER
74094 **       SQLITE_DROP_TEMP_VIEW
74095 **       SQLITE_DROP_TRIGGER
74096 **       SQLITE_DROP_VIEW
74097 **       SQLITE_INSERT
74098 **       SQLITE_PRAGMA
74099 **       SQLITE_READ
74100 **       SQLITE_SELECT
74101 **       SQLITE_TRANSACTION
74102 **       SQLITE_UPDATE
74103 **
74104 ** The third and fourth arguments to the auth function are the name of
74105 ** the table and the column that are being accessed.  The auth function
74106 ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE.  If
74107 ** SQLITE_OK is returned, it means that access is allowed.  SQLITE_DENY
74108 ** means that the SQL statement will never-run - the sqlite3_exec() call
74109 ** will return with an error.  SQLITE_IGNORE means that the SQL statement
74110 ** should run but attempts to read the specified column will return NULL
74111 ** and attempts to write the column will be ignored.
74112 **
74113 ** Setting the auth function to NULL disables this hook.  The default
74114 ** setting of the auth function is NULL.
74115 */
74116 SQLITE_API int sqlite3_set_authorizer(
74117   sqlite3 *db,
74118   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
74119   void *pArg
74120 ){
74121   sqlite3_mutex_enter(db->mutex);
74122   db->xAuth = xAuth;
74123   db->pAuthArg = pArg;
74124   sqlite3ExpirePreparedStatements(db);
74125   sqlite3_mutex_leave(db->mutex);
74126   return SQLITE_OK;
74127 }
74128
74129 /*
74130 ** Write an error message into pParse->zErrMsg that explains that the
74131 ** user-supplied authorization function returned an illegal value.
74132 */
74133 static void sqliteAuthBadReturnCode(Parse *pParse){
74134   sqlite3ErrorMsg(pParse, "authorizer malfunction");
74135   pParse->rc = SQLITE_ERROR;
74136 }
74137
74138 /*
74139 ** Invoke the authorization callback for permission to read column zCol from
74140 ** table zTab in database zDb. This function assumes that an authorization
74141 ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
74142 **
74143 ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
74144 ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
74145 ** is treated as SQLITE_DENY. In this case an error is left in pParse.
74146 */
74147 SQLITE_PRIVATE int sqlite3AuthReadCol(
74148   Parse *pParse,                  /* The parser context */
74149   const char *zTab,               /* Table name */
74150   const char *zCol,               /* Column name */
74151   int iDb                         /* Index of containing database. */
74152 ){
74153   sqlite3 *db = pParse->db;       /* Database handle */
74154   char *zDb = db->aDb[iDb].zName; /* Name of attached database */
74155   int rc;                         /* Auth callback return code */
74156
74157   rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext);
74158   if( rc==SQLITE_DENY ){
74159     if( db->nDb>2 || iDb!=0 ){
74160       sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
74161     }else{
74162       sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
74163     }
74164     pParse->rc = SQLITE_AUTH;
74165   }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
74166     sqliteAuthBadReturnCode(pParse);
74167   }
74168   return rc;
74169 }
74170
74171 /*
74172 ** The pExpr should be a TK_COLUMN expression.  The table referred to
74173 ** is in pTabList or else it is the NEW or OLD table of a trigger.  
74174 ** Check to see if it is OK to read this particular column.
74175 **
74176 ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN 
74177 ** instruction into a TK_NULL.  If the auth function returns SQLITE_DENY,
74178 ** then generate an error.
74179 */
74180 SQLITE_PRIVATE void sqlite3AuthRead(
74181   Parse *pParse,        /* The parser context */
74182   Expr *pExpr,          /* The expression to check authorization on */
74183   Schema *pSchema,      /* The schema of the expression */
74184   SrcList *pTabList     /* All table that pExpr might refer to */
74185 ){
74186   sqlite3 *db = pParse->db;
74187   Table *pTab = 0;      /* The table being read */
74188   const char *zCol;     /* Name of the column of the table */
74189   int iSrc;             /* Index in pTabList->a[] of table being read */
74190   int iDb;              /* The index of the database the expression refers to */
74191   int iCol;             /* Index of column in table */
74192
74193   if( db->xAuth==0 ) return;
74194   iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
74195   if( iDb<0 ){
74196     /* An attempt to read a column out of a subquery or other
74197     ** temporary table. */
74198     return;
74199   }
74200
74201   assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
74202   if( pExpr->op==TK_TRIGGER ){
74203     pTab = pParse->pTriggerTab;
74204   }else{
74205     assert( pTabList );
74206     for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
74207       if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
74208         pTab = pTabList->a[iSrc].pTab;
74209         break;
74210       }
74211     }
74212   }
74213   iCol = pExpr->iColumn;
74214   if( NEVER(pTab==0) ) return;
74215
74216   if( iCol>=0 ){
74217     assert( iCol<pTab->nCol );
74218     zCol = pTab->aCol[iCol].zName;
74219   }else if( pTab->iPKey>=0 ){
74220     assert( pTab->iPKey<pTab->nCol );
74221     zCol = pTab->aCol[pTab->iPKey].zName;
74222   }else{
74223     zCol = "ROWID";
74224   }
74225   assert( iDb>=0 && iDb<db->nDb );
74226   if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
74227     pExpr->op = TK_NULL;
74228   }
74229 }
74230
74231 /*
74232 ** Do an authorization check using the code and arguments given.  Return
74233 ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY.  If SQLITE_DENY
74234 ** is returned, then the error count and error message in pParse are
74235 ** modified appropriately.
74236 */
74237 SQLITE_PRIVATE int sqlite3AuthCheck(
74238   Parse *pParse,
74239   int code,
74240   const char *zArg1,
74241   const char *zArg2,
74242   const char *zArg3
74243 ){
74244   sqlite3 *db = pParse->db;
74245   int rc;
74246
74247   /* Don't do any authorization checks if the database is initialising
74248   ** or if the parser is being invoked from within sqlite3_declare_vtab.
74249   */
74250   if( db->init.busy || IN_DECLARE_VTAB ){
74251     return SQLITE_OK;
74252   }
74253
74254   if( db->xAuth==0 ){
74255     return SQLITE_OK;
74256   }
74257   rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
74258   if( rc==SQLITE_DENY ){
74259     sqlite3ErrorMsg(pParse, "not authorized");
74260     pParse->rc = SQLITE_AUTH;
74261   }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
74262     rc = SQLITE_DENY;
74263     sqliteAuthBadReturnCode(pParse);
74264   }
74265   return rc;
74266 }
74267
74268 /*
74269 ** Push an authorization context.  After this routine is called, the
74270 ** zArg3 argument to authorization callbacks will be zContext until
74271 ** popped.  Or if pParse==0, this routine is a no-op.
74272 */
74273 SQLITE_PRIVATE void sqlite3AuthContextPush(
74274   Parse *pParse,
74275   AuthContext *pContext, 
74276   const char *zContext
74277 ){
74278   assert( pParse );
74279   pContext->pParse = pParse;
74280   pContext->zAuthContext = pParse->zAuthContext;
74281   pParse->zAuthContext = zContext;
74282 }
74283
74284 /*
74285 ** Pop an authorization context that was previously pushed
74286 ** by sqlite3AuthContextPush
74287 */
74288 SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
74289   if( pContext->pParse ){
74290     pContext->pParse->zAuthContext = pContext->zAuthContext;
74291     pContext->pParse = 0;
74292   }
74293 }
74294
74295 #endif /* SQLITE_OMIT_AUTHORIZATION */
74296
74297 /************** End of auth.c ************************************************/
74298 /************** Begin file build.c *******************************************/
74299 /*
74300 ** 2001 September 15
74301 **
74302 ** The author disclaims copyright to this source code.  In place of
74303 ** a legal notice, here is a blessing:
74304 **
74305 **    May you do good and not evil.
74306 **    May you find forgiveness for yourself and forgive others.
74307 **    May you share freely, never taking more than you give.
74308 **
74309 *************************************************************************
74310 ** This file contains C code routines that are called by the SQLite parser
74311 ** when syntax rules are reduced.  The routines in this file handle the
74312 ** following kinds of SQL syntax:
74313 **
74314 **     CREATE TABLE
74315 **     DROP TABLE
74316 **     CREATE INDEX
74317 **     DROP INDEX
74318 **     creating ID lists
74319 **     BEGIN TRANSACTION
74320 **     COMMIT
74321 **     ROLLBACK
74322 */
74323
74324 /*
74325 ** This routine is called when a new SQL statement is beginning to
74326 ** be parsed.  Initialize the pParse structure as needed.
74327 */
74328 SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
74329   pParse->explain = (u8)explainFlag;
74330   pParse->nVar = 0;
74331 }
74332
74333 #ifndef SQLITE_OMIT_SHARED_CACHE
74334 /*
74335 ** The TableLock structure is only used by the sqlite3TableLock() and
74336 ** codeTableLocks() functions.
74337 */
74338 struct TableLock {
74339   int iDb;             /* The database containing the table to be locked */
74340   int iTab;            /* The root page of the table to be locked */
74341   u8 isWriteLock;      /* True for write lock.  False for a read lock */
74342   const char *zName;   /* Name of the table */
74343 };
74344
74345 /*
74346 ** Record the fact that we want to lock a table at run-time.  
74347 **
74348 ** The table to be locked has root page iTab and is found in database iDb.
74349 ** A read or a write lock can be taken depending on isWritelock.
74350 **
74351 ** This routine just records the fact that the lock is desired.  The
74352 ** code to make the lock occur is generated by a later call to
74353 ** codeTableLocks() which occurs during sqlite3FinishCoding().
74354 */
74355 SQLITE_PRIVATE void sqlite3TableLock(
74356   Parse *pParse,     /* Parsing context */
74357   int iDb,           /* Index of the database containing the table to lock */
74358   int iTab,          /* Root page number of the table to be locked */
74359   u8 isWriteLock,    /* True for a write lock */
74360   const char *zName  /* Name of the table to be locked */
74361 ){
74362   Parse *pToplevel = sqlite3ParseToplevel(pParse);
74363   int i;
74364   int nBytes;
74365   TableLock *p;
74366   assert( iDb>=0 );
74367
74368   for(i=0; i<pToplevel->nTableLock; i++){
74369     p = &pToplevel->aTableLock[i];
74370     if( p->iDb==iDb && p->iTab==iTab ){
74371       p->isWriteLock = (p->isWriteLock || isWriteLock);
74372       return;
74373     }
74374   }
74375
74376   nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
74377   pToplevel->aTableLock =
74378       sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
74379   if( pToplevel->aTableLock ){
74380     p = &pToplevel->aTableLock[pToplevel->nTableLock++];
74381     p->iDb = iDb;
74382     p->iTab = iTab;
74383     p->isWriteLock = isWriteLock;
74384     p->zName = zName;
74385   }else{
74386     pToplevel->nTableLock = 0;
74387     pToplevel->db->mallocFailed = 1;
74388   }
74389 }
74390
74391 /*
74392 ** Code an OP_TableLock instruction for each table locked by the
74393 ** statement (configured by calls to sqlite3TableLock()).
74394 */
74395 static void codeTableLocks(Parse *pParse){
74396   int i;
74397   Vdbe *pVdbe; 
74398
74399   pVdbe = sqlite3GetVdbe(pParse);
74400   assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
74401
74402   for(i=0; i<pParse->nTableLock; i++){
74403     TableLock *p = &pParse->aTableLock[i];
74404     int p1 = p->iDb;
74405     sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
74406                       p->zName, P4_STATIC);
74407   }
74408 }
74409 #else
74410   #define codeTableLocks(x)
74411 #endif
74412
74413 /*
74414 ** This routine is called after a single SQL statement has been
74415 ** parsed and a VDBE program to execute that statement has been
74416 ** prepared.  This routine puts the finishing touches on the
74417 ** VDBE program and resets the pParse structure for the next
74418 ** parse.
74419 **
74420 ** Note that if an error occurred, it might be the case that
74421 ** no VDBE code was generated.
74422 */
74423 SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
74424   sqlite3 *db;
74425   Vdbe *v;
74426
74427   db = pParse->db;
74428   if( db->mallocFailed ) return;
74429   if( pParse->nested ) return;
74430   if( pParse->nErr ) return;
74431
74432   /* Begin by generating some termination code at the end of the
74433   ** vdbe program
74434   */
74435   v = sqlite3GetVdbe(pParse);
74436   assert( !pParse->isMultiWrite 
74437        || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
74438   if( v ){
74439     sqlite3VdbeAddOp0(v, OP_Halt);
74440
74441     /* The cookie mask contains one bit for each database file open.
74442     ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
74443     ** set for each database that is used.  Generate code to start a
74444     ** transaction on each used database and to verify the schema cookie
74445     ** on each used database.
74446     */
74447     if( pParse->cookieGoto>0 ){
74448       u32 mask;
74449       int iDb;
74450       sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
74451       for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
74452         if( (mask & pParse->cookieMask)==0 ) continue;
74453         sqlite3VdbeUsesBtree(v, iDb);
74454         sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
74455         if( db->init.busy==0 ){
74456           sqlite3VdbeAddOp2(v,OP_VerifyCookie, iDb, pParse->cookieValue[iDb]);
74457         }
74458       }
74459 #ifndef SQLITE_OMIT_VIRTUALTABLE
74460       {
74461         int i;
74462         for(i=0; i<pParse->nVtabLock; i++){
74463           char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
74464           sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
74465         }
74466         pParse->nVtabLock = 0;
74467       }
74468 #endif
74469
74470       /* Once all the cookies have been verified and transactions opened, 
74471       ** obtain the required table-locks. This is a no-op unless the 
74472       ** shared-cache feature is enabled.
74473       */
74474       codeTableLocks(pParse);
74475
74476       /* Initialize any AUTOINCREMENT data structures required.
74477       */
74478       sqlite3AutoincrementBegin(pParse);
74479
74480       /* Finally, jump back to the beginning of the executable code. */
74481       sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
74482     }
74483   }
74484
74485
74486   /* Get the VDBE program ready for execution
74487   */
74488   if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
74489 #ifdef SQLITE_DEBUG
74490     FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
74491     sqlite3VdbeTrace(v, trace);
74492 #endif
74493     assert( pParse->iCacheLevel==0 );  /* Disables and re-enables match */
74494     /* A minimum of one cursor is required if autoincrement is used
74495     *  See ticket [a696379c1f08866] */
74496     if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
74497     sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem,
74498                          pParse->nTab, pParse->nMaxArg, pParse->explain,
74499                          pParse->isMultiWrite && pParse->mayAbort);
74500     pParse->rc = SQLITE_DONE;
74501     pParse->colNamesSet = 0;
74502   }else{
74503     pParse->rc = SQLITE_ERROR;
74504   }
74505   pParse->nTab = 0;
74506   pParse->nMem = 0;
74507   pParse->nSet = 0;
74508   pParse->nVar = 0;
74509   pParse->cookieMask = 0;
74510   pParse->cookieGoto = 0;
74511 }
74512
74513 /*
74514 ** Run the parser and code generator recursively in order to generate
74515 ** code for the SQL statement given onto the end of the pParse context
74516 ** currently under construction.  When the parser is run recursively
74517 ** this way, the final OP_Halt is not appended and other initialization
74518 ** and finalization steps are omitted because those are handling by the
74519 ** outermost parser.
74520 **
74521 ** Not everything is nestable.  This facility is designed to permit
74522 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
74523 ** care if you decide to try to use this routine for some other purposes.
74524 */
74525 SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
74526   va_list ap;
74527   char *zSql;
74528   char *zErrMsg = 0;
74529   sqlite3 *db = pParse->db;
74530 # define SAVE_SZ  (sizeof(Parse) - offsetof(Parse,nVar))
74531   char saveBuf[SAVE_SZ];
74532
74533   if( pParse->nErr ) return;
74534   assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
74535   va_start(ap, zFormat);
74536   zSql = sqlite3VMPrintf(db, zFormat, ap);
74537   va_end(ap);
74538   if( zSql==0 ){
74539     return;   /* A malloc must have failed */
74540   }
74541   pParse->nested++;
74542   memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
74543   memset(&pParse->nVar, 0, SAVE_SZ);
74544   sqlite3RunParser(pParse, zSql, &zErrMsg);
74545   sqlite3DbFree(db, zErrMsg);
74546   sqlite3DbFree(db, zSql);
74547   memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
74548   pParse->nested--;
74549 }
74550
74551 /*
74552 ** Locate the in-memory structure that describes a particular database
74553 ** table given the name of that table and (optionally) the name of the
74554 ** database containing the table.  Return NULL if not found.
74555 **
74556 ** If zDatabase is 0, all databases are searched for the table and the
74557 ** first matching table is returned.  (No checking for duplicate table
74558 ** names is done.)  The search order is TEMP first, then MAIN, then any
74559 ** auxiliary databases added using the ATTACH command.
74560 **
74561 ** See also sqlite3LocateTable().
74562 */
74563 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
74564   Table *p = 0;
74565   int i;
74566   int nName;
74567   assert( zName!=0 );
74568   nName = sqlite3Strlen30(zName);
74569   for(i=OMIT_TEMPDB; i<db->nDb; i++){
74570     int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
74571     if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
74572     p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
74573     if( p ) break;
74574   }
74575   return p;
74576 }
74577
74578 /*
74579 ** Locate the in-memory structure that describes a particular database
74580 ** table given the name of that table and (optionally) the name of the
74581 ** database containing the table.  Return NULL if not found.  Also leave an
74582 ** error message in pParse->zErrMsg.
74583 **
74584 ** The difference between this routine and sqlite3FindTable() is that this
74585 ** routine leaves an error message in pParse->zErrMsg where
74586 ** sqlite3FindTable() does not.
74587 */
74588 SQLITE_PRIVATE Table *sqlite3LocateTable(
74589   Parse *pParse,         /* context in which to report errors */
74590   int isView,            /* True if looking for a VIEW rather than a TABLE */
74591   const char *zName,     /* Name of the table we are looking for */
74592   const char *zDbase     /* Name of the database.  Might be NULL */
74593 ){
74594   Table *p;
74595
74596   /* Read the database schema. If an error occurs, leave an error message
74597   ** and code in pParse and return NULL. */
74598   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
74599     return 0;
74600   }
74601
74602   p = sqlite3FindTable(pParse->db, zName, zDbase);
74603   if( p==0 ){
74604     const char *zMsg = isView ? "no such view" : "no such table";
74605     if( zDbase ){
74606       sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
74607     }else{
74608       sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
74609     }
74610     pParse->checkSchema = 1;
74611   }
74612   return p;
74613 }
74614
74615 /*
74616 ** Locate the in-memory structure that describes 
74617 ** a particular index given the name of that index
74618 ** and the name of the database that contains the index.
74619 ** Return NULL if not found.
74620 **
74621 ** If zDatabase is 0, all databases are searched for the
74622 ** table and the first matching index is returned.  (No checking
74623 ** for duplicate index names is done.)  The search order is
74624 ** TEMP first, then MAIN, then any auxiliary databases added
74625 ** using the ATTACH command.
74626 */
74627 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
74628   Index *p = 0;
74629   int i;
74630   int nName = sqlite3Strlen30(zName);
74631   for(i=OMIT_TEMPDB; i<db->nDb; i++){
74632     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
74633     Schema *pSchema = db->aDb[j].pSchema;
74634     assert( pSchema );
74635     if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
74636     p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
74637     if( p ) break;
74638   }
74639   return p;
74640 }
74641
74642 /*
74643 ** Reclaim the memory used by an index
74644 */
74645 static void freeIndex(sqlite3 *db, Index *p){
74646 #ifndef SQLITE_OMIT_ANALYZE
74647   sqlite3DeleteIndexSamples(db, p);
74648 #endif
74649   sqlite3DbFree(db, p->zColAff);
74650   sqlite3DbFree(db, p);
74651 }
74652
74653 /*
74654 ** For the index called zIdxName which is found in the database iDb,
74655 ** unlike that index from its Table then remove the index from
74656 ** the index hash table and free all memory structures associated
74657 ** with the index.
74658 */
74659 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
74660   Index *pIndex;
74661   int len;
74662   Hash *pHash = &db->aDb[iDb].pSchema->idxHash;
74663
74664   len = sqlite3Strlen30(zIdxName);
74665   pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
74666   if( pIndex ){
74667     if( pIndex->pTable->pIndex==pIndex ){
74668       pIndex->pTable->pIndex = pIndex->pNext;
74669     }else{
74670       Index *p;
74671       /* Justification of ALWAYS();  The index must be on the list of
74672       ** indices. */
74673       p = pIndex->pTable->pIndex;
74674       while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
74675       if( ALWAYS(p && p->pNext==pIndex) ){
74676         p->pNext = pIndex->pNext;
74677       }
74678     }
74679     freeIndex(db, pIndex);
74680   }
74681   db->flags |= SQLITE_InternChanges;
74682 }
74683
74684 /*
74685 ** Erase all schema information from the in-memory hash tables of
74686 ** a single database.  This routine is called to reclaim memory
74687 ** before the database closes.  It is also called during a rollback
74688 ** if there were schema changes during the transaction or if a
74689 ** schema-cookie mismatch occurs.
74690 **
74691 ** If iDb==0 then reset the internal schema tables for all database
74692 ** files.  If iDb>=1 then reset the internal schema for only the
74693 ** single file indicated.
74694 */
74695 SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
74696   int i, j;
74697   assert( iDb>=0 && iDb<db->nDb );
74698
74699   if( iDb==0 ){
74700     sqlite3BtreeEnterAll(db);
74701   }
74702   for(i=iDb; i<db->nDb; i++){
74703     Db *pDb = &db->aDb[i];
74704     if( pDb->pSchema ){
74705       assert(i==1 || (pDb->pBt && sqlite3BtreeHoldsMutex(pDb->pBt)));
74706       sqlite3SchemaFree(pDb->pSchema);
74707     }
74708     if( iDb>0 ) return;
74709   }
74710   assert( iDb==0 );
74711   db->flags &= ~SQLITE_InternChanges;
74712   sqlite3VtabUnlockList(db);
74713   sqlite3BtreeLeaveAll(db);
74714
74715   /* If one or more of the auxiliary database files has been closed,
74716   ** then remove them from the auxiliary database list.  We take the
74717   ** opportunity to do this here since we have just deleted all of the
74718   ** schema hash tables and therefore do not have to make any changes
74719   ** to any of those tables.
74720   */
74721   for(i=j=2; i<db->nDb; i++){
74722     struct Db *pDb = &db->aDb[i];
74723     if( pDb->pBt==0 ){
74724       sqlite3DbFree(db, pDb->zName);
74725       pDb->zName = 0;
74726       continue;
74727     }
74728     if( j<i ){
74729       db->aDb[j] = db->aDb[i];
74730     }
74731     j++;
74732   }
74733   memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
74734   db->nDb = j;
74735   if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
74736     memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
74737     sqlite3DbFree(db, db->aDb);
74738     db->aDb = db->aDbStatic;
74739   }
74740 }
74741
74742 /*
74743 ** This routine is called when a commit occurs.
74744 */
74745 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
74746   db->flags &= ~SQLITE_InternChanges;
74747 }
74748
74749 /*
74750 ** Delete memory allocated for the column names of a table or view (the
74751 ** Table.aCol[] array).
74752 */
74753 static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
74754   int i;
74755   Column *pCol;
74756   assert( pTable!=0 );
74757   if( (pCol = pTable->aCol)!=0 ){
74758     for(i=0; i<pTable->nCol; i++, pCol++){
74759       sqlite3DbFree(db, pCol->zName);
74760       sqlite3ExprDelete(db, pCol->pDflt);
74761       sqlite3DbFree(db, pCol->zDflt);
74762       sqlite3DbFree(db, pCol->zType);
74763       sqlite3DbFree(db, pCol->zColl);
74764     }
74765     sqlite3DbFree(db, pTable->aCol);
74766   }
74767 }
74768
74769 /*
74770 ** Remove the memory data structures associated with the given
74771 ** Table.  No changes are made to disk by this routine.
74772 **
74773 ** This routine just deletes the data structure.  It does not unlink
74774 ** the table data structure from the hash table.  But it does destroy
74775 ** memory structures of the indices and foreign keys associated with 
74776 ** the table.
74777 */
74778 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
74779   Index *pIndex, *pNext;
74780
74781   assert( !pTable || pTable->nRef>0 );
74782
74783   /* Do not delete the table until the reference count reaches zero. */
74784   if( !pTable ) return;
74785   if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
74786
74787   /* Delete all indices associated with this table. */
74788   for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
74789     pNext = pIndex->pNext;
74790     assert( pIndex->pSchema==pTable->pSchema );
74791     if( !db || db->pnBytesFreed==0 ){
74792       char *zName = pIndex->zName; 
74793       TESTONLY ( Index *pOld = ) sqlite3HashInsert(
74794           &pIndex->pSchema->idxHash, zName, sqlite3Strlen30(zName), 0
74795       );
74796       assert( pOld==pIndex || pOld==0 );
74797     }
74798     freeIndex(db, pIndex);
74799   }
74800
74801   /* Delete any foreign keys attached to this table. */
74802   sqlite3FkDelete(db, pTable);
74803
74804   /* Delete the Table structure itself.
74805   */
74806   sqliteDeleteColumnNames(db, pTable);
74807   sqlite3DbFree(db, pTable->zName);
74808   sqlite3DbFree(db, pTable->zColAff);
74809   sqlite3SelectDelete(db, pTable->pSelect);
74810 #ifndef SQLITE_OMIT_CHECK
74811   sqlite3ExprDelete(db, pTable->pCheck);
74812 #endif
74813 #ifndef SQLITE_OMIT_VIRTUALTABLE
74814   sqlite3VtabClear(db, pTable);
74815 #endif
74816   sqlite3DbFree(db, pTable);
74817 }
74818
74819 /*
74820 ** Unlink the given table from the hash tables and the delete the
74821 ** table structure with all its indices and foreign keys.
74822 */
74823 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
74824   Table *p;
74825   Db *pDb;
74826
74827   assert( db!=0 );
74828   assert( iDb>=0 && iDb<db->nDb );
74829   assert( zTabName );
74830   testcase( zTabName[0]==0 );  /* Zero-length table names are allowed */
74831   pDb = &db->aDb[iDb];
74832   p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
74833                         sqlite3Strlen30(zTabName),0);
74834   sqlite3DeleteTable(db, p);
74835   db->flags |= SQLITE_InternChanges;
74836 }
74837
74838 /*
74839 ** Given a token, return a string that consists of the text of that
74840 ** token.  Space to hold the returned string
74841 ** is obtained from sqliteMalloc() and must be freed by the calling
74842 ** function.
74843 **
74844 ** Any quotation marks (ex:  "name", 'name', [name], or `name`) that
74845 ** surround the body of the token are removed.
74846 **
74847 ** Tokens are often just pointers into the original SQL text and so
74848 ** are not \000 terminated and are not persistent.  The returned string
74849 ** is \000 terminated and is persistent.
74850 */
74851 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
74852   char *zName;
74853   if( pName ){
74854     zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
74855     sqlite3Dequote(zName);
74856   }else{
74857     zName = 0;
74858   }
74859   return zName;
74860 }
74861
74862 /*
74863 ** Open the sqlite_master table stored in database number iDb for
74864 ** writing. The table is opened using cursor 0.
74865 */
74866 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
74867   Vdbe *v = sqlite3GetVdbe(p);
74868   sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
74869   sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
74870   sqlite3VdbeChangeP4(v, -1, (char *)5, P4_INT32);  /* 5 column table */
74871   if( p->nTab==0 ){
74872     p->nTab = 1;
74873   }
74874 }
74875
74876 /*
74877 ** Parameter zName points to a nul-terminated buffer containing the name
74878 ** of a database ("main", "temp" or the name of an attached db). This
74879 ** function returns the index of the named database in db->aDb[], or
74880 ** -1 if the named db cannot be found.
74881 */
74882 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
74883   int i = -1;         /* Database number */
74884   if( zName ){
74885     Db *pDb;
74886     int n = sqlite3Strlen30(zName);
74887     for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
74888       if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) && 
74889           0==sqlite3StrICmp(pDb->zName, zName) ){
74890         break;
74891       }
74892     }
74893   }
74894   return i;
74895 }
74896
74897 /*
74898 ** The token *pName contains the name of a database (either "main" or
74899 ** "temp" or the name of an attached db). This routine returns the
74900 ** index of the named database in db->aDb[], or -1 if the named db 
74901 ** does not exist.
74902 */
74903 SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
74904   int i;                               /* Database number */
74905   char *zName;                         /* Name we are searching for */
74906   zName = sqlite3NameFromToken(db, pName);
74907   i = sqlite3FindDbName(db, zName);
74908   sqlite3DbFree(db, zName);
74909   return i;
74910 }
74911
74912 /* The table or view or trigger name is passed to this routine via tokens
74913 ** pName1 and pName2. If the table name was fully qualified, for example:
74914 **
74915 ** CREATE TABLE xxx.yyy (...);
74916 ** 
74917 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
74918 ** the table name is not fully qualified, i.e.:
74919 **
74920 ** CREATE TABLE yyy(...);
74921 **
74922 ** Then pName1 is set to "yyy" and pName2 is "".
74923 **
74924 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
74925 ** pName2) that stores the unqualified table name.  The index of the
74926 ** database "xxx" is returned.
74927 */
74928 SQLITE_PRIVATE int sqlite3TwoPartName(
74929   Parse *pParse,      /* Parsing and code generating context */
74930   Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
74931   Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
74932   Token **pUnqual     /* Write the unqualified object name here */
74933 ){
74934   int iDb;                    /* Database holding the object */
74935   sqlite3 *db = pParse->db;
74936
74937   if( ALWAYS(pName2!=0) && pName2->n>0 ){
74938     if( db->init.busy ) {
74939       sqlite3ErrorMsg(pParse, "corrupt database");
74940       pParse->nErr++;
74941       return -1;
74942     }
74943     *pUnqual = pName2;
74944     iDb = sqlite3FindDb(db, pName1);
74945     if( iDb<0 ){
74946       sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
74947       pParse->nErr++;
74948       return -1;
74949     }
74950   }else{
74951     assert( db->init.iDb==0 || db->init.busy );
74952     iDb = db->init.iDb;
74953     *pUnqual = pName1;
74954   }
74955   return iDb;
74956 }
74957
74958 /*
74959 ** This routine is used to check if the UTF-8 string zName is a legal
74960 ** unqualified name for a new schema object (table, index, view or
74961 ** trigger). All names are legal except those that begin with the string
74962 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
74963 ** is reserved for internal use.
74964 */
74965 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
74966   if( !pParse->db->init.busy && pParse->nested==0 
74967           && (pParse->db->flags & SQLITE_WriteSchema)==0
74968           && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
74969     sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
74970     return SQLITE_ERROR;
74971   }
74972   return SQLITE_OK;
74973 }
74974
74975 /*
74976 ** Begin constructing a new table representation in memory.  This is
74977 ** the first of several action routines that get called in response
74978 ** to a CREATE TABLE statement.  In particular, this routine is called
74979 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
74980 ** flag is true if the table should be stored in the auxiliary database
74981 ** file instead of in the main database file.  This is normally the case
74982 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
74983 ** CREATE and TABLE.
74984 **
74985 ** The new table record is initialized and put in pParse->pNewTable.
74986 ** As more of the CREATE TABLE statement is parsed, additional action
74987 ** routines will be called to add more information to this record.
74988 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
74989 ** is called to complete the construction of the new table record.
74990 */
74991 SQLITE_PRIVATE void sqlite3StartTable(
74992   Parse *pParse,   /* Parser context */
74993   Token *pName1,   /* First part of the name of the table or view */
74994   Token *pName2,   /* Second part of the name of the table or view */
74995   int isTemp,      /* True if this is a TEMP table */
74996   int isView,      /* True if this is a VIEW */
74997   int isVirtual,   /* True if this is a VIRTUAL table */
74998   int noErr        /* Do nothing if table already exists */
74999 ){
75000   Table *pTable;
75001   char *zName = 0; /* The name of the new table */
75002   sqlite3 *db = pParse->db;
75003   Vdbe *v;
75004   int iDb;         /* Database number to create the table in */
75005   Token *pName;    /* Unqualified name of the table to create */
75006
75007   /* The table or view name to create is passed to this routine via tokens
75008   ** pName1 and pName2. If the table name was fully qualified, for example:
75009   **
75010   ** CREATE TABLE xxx.yyy (...);
75011   ** 
75012   ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
75013   ** the table name is not fully qualified, i.e.:
75014   **
75015   ** CREATE TABLE yyy(...);
75016   **
75017   ** Then pName1 is set to "yyy" and pName2 is "".
75018   **
75019   ** The call below sets the pName pointer to point at the token (pName1 or
75020   ** pName2) that stores the unqualified table name. The variable iDb is
75021   ** set to the index of the database that the table or view is to be
75022   ** created in.
75023   */
75024   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
75025   if( iDb<0 ) return;
75026   if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
75027     /* If creating a temp table, the name may not be qualified. Unless 
75028     ** the database name is "temp" anyway.  */
75029     sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
75030     return;
75031   }
75032   if( !OMIT_TEMPDB && isTemp ) iDb = 1;
75033
75034   pParse->sNameToken = *pName;
75035   zName = sqlite3NameFromToken(db, pName);
75036   if( zName==0 ) return;
75037   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
75038     goto begin_table_error;
75039   }
75040   if( db->init.iDb==1 ) isTemp = 1;
75041 #ifndef SQLITE_OMIT_AUTHORIZATION
75042   assert( (isTemp & 1)==isTemp );
75043   {
75044     int code;
75045     char *zDb = db->aDb[iDb].zName;
75046     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
75047       goto begin_table_error;
75048     }
75049     if( isView ){
75050       if( !OMIT_TEMPDB && isTemp ){
75051         code = SQLITE_CREATE_TEMP_VIEW;
75052       }else{
75053         code = SQLITE_CREATE_VIEW;
75054       }
75055     }else{
75056       if( !OMIT_TEMPDB && isTemp ){
75057         code = SQLITE_CREATE_TEMP_TABLE;
75058       }else{
75059         code = SQLITE_CREATE_TABLE;
75060       }
75061     }
75062     if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
75063       goto begin_table_error;
75064     }
75065   }
75066 #endif
75067
75068   /* Make sure the new table name does not collide with an existing
75069   ** index or table name in the same database.  Issue an error message if
75070   ** it does. The exception is if the statement being parsed was passed
75071   ** to an sqlite3_declare_vtab() call. In that case only the column names
75072   ** and types will be used, so there is no need to test for namespace
75073   ** collisions.
75074   */
75075   if( !IN_DECLARE_VTAB ){
75076     char *zDb = db->aDb[iDb].zName;
75077     if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
75078       goto begin_table_error;
75079     }
75080     pTable = sqlite3FindTable(db, zName, zDb);
75081     if( pTable ){
75082       if( !noErr ){
75083         sqlite3ErrorMsg(pParse, "table %T already exists", pName);
75084       }
75085       goto begin_table_error;
75086     }
75087     if( sqlite3FindIndex(db, zName, zDb)!=0 ){
75088       sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
75089       goto begin_table_error;
75090     }
75091   }
75092
75093   pTable = sqlite3DbMallocZero(db, sizeof(Table));
75094   if( pTable==0 ){
75095     db->mallocFailed = 1;
75096     pParse->rc = SQLITE_NOMEM;
75097     pParse->nErr++;
75098     goto begin_table_error;
75099   }
75100   pTable->zName = zName;
75101   pTable->iPKey = -1;
75102   pTable->pSchema = db->aDb[iDb].pSchema;
75103   pTable->nRef = 1;
75104   pTable->nRowEst = 1000000;
75105   assert( pParse->pNewTable==0 );
75106   pParse->pNewTable = pTable;
75107
75108   /* If this is the magic sqlite_sequence table used by autoincrement,
75109   ** then record a pointer to this table in the main database structure
75110   ** so that INSERT can find the table easily.
75111   */
75112 #ifndef SQLITE_OMIT_AUTOINCREMENT
75113   if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
75114     pTable->pSchema->pSeqTab = pTable;
75115   }
75116 #endif
75117
75118   /* Begin generating the code that will insert the table record into
75119   ** the SQLITE_MASTER table.  Note in particular that we must go ahead
75120   ** and allocate the record number for the table entry now.  Before any
75121   ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
75122   ** indices to be created and the table record must come before the 
75123   ** indices.  Hence, the record number for the table must be allocated
75124   ** now.
75125   */
75126   if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
75127     int j1;
75128     int fileFormat;
75129     int reg1, reg2, reg3;
75130     sqlite3BeginWriteOperation(pParse, 0, iDb);
75131
75132 #ifndef SQLITE_OMIT_VIRTUALTABLE
75133     if( isVirtual ){
75134       sqlite3VdbeAddOp0(v, OP_VBegin);
75135     }
75136 #endif
75137
75138     /* If the file format and encoding in the database have not been set, 
75139     ** set them now.
75140     */
75141     reg1 = pParse->regRowid = ++pParse->nMem;
75142     reg2 = pParse->regRoot = ++pParse->nMem;
75143     reg3 = ++pParse->nMem;
75144     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
75145     sqlite3VdbeUsesBtree(v, iDb);
75146     j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
75147     fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
75148                   1 : SQLITE_MAX_FILE_FORMAT;
75149     sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
75150     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
75151     sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
75152     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
75153     sqlite3VdbeJumpHere(v, j1);
75154
75155     /* This just creates a place-holder record in the sqlite_master table.
75156     ** The record created does not contain anything yet.  It will be replaced
75157     ** by the real entry in code generated at sqlite3EndTable().
75158     **
75159     ** The rowid for the new entry is left in register pParse->regRowid.
75160     ** The root page number of the new table is left in reg pParse->regRoot.
75161     ** The rowid and root page number values are needed by the code that
75162     ** sqlite3EndTable will generate.
75163     */
75164 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
75165     if( isView || isVirtual ){
75166       sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
75167     }else
75168 #endif
75169     {
75170       sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
75171     }
75172     sqlite3OpenMasterTable(pParse, iDb);
75173     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
75174     sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
75175     sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
75176     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
75177     sqlite3VdbeAddOp0(v, OP_Close);
75178   }
75179
75180   /* Normal (non-error) return. */
75181   return;
75182
75183   /* If an error occurs, we jump here */
75184 begin_table_error:
75185   sqlite3DbFree(db, zName);
75186   return;
75187 }
75188
75189 /*
75190 ** This macro is used to compare two strings in a case-insensitive manner.
75191 ** It is slightly faster than calling sqlite3StrICmp() directly, but
75192 ** produces larger code.
75193 **
75194 ** WARNING: This macro is not compatible with the strcmp() family. It
75195 ** returns true if the two strings are equal, otherwise false.
75196 */
75197 #define STRICMP(x, y) (\
75198 sqlite3UpperToLower[*(unsigned char *)(x)]==   \
75199 sqlite3UpperToLower[*(unsigned char *)(y)]     \
75200 && sqlite3StrICmp((x)+1,(y)+1)==0 )
75201
75202 /*
75203 ** Add a new column to the table currently being constructed.
75204 **
75205 ** The parser calls this routine once for each column declaration
75206 ** in a CREATE TABLE statement.  sqlite3StartTable() gets called
75207 ** first to get things going.  Then this routine is called for each
75208 ** column.
75209 */
75210 SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
75211   Table *p;
75212   int i;
75213   char *z;
75214   Column *pCol;
75215   sqlite3 *db = pParse->db;
75216   if( (p = pParse->pNewTable)==0 ) return;
75217 #if SQLITE_MAX_COLUMN
75218   if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
75219     sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
75220     return;
75221   }
75222 #endif
75223   z = sqlite3NameFromToken(db, pName);
75224   if( z==0 ) return;
75225   for(i=0; i<p->nCol; i++){
75226     if( STRICMP(z, p->aCol[i].zName) ){
75227       sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
75228       sqlite3DbFree(db, z);
75229       return;
75230     }
75231   }
75232   if( (p->nCol & 0x7)==0 ){
75233     Column *aNew;
75234     aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
75235     if( aNew==0 ){
75236       sqlite3DbFree(db, z);
75237       return;
75238     }
75239     p->aCol = aNew;
75240   }
75241   pCol = &p->aCol[p->nCol];
75242   memset(pCol, 0, sizeof(p->aCol[0]));
75243   pCol->zName = z;
75244  
75245   /* If there is no type specified, columns have the default affinity
75246   ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
75247   ** be called next to set pCol->affinity correctly.
75248   */
75249   pCol->affinity = SQLITE_AFF_NONE;
75250   p->nCol++;
75251 }
75252
75253 /*
75254 ** This routine is called by the parser while in the middle of
75255 ** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
75256 ** been seen on a column.  This routine sets the notNull flag on
75257 ** the column currently under construction.
75258 */
75259 SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
75260   Table *p;
75261   p = pParse->pNewTable;
75262   if( p==0 || NEVER(p->nCol<1) ) return;
75263   p->aCol[p->nCol-1].notNull = (u8)onError;
75264 }
75265
75266 /*
75267 ** Scan the column type name zType (length nType) and return the
75268 ** associated affinity type.
75269 **
75270 ** This routine does a case-independent search of zType for the 
75271 ** substrings in the following table. If one of the substrings is
75272 ** found, the corresponding affinity is returned. If zType contains
75273 ** more than one of the substrings, entries toward the top of 
75274 ** the table take priority. For example, if zType is 'BLOBINT', 
75275 ** SQLITE_AFF_INTEGER is returned.
75276 **
75277 ** Substring     | Affinity
75278 ** --------------------------------
75279 ** 'INT'         | SQLITE_AFF_INTEGER
75280 ** 'CHAR'        | SQLITE_AFF_TEXT
75281 ** 'CLOB'        | SQLITE_AFF_TEXT
75282 ** 'TEXT'        | SQLITE_AFF_TEXT
75283 ** 'BLOB'        | SQLITE_AFF_NONE
75284 ** 'REAL'        | SQLITE_AFF_REAL
75285 ** 'FLOA'        | SQLITE_AFF_REAL
75286 ** 'DOUB'        | SQLITE_AFF_REAL
75287 **
75288 ** If none of the substrings in the above table are found,
75289 ** SQLITE_AFF_NUMERIC is returned.
75290 */
75291 SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn){
75292   u32 h = 0;
75293   char aff = SQLITE_AFF_NUMERIC;
75294
75295   if( zIn ) while( zIn[0] ){
75296     h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
75297     zIn++;
75298     if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
75299       aff = SQLITE_AFF_TEXT; 
75300     }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
75301       aff = SQLITE_AFF_TEXT;
75302     }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
75303       aff = SQLITE_AFF_TEXT;
75304     }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
75305         && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
75306       aff = SQLITE_AFF_NONE;
75307 #ifndef SQLITE_OMIT_FLOATING_POINT
75308     }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
75309         && aff==SQLITE_AFF_NUMERIC ){
75310       aff = SQLITE_AFF_REAL;
75311     }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
75312         && aff==SQLITE_AFF_NUMERIC ){
75313       aff = SQLITE_AFF_REAL;
75314     }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
75315         && aff==SQLITE_AFF_NUMERIC ){
75316       aff = SQLITE_AFF_REAL;
75317 #endif
75318     }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
75319       aff = SQLITE_AFF_INTEGER;
75320       break;
75321     }
75322   }
75323
75324   return aff;
75325 }
75326
75327 /*
75328 ** This routine is called by the parser while in the middle of
75329 ** parsing a CREATE TABLE statement.  The pFirst token is the first
75330 ** token in the sequence of tokens that describe the type of the
75331 ** column currently under construction.   pLast is the last token
75332 ** in the sequence.  Use this information to construct a string
75333 ** that contains the typename of the column and store that string
75334 ** in zType.
75335 */ 
75336 SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
75337   Table *p;
75338   Column *pCol;
75339
75340   p = pParse->pNewTable;
75341   if( p==0 || NEVER(p->nCol<1) ) return;
75342   pCol = &p->aCol[p->nCol-1];
75343   assert( pCol->zType==0 );
75344   pCol->zType = sqlite3NameFromToken(pParse->db, pType);
75345   pCol->affinity = sqlite3AffinityType(pCol->zType);
75346 }
75347
75348 /*
75349 ** The expression is the default value for the most recently added column
75350 ** of the table currently under construction.
75351 **
75352 ** Default value expressions must be constant.  Raise an exception if this
75353 ** is not the case.
75354 **
75355 ** This routine is called by the parser while in the middle of
75356 ** parsing a CREATE TABLE statement.
75357 */
75358 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
75359   Table *p;
75360   Column *pCol;
75361   sqlite3 *db = pParse->db;
75362   p = pParse->pNewTable;
75363   if( p!=0 ){
75364     pCol = &(p->aCol[p->nCol-1]);
75365     if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
75366       sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
75367           pCol->zName);
75368     }else{
75369       /* A copy of pExpr is used instead of the original, as pExpr contains
75370       ** tokens that point to volatile memory. The 'span' of the expression
75371       ** is required by pragma table_info.
75372       */
75373       sqlite3ExprDelete(db, pCol->pDflt);
75374       pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
75375       sqlite3DbFree(db, pCol->zDflt);
75376       pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
75377                                      (int)(pSpan->zEnd - pSpan->zStart));
75378     }
75379   }
75380   sqlite3ExprDelete(db, pSpan->pExpr);
75381 }
75382
75383 /*
75384 ** Designate the PRIMARY KEY for the table.  pList is a list of names 
75385 ** of columns that form the primary key.  If pList is NULL, then the
75386 ** most recently added column of the table is the primary key.
75387 **
75388 ** A table can have at most one primary key.  If the table already has
75389 ** a primary key (and this is the second primary key) then create an
75390 ** error.
75391 **
75392 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
75393 ** then we will try to use that column as the rowid.  Set the Table.iPKey
75394 ** field of the table under construction to be the index of the
75395 ** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
75396 ** no INTEGER PRIMARY KEY.
75397 **
75398 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
75399 ** index for the key.  No index is created for INTEGER PRIMARY KEYs.
75400 */
75401 SQLITE_PRIVATE void sqlite3AddPrimaryKey(
75402   Parse *pParse,    /* Parsing context */
75403   ExprList *pList,  /* List of field names to be indexed */
75404   int onError,      /* What to do with a uniqueness conflict */
75405   int autoInc,      /* True if the AUTOINCREMENT keyword is present */
75406   int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
75407 ){
75408   Table *pTab = pParse->pNewTable;
75409   char *zType = 0;
75410   int iCol = -1, i;
75411   if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
75412   if( pTab->tabFlags & TF_HasPrimaryKey ){
75413     sqlite3ErrorMsg(pParse, 
75414       "table \"%s\" has more than one primary key", pTab->zName);
75415     goto primary_key_exit;
75416   }
75417   pTab->tabFlags |= TF_HasPrimaryKey;
75418   if( pList==0 ){
75419     iCol = pTab->nCol - 1;
75420     pTab->aCol[iCol].isPrimKey = 1;
75421   }else{
75422     for(i=0; i<pList->nExpr; i++){
75423       for(iCol=0; iCol<pTab->nCol; iCol++){
75424         if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
75425           break;
75426         }
75427       }
75428       if( iCol<pTab->nCol ){
75429         pTab->aCol[iCol].isPrimKey = 1;
75430       }
75431     }
75432     if( pList->nExpr>1 ) iCol = -1;
75433   }
75434   if( iCol>=0 && iCol<pTab->nCol ){
75435     zType = pTab->aCol[iCol].zType;
75436   }
75437   if( zType && sqlite3StrICmp(zType, "INTEGER")==0
75438         && sortOrder==SQLITE_SO_ASC ){
75439     pTab->iPKey = iCol;
75440     pTab->keyConf = (u8)onError;
75441     assert( autoInc==0 || autoInc==1 );
75442     pTab->tabFlags |= autoInc*TF_Autoincrement;
75443   }else if( autoInc ){
75444 #ifndef SQLITE_OMIT_AUTOINCREMENT
75445     sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
75446        "INTEGER PRIMARY KEY");
75447 #endif
75448   }else{
75449     Index *p;
75450     p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
75451     if( p ){
75452       p->autoIndex = 2;
75453     }
75454     pList = 0;
75455   }
75456
75457 primary_key_exit:
75458   sqlite3ExprListDelete(pParse->db, pList);
75459   return;
75460 }
75461
75462 /*
75463 ** Add a new CHECK constraint to the table currently under construction.
75464 */
75465 SQLITE_PRIVATE void sqlite3AddCheckConstraint(
75466   Parse *pParse,    /* Parsing context */
75467   Expr *pCheckExpr  /* The check expression */
75468 ){
75469   sqlite3 *db = pParse->db;
75470 #ifndef SQLITE_OMIT_CHECK
75471   Table *pTab = pParse->pNewTable;
75472   if( pTab && !IN_DECLARE_VTAB ){
75473     pTab->pCheck = sqlite3ExprAnd(db, pTab->pCheck, pCheckExpr);
75474   }else
75475 #endif
75476   {
75477     sqlite3ExprDelete(db, pCheckExpr);
75478   }
75479 }
75480
75481 /*
75482 ** Set the collation function of the most recently parsed table column
75483 ** to the CollSeq given.
75484 */
75485 SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
75486   Table *p;
75487   int i;
75488   char *zColl;              /* Dequoted name of collation sequence */
75489   sqlite3 *db;
75490
75491   if( (p = pParse->pNewTable)==0 ) return;
75492   i = p->nCol-1;
75493   db = pParse->db;
75494   zColl = sqlite3NameFromToken(db, pToken);
75495   if( !zColl ) return;
75496
75497   if( sqlite3LocateCollSeq(pParse, zColl) ){
75498     Index *pIdx;
75499     p->aCol[i].zColl = zColl;
75500   
75501     /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
75502     ** then an index may have been created on this column before the
75503     ** collation type was added. Correct this if it is the case.
75504     */
75505     for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
75506       assert( pIdx->nColumn==1 );
75507       if( pIdx->aiColumn[0]==i ){
75508         pIdx->azColl[0] = p->aCol[i].zColl;
75509       }
75510     }
75511   }else{
75512     sqlite3DbFree(db, zColl);
75513   }
75514 }
75515
75516 /*
75517 ** This function returns the collation sequence for database native text
75518 ** encoding identified by the string zName, length nName.
75519 **
75520 ** If the requested collation sequence is not available, or not available
75521 ** in the database native encoding, the collation factory is invoked to
75522 ** request it. If the collation factory does not supply such a sequence,
75523 ** and the sequence is available in another text encoding, then that is
75524 ** returned instead.
75525 **
75526 ** If no versions of the requested collations sequence are available, or
75527 ** another error occurs, NULL is returned and an error message written into
75528 ** pParse.
75529 **
75530 ** This routine is a wrapper around sqlite3FindCollSeq().  This routine
75531 ** invokes the collation factory if the named collation cannot be found
75532 ** and generates an error message.
75533 **
75534 ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
75535 */
75536 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
75537   sqlite3 *db = pParse->db;
75538   u8 enc = ENC(db);
75539   u8 initbusy = db->init.busy;
75540   CollSeq *pColl;
75541
75542   pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
75543   if( !initbusy && (!pColl || !pColl->xCmp) ){
75544     pColl = sqlite3GetCollSeq(db, enc, pColl, zName);
75545     if( !pColl ){
75546       sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
75547     }
75548   }
75549
75550   return pColl;
75551 }
75552
75553
75554 /*
75555 ** Generate code that will increment the schema cookie.
75556 **
75557 ** The schema cookie is used to determine when the schema for the
75558 ** database changes.  After each schema change, the cookie value
75559 ** changes.  When a process first reads the schema it records the
75560 ** cookie.  Thereafter, whenever it goes to access the database,
75561 ** it checks the cookie to make sure the schema has not changed
75562 ** since it was last read.
75563 **
75564 ** This plan is not completely bullet-proof.  It is possible for
75565 ** the schema to change multiple times and for the cookie to be
75566 ** set back to prior value.  But schema changes are infrequent
75567 ** and the probability of hitting the same cookie value is only
75568 ** 1 chance in 2^32.  So we're safe enough.
75569 */
75570 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
75571   int r1 = sqlite3GetTempReg(pParse);
75572   sqlite3 *db = pParse->db;
75573   Vdbe *v = pParse->pVdbe;
75574   sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
75575   sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
75576   sqlite3ReleaseTempReg(pParse, r1);
75577 }
75578
75579 /*
75580 ** Measure the number of characters needed to output the given
75581 ** identifier.  The number returned includes any quotes used
75582 ** but does not include the null terminator.
75583 **
75584 ** The estimate is conservative.  It might be larger that what is
75585 ** really needed.
75586 */
75587 static int identLength(const char *z){
75588   int n;
75589   for(n=0; *z; n++, z++){
75590     if( *z=='"' ){ n++; }
75591   }
75592   return n + 2;
75593 }
75594
75595 /*
75596 ** The first parameter is a pointer to an output buffer. The second 
75597 ** parameter is a pointer to an integer that contains the offset at
75598 ** which to write into the output buffer. This function copies the
75599 ** nul-terminated string pointed to by the third parameter, zSignedIdent,
75600 ** to the specified offset in the buffer and updates *pIdx to refer
75601 ** to the first byte after the last byte written before returning.
75602 ** 
75603 ** If the string zSignedIdent consists entirely of alpha-numeric
75604 ** characters, does not begin with a digit and is not an SQL keyword,
75605 ** then it is copied to the output buffer exactly as it is. Otherwise,
75606 ** it is quoted using double-quotes.
75607 */
75608 static void identPut(char *z, int *pIdx, char *zSignedIdent){
75609   unsigned char *zIdent = (unsigned char*)zSignedIdent;
75610   int i, j, needQuote;
75611   i = *pIdx;
75612
75613   for(j=0; zIdent[j]; j++){
75614     if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
75615   }
75616   needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID;
75617   if( !needQuote ){
75618     needQuote = zIdent[j];
75619   }
75620
75621   if( needQuote ) z[i++] = '"';
75622   for(j=0; zIdent[j]; j++){
75623     z[i++] = zIdent[j];
75624     if( zIdent[j]=='"' ) z[i++] = '"';
75625   }
75626   if( needQuote ) z[i++] = '"';
75627   z[i] = 0;
75628   *pIdx = i;
75629 }
75630
75631 /*
75632 ** Generate a CREATE TABLE statement appropriate for the given
75633 ** table.  Memory to hold the text of the statement is obtained
75634 ** from sqliteMalloc() and must be freed by the calling function.
75635 */
75636 static char *createTableStmt(sqlite3 *db, Table *p){
75637   int i, k, n;
75638   char *zStmt;
75639   char *zSep, *zSep2, *zEnd;
75640   Column *pCol;
75641   n = 0;
75642   for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
75643     n += identLength(pCol->zName) + 5;
75644   }
75645   n += identLength(p->zName);
75646   if( n<50 ){ 
75647     zSep = "";
75648     zSep2 = ",";
75649     zEnd = ")";
75650   }else{
75651     zSep = "\n  ";
75652     zSep2 = ",\n  ";
75653     zEnd = "\n)";
75654   }
75655   n += 35 + 6*p->nCol;
75656   zStmt = sqlite3DbMallocRaw(0, n);
75657   if( zStmt==0 ){
75658     db->mallocFailed = 1;
75659     return 0;
75660   }
75661   sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
75662   k = sqlite3Strlen30(zStmt);
75663   identPut(zStmt, &k, p->zName);
75664   zStmt[k++] = '(';
75665   for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
75666     static const char * const azType[] = {
75667         /* SQLITE_AFF_TEXT    */ " TEXT",
75668         /* SQLITE_AFF_NONE    */ "",
75669         /* SQLITE_AFF_NUMERIC */ " NUM",
75670         /* SQLITE_AFF_INTEGER */ " INT",
75671         /* SQLITE_AFF_REAL    */ " REAL"
75672     };
75673     int len;
75674     const char *zType;
75675
75676     sqlite3_snprintf(n-k, &zStmt[k], zSep);
75677     k += sqlite3Strlen30(&zStmt[k]);
75678     zSep = zSep2;
75679     identPut(zStmt, &k, pCol->zName);
75680     assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
75681     assert( pCol->affinity-SQLITE_AFF_TEXT < sizeof(azType)/sizeof(azType[0]) );
75682     testcase( pCol->affinity==SQLITE_AFF_TEXT );
75683     testcase( pCol->affinity==SQLITE_AFF_NONE );
75684     testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
75685     testcase( pCol->affinity==SQLITE_AFF_INTEGER );
75686     testcase( pCol->affinity==SQLITE_AFF_REAL );
75687     
75688     zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
75689     len = sqlite3Strlen30(zType);
75690     assert( pCol->affinity==SQLITE_AFF_NONE 
75691             || pCol->affinity==sqlite3AffinityType(zType) );
75692     memcpy(&zStmt[k], zType, len);
75693     k += len;
75694     assert( k<=n );
75695   }
75696   sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
75697   return zStmt;
75698 }
75699
75700 /*
75701 ** This routine is called to report the final ")" that terminates
75702 ** a CREATE TABLE statement.
75703 **
75704 ** The table structure that other action routines have been building
75705 ** is added to the internal hash tables, assuming no errors have
75706 ** occurred.
75707 **
75708 ** An entry for the table is made in the master table on disk, unless
75709 ** this is a temporary table or db->init.busy==1.  When db->init.busy==1
75710 ** it means we are reading the sqlite_master table because we just
75711 ** connected to the database or because the sqlite_master table has
75712 ** recently changed, so the entry for this table already exists in
75713 ** the sqlite_master table.  We do not want to create it again.
75714 **
75715 ** If the pSelect argument is not NULL, it means that this routine
75716 ** was called to create a table generated from a 
75717 ** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
75718 ** the new table will match the result set of the SELECT.
75719 */
75720 SQLITE_PRIVATE void sqlite3EndTable(
75721   Parse *pParse,          /* Parse context */
75722   Token *pCons,           /* The ',' token after the last column defn. */
75723   Token *pEnd,            /* The final ')' token in the CREATE TABLE */
75724   Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
75725 ){
75726   Table *p;
75727   sqlite3 *db = pParse->db;
75728   int iDb;
75729
75730   if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
75731     return;
75732   }
75733   p = pParse->pNewTable;
75734   if( p==0 ) return;
75735
75736   assert( !db->init.busy || !pSelect );
75737
75738   iDb = sqlite3SchemaToIndex(db, p->pSchema);
75739
75740 #ifndef SQLITE_OMIT_CHECK
75741   /* Resolve names in all CHECK constraint expressions.
75742   */
75743   if( p->pCheck ){
75744     SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
75745     NameContext sNC;                /* Name context for pParse->pNewTable */
75746
75747     memset(&sNC, 0, sizeof(sNC));
75748     memset(&sSrc, 0, sizeof(sSrc));
75749     sSrc.nSrc = 1;
75750     sSrc.a[0].zName = p->zName;
75751     sSrc.a[0].pTab = p;
75752     sSrc.a[0].iCursor = -1;
75753     sNC.pParse = pParse;
75754     sNC.pSrcList = &sSrc;
75755     sNC.isCheck = 1;
75756     if( sqlite3ResolveExprNames(&sNC, p->pCheck) ){
75757       return;
75758     }
75759   }
75760 #endif /* !defined(SQLITE_OMIT_CHECK) */
75761
75762   /* If the db->init.busy is 1 it means we are reading the SQL off the
75763   ** "sqlite_master" or "sqlite_temp_master" table on the disk.
75764   ** So do not write to the disk again.  Extract the root page number
75765   ** for the table from the db->init.newTnum field.  (The page number
75766   ** should have been put there by the sqliteOpenCb routine.)
75767   */
75768   if( db->init.busy ){
75769     p->tnum = db->init.newTnum;
75770   }
75771
75772   /* If not initializing, then create a record for the new table
75773   ** in the SQLITE_MASTER table of the database.
75774   **
75775   ** If this is a TEMPORARY table, write the entry into the auxiliary
75776   ** file instead of into the main database file.
75777   */
75778   if( !db->init.busy ){
75779     int n;
75780     Vdbe *v;
75781     char *zType;    /* "view" or "table" */
75782     char *zType2;   /* "VIEW" or "TABLE" */
75783     char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
75784
75785     v = sqlite3GetVdbe(pParse);
75786     if( NEVER(v==0) ) return;
75787
75788     sqlite3VdbeAddOp1(v, OP_Close, 0);
75789
75790     /* 
75791     ** Initialize zType for the new view or table.
75792     */
75793     if( p->pSelect==0 ){
75794       /* A regular table */
75795       zType = "table";
75796       zType2 = "TABLE";
75797 #ifndef SQLITE_OMIT_VIEW
75798     }else{
75799       /* A view */
75800       zType = "view";
75801       zType2 = "VIEW";
75802 #endif
75803     }
75804
75805     /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
75806     ** statement to populate the new table. The root-page number for the
75807     ** new table is in register pParse->regRoot.
75808     **
75809     ** Once the SELECT has been coded by sqlite3Select(), it is in a
75810     ** suitable state to query for the column names and types to be used
75811     ** by the new table.
75812     **
75813     ** A shared-cache write-lock is not required to write to the new table,
75814     ** as a schema-lock must have already been obtained to create it. Since
75815     ** a schema-lock excludes all other database users, the write-lock would
75816     ** be redundant.
75817     */
75818     if( pSelect ){
75819       SelectDest dest;
75820       Table *pSelTab;
75821
75822       assert(pParse->nTab==1);
75823       sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
75824       sqlite3VdbeChangeP5(v, 1);
75825       pParse->nTab = 2;
75826       sqlite3SelectDestInit(&dest, SRT_Table, 1);
75827       sqlite3Select(pParse, pSelect, &dest);
75828       sqlite3VdbeAddOp1(v, OP_Close, 1);
75829       if( pParse->nErr==0 ){
75830         pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
75831         if( pSelTab==0 ) return;
75832         assert( p->aCol==0 );
75833         p->nCol = pSelTab->nCol;
75834         p->aCol = pSelTab->aCol;
75835         pSelTab->nCol = 0;
75836         pSelTab->aCol = 0;
75837         sqlite3DeleteTable(db, pSelTab);
75838       }
75839     }
75840
75841     /* Compute the complete text of the CREATE statement */
75842     if( pSelect ){
75843       zStmt = createTableStmt(db, p);
75844     }else{
75845       n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
75846       zStmt = sqlite3MPrintf(db, 
75847           "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
75848       );
75849     }
75850
75851     /* A slot for the record has already been allocated in the 
75852     ** SQLITE_MASTER table.  We just need to update that slot with all
75853     ** the information we've collected.
75854     */
75855     sqlite3NestedParse(pParse,
75856       "UPDATE %Q.%s "
75857          "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
75858        "WHERE rowid=#%d",
75859       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
75860       zType,
75861       p->zName,
75862       p->zName,
75863       pParse->regRoot,
75864       zStmt,
75865       pParse->regRowid
75866     );
75867     sqlite3DbFree(db, zStmt);
75868     sqlite3ChangeCookie(pParse, iDb);
75869
75870 #ifndef SQLITE_OMIT_AUTOINCREMENT
75871     /* Check to see if we need to create an sqlite_sequence table for
75872     ** keeping track of autoincrement keys.
75873     */
75874     if( p->tabFlags & TF_Autoincrement ){
75875       Db *pDb = &db->aDb[iDb];
75876       if( pDb->pSchema->pSeqTab==0 ){
75877         sqlite3NestedParse(pParse,
75878           "CREATE TABLE %Q.sqlite_sequence(name,seq)",
75879           pDb->zName
75880         );
75881       }
75882     }
75883 #endif
75884
75885     /* Reparse everything to update our internal data structures */
75886     sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
75887         sqlite3MPrintf(db, "tbl_name='%q'",p->zName), P4_DYNAMIC);
75888   }
75889
75890
75891   /* Add the table to the in-memory representation of the database.
75892   */
75893   if( db->init.busy ){
75894     Table *pOld;
75895     Schema *pSchema = p->pSchema;
75896     pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
75897                              sqlite3Strlen30(p->zName),p);
75898     if( pOld ){
75899       assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
75900       db->mallocFailed = 1;
75901       return;
75902     }
75903     pParse->pNewTable = 0;
75904     db->nTable++;
75905     db->flags |= SQLITE_InternChanges;
75906
75907 #ifndef SQLITE_OMIT_ALTERTABLE
75908     if( !p->pSelect ){
75909       const char *zName = (const char *)pParse->sNameToken.z;
75910       int nName;
75911       assert( !pSelect && pCons && pEnd );
75912       if( pCons->z==0 ){
75913         pCons = pEnd;
75914       }
75915       nName = (int)((const char *)pCons->z - zName);
75916       p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
75917     }
75918 #endif
75919   }
75920 }
75921
75922 #ifndef SQLITE_OMIT_VIEW
75923 /*
75924 ** The parser calls this routine in order to create a new VIEW
75925 */
75926 SQLITE_PRIVATE void sqlite3CreateView(
75927   Parse *pParse,     /* The parsing context */
75928   Token *pBegin,     /* The CREATE token that begins the statement */
75929   Token *pName1,     /* The token that holds the name of the view */
75930   Token *pName2,     /* The token that holds the name of the view */
75931   Select *pSelect,   /* A SELECT statement that will become the new view */
75932   int isTemp,        /* TRUE for a TEMPORARY view */
75933   int noErr          /* Suppress error messages if VIEW already exists */
75934 ){
75935   Table *p;
75936   int n;
75937   const char *z;
75938   Token sEnd;
75939   DbFixer sFix;
75940   Token *pName;
75941   int iDb;
75942   sqlite3 *db = pParse->db;
75943
75944   if( pParse->nVar>0 ){
75945     sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
75946     sqlite3SelectDelete(db, pSelect);
75947     return;
75948   }
75949   sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
75950   p = pParse->pNewTable;
75951   if( p==0 || pParse->nErr ){
75952     sqlite3SelectDelete(db, pSelect);
75953     return;
75954   }
75955   sqlite3TwoPartName(pParse, pName1, pName2, &pName);
75956   iDb = sqlite3SchemaToIndex(db, p->pSchema);
75957   if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
75958     && sqlite3FixSelect(&sFix, pSelect)
75959   ){
75960     sqlite3SelectDelete(db, pSelect);
75961     return;
75962   }
75963
75964   /* Make a copy of the entire SELECT statement that defines the view.
75965   ** This will force all the Expr.token.z values to be dynamically
75966   ** allocated rather than point to the input string - which means that
75967   ** they will persist after the current sqlite3_exec() call returns.
75968   */
75969   p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
75970   sqlite3SelectDelete(db, pSelect);
75971   if( db->mallocFailed ){
75972     return;
75973   }
75974   if( !db->init.busy ){
75975     sqlite3ViewGetColumnNames(pParse, p);
75976   }
75977
75978   /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
75979   ** the end.
75980   */
75981   sEnd = pParse->sLastToken;
75982   if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
75983     sEnd.z += sEnd.n;
75984   }
75985   sEnd.n = 0;
75986   n = (int)(sEnd.z - pBegin->z);
75987   z = pBegin->z;
75988   while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
75989   sEnd.z = &z[n-1];
75990   sEnd.n = 1;
75991
75992   /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
75993   sqlite3EndTable(pParse, 0, &sEnd, 0);
75994   return;
75995 }
75996 #endif /* SQLITE_OMIT_VIEW */
75997
75998 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
75999 /*
76000 ** The Table structure pTable is really a VIEW.  Fill in the names of
76001 ** the columns of the view in the pTable structure.  Return the number
76002 ** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
76003 */
76004 SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
76005   Table *pSelTab;   /* A fake table from which we get the result set */
76006   Select *pSel;     /* Copy of the SELECT that implements the view */
76007   int nErr = 0;     /* Number of errors encountered */
76008   int n;            /* Temporarily holds the number of cursors assigned */
76009   sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
76010   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
76011
76012   assert( pTable );
76013
76014 #ifndef SQLITE_OMIT_VIRTUALTABLE
76015   if( sqlite3VtabCallConnect(pParse, pTable) ){
76016     return SQLITE_ERROR;
76017   }
76018   if( IsVirtual(pTable) ) return 0;
76019 #endif
76020
76021 #ifndef SQLITE_OMIT_VIEW
76022   /* A positive nCol means the columns names for this view are
76023   ** already known.
76024   */
76025   if( pTable->nCol>0 ) return 0;
76026
76027   /* A negative nCol is a special marker meaning that we are currently
76028   ** trying to compute the column names.  If we enter this routine with
76029   ** a negative nCol, it means two or more views form a loop, like this:
76030   **
76031   **     CREATE VIEW one AS SELECT * FROM two;
76032   **     CREATE VIEW two AS SELECT * FROM one;
76033   **
76034   ** Actually, the error above is now caught prior to reaching this point.
76035   ** But the following test is still important as it does come up
76036   ** in the following:
76037   ** 
76038   **     CREATE TABLE main.ex1(a);
76039   **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
76040   **     SELECT * FROM temp.ex1;
76041   */
76042   if( pTable->nCol<0 ){
76043     sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
76044     return 1;
76045   }
76046   assert( pTable->nCol>=0 );
76047
76048   /* If we get this far, it means we need to compute the table names.
76049   ** Note that the call to sqlite3ResultSetOfSelect() will expand any
76050   ** "*" elements in the results set of the view and will assign cursors
76051   ** to the elements of the FROM clause.  But we do not want these changes
76052   ** to be permanent.  So the computation is done on a copy of the SELECT
76053   ** statement that defines the view.
76054   */
76055   assert( pTable->pSelect );
76056   pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
76057   if( pSel ){
76058     u8 enableLookaside = db->lookaside.bEnabled;
76059     n = pParse->nTab;
76060     sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
76061     pTable->nCol = -1;
76062     db->lookaside.bEnabled = 0;
76063 #ifndef SQLITE_OMIT_AUTHORIZATION
76064     xAuth = db->xAuth;
76065     db->xAuth = 0;
76066     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
76067     db->xAuth = xAuth;
76068 #else
76069     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
76070 #endif
76071     db->lookaside.bEnabled = enableLookaside;
76072     pParse->nTab = n;
76073     if( pSelTab ){
76074       assert( pTable->aCol==0 );
76075       pTable->nCol = pSelTab->nCol;
76076       pTable->aCol = pSelTab->aCol;
76077       pSelTab->nCol = 0;
76078       pSelTab->aCol = 0;
76079       sqlite3DeleteTable(db, pSelTab);
76080       pTable->pSchema->flags |= DB_UnresetViews;
76081     }else{
76082       pTable->nCol = 0;
76083       nErr++;
76084     }
76085     sqlite3SelectDelete(db, pSel);
76086   } else {
76087     nErr++;
76088   }
76089 #endif /* SQLITE_OMIT_VIEW */
76090   return nErr;  
76091 }
76092 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
76093
76094 #ifndef SQLITE_OMIT_VIEW
76095 /*
76096 ** Clear the column names from every VIEW in database idx.
76097 */
76098 static void sqliteViewResetAll(sqlite3 *db, int idx){
76099   HashElem *i;
76100   if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
76101   for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
76102     Table *pTab = sqliteHashData(i);
76103     if( pTab->pSelect ){
76104       sqliteDeleteColumnNames(db, pTab);
76105       pTab->aCol = 0;
76106       pTab->nCol = 0;
76107     }
76108   }
76109   DbClearProperty(db, idx, DB_UnresetViews);
76110 }
76111 #else
76112 # define sqliteViewResetAll(A,B)
76113 #endif /* SQLITE_OMIT_VIEW */
76114
76115 /*
76116 ** This function is called by the VDBE to adjust the internal schema
76117 ** used by SQLite when the btree layer moves a table root page. The
76118 ** root-page of a table or index in database iDb has changed from iFrom
76119 ** to iTo.
76120 **
76121 ** Ticket #1728:  The symbol table might still contain information
76122 ** on tables and/or indices that are the process of being deleted.
76123 ** If you are unlucky, one of those deleted indices or tables might
76124 ** have the same rootpage number as the real table or index that is
76125 ** being moved.  So we cannot stop searching after the first match 
76126 ** because the first match might be for one of the deleted indices
76127 ** or tables and not the table/index that is actually being moved.
76128 ** We must continue looping until all tables and indices with
76129 ** rootpage==iFrom have been converted to have a rootpage of iTo
76130 ** in order to be certain that we got the right one.
76131 */
76132 #ifndef SQLITE_OMIT_AUTOVACUUM
76133 SQLITE_PRIVATE void sqlite3RootPageMoved(Db *pDb, int iFrom, int iTo){
76134   HashElem *pElem;
76135   Hash *pHash;
76136
76137   pHash = &pDb->pSchema->tblHash;
76138   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
76139     Table *pTab = sqliteHashData(pElem);
76140     if( pTab->tnum==iFrom ){
76141       pTab->tnum = iTo;
76142     }
76143   }
76144   pHash = &pDb->pSchema->idxHash;
76145   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
76146     Index *pIdx = sqliteHashData(pElem);
76147     if( pIdx->tnum==iFrom ){
76148       pIdx->tnum = iTo;
76149     }
76150   }
76151 }
76152 #endif
76153
76154 /*
76155 ** Write code to erase the table with root-page iTable from database iDb.
76156 ** Also write code to modify the sqlite_master table and internal schema
76157 ** if a root-page of another table is moved by the btree-layer whilst
76158 ** erasing iTable (this can happen with an auto-vacuum database).
76159 */ 
76160 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
76161   Vdbe *v = sqlite3GetVdbe(pParse);
76162   int r1 = sqlite3GetTempReg(pParse);
76163   sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
76164   sqlite3MayAbort(pParse);
76165 #ifndef SQLITE_OMIT_AUTOVACUUM
76166   /* OP_Destroy stores an in integer r1. If this integer
76167   ** is non-zero, then it is the root page number of a table moved to
76168   ** location iTable. The following code modifies the sqlite_master table to
76169   ** reflect this.
76170   **
76171   ** The "#NNN" in the SQL is a special constant that means whatever value
76172   ** is in register NNN.  See grammar rules associated with the TK_REGISTER
76173   ** token for additional information.
76174   */
76175   sqlite3NestedParse(pParse, 
76176      "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
76177      pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
76178 #endif
76179   sqlite3ReleaseTempReg(pParse, r1);
76180 }
76181
76182 /*
76183 ** Write VDBE code to erase table pTab and all associated indices on disk.
76184 ** Code to update the sqlite_master tables and internal schema definitions
76185 ** in case a root-page belonging to another table is moved by the btree layer
76186 ** is also added (this can happen with an auto-vacuum database).
76187 */
76188 static void destroyTable(Parse *pParse, Table *pTab){
76189 #ifdef SQLITE_OMIT_AUTOVACUUM
76190   Index *pIdx;
76191   int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
76192   destroyRootPage(pParse, pTab->tnum, iDb);
76193   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
76194     destroyRootPage(pParse, pIdx->tnum, iDb);
76195   }
76196 #else
76197   /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
76198   ** is not defined), then it is important to call OP_Destroy on the
76199   ** table and index root-pages in order, starting with the numerically 
76200   ** largest root-page number. This guarantees that none of the root-pages
76201   ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
76202   ** following were coded:
76203   **
76204   ** OP_Destroy 4 0
76205   ** ...
76206   ** OP_Destroy 5 0
76207   **
76208   ** and root page 5 happened to be the largest root-page number in the
76209   ** database, then root page 5 would be moved to page 4 by the 
76210   ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
76211   ** a free-list page.
76212   */
76213   int iTab = pTab->tnum;
76214   int iDestroyed = 0;
76215
76216   while( 1 ){
76217     Index *pIdx;
76218     int iLargest = 0;
76219
76220     if( iDestroyed==0 || iTab<iDestroyed ){
76221       iLargest = iTab;
76222     }
76223     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
76224       int iIdx = pIdx->tnum;
76225       assert( pIdx->pSchema==pTab->pSchema );
76226       if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
76227         iLargest = iIdx;
76228       }
76229     }
76230     if( iLargest==0 ){
76231       return;
76232     }else{
76233       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
76234       destroyRootPage(pParse, iLargest, iDb);
76235       iDestroyed = iLargest;
76236     }
76237   }
76238 #endif
76239 }
76240
76241 /*
76242 ** This routine is called to do the work of a DROP TABLE statement.
76243 ** pName is the name of the table to be dropped.
76244 */
76245 SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
76246   Table *pTab;
76247   Vdbe *v;
76248   sqlite3 *db = pParse->db;
76249   int iDb;
76250
76251   if( db->mallocFailed ){
76252     goto exit_drop_table;
76253   }
76254   assert( pParse->nErr==0 );
76255   assert( pName->nSrc==1 );
76256   if( noErr ) db->suppressErr++;
76257   pTab = sqlite3LocateTable(pParse, isView, 
76258                             pName->a[0].zName, pName->a[0].zDatabase);
76259   if( noErr ) db->suppressErr--;
76260
76261   if( pTab==0 ){
76262     goto exit_drop_table;
76263   }
76264   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
76265   assert( iDb>=0 && iDb<db->nDb );
76266
76267   /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
76268   ** it is initialized.
76269   */
76270   if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
76271     goto exit_drop_table;
76272   }
76273 #ifndef SQLITE_OMIT_AUTHORIZATION
76274   {
76275     int code;
76276     const char *zTab = SCHEMA_TABLE(iDb);
76277     const char *zDb = db->aDb[iDb].zName;
76278     const char *zArg2 = 0;
76279     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
76280       goto exit_drop_table;
76281     }
76282     if( isView ){
76283       if( !OMIT_TEMPDB && iDb==1 ){
76284         code = SQLITE_DROP_TEMP_VIEW;
76285       }else{
76286         code = SQLITE_DROP_VIEW;
76287       }
76288 #ifndef SQLITE_OMIT_VIRTUALTABLE
76289     }else if( IsVirtual(pTab) ){
76290       code = SQLITE_DROP_VTABLE;
76291       zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
76292 #endif
76293     }else{
76294       if( !OMIT_TEMPDB && iDb==1 ){
76295         code = SQLITE_DROP_TEMP_TABLE;
76296       }else{
76297         code = SQLITE_DROP_TABLE;
76298       }
76299     }
76300     if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
76301       goto exit_drop_table;
76302     }
76303     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
76304       goto exit_drop_table;
76305     }
76306   }
76307 #endif
76308   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
76309     sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
76310     goto exit_drop_table;
76311   }
76312
76313 #ifndef SQLITE_OMIT_VIEW
76314   /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
76315   ** on a table.
76316   */
76317   if( isView && pTab->pSelect==0 ){
76318     sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
76319     goto exit_drop_table;
76320   }
76321   if( !isView && pTab->pSelect ){
76322     sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
76323     goto exit_drop_table;
76324   }
76325 #endif
76326
76327   /* Generate code to remove the table from the master table
76328   ** on disk.
76329   */
76330   v = sqlite3GetVdbe(pParse);
76331   if( v ){
76332     Trigger *pTrigger;
76333     Db *pDb = &db->aDb[iDb];
76334     sqlite3BeginWriteOperation(pParse, 1, iDb);
76335
76336 #ifndef SQLITE_OMIT_VIRTUALTABLE
76337     if( IsVirtual(pTab) ){
76338       sqlite3VdbeAddOp0(v, OP_VBegin);
76339     }
76340 #endif
76341     sqlite3FkDropTable(pParse, pName, pTab);
76342
76343     /* Drop all triggers associated with the table being dropped. Code
76344     ** is generated to remove entries from sqlite_master and/or
76345     ** sqlite_temp_master if required.
76346     */
76347     pTrigger = sqlite3TriggerList(pParse, pTab);
76348     while( pTrigger ){
76349       assert( pTrigger->pSchema==pTab->pSchema || 
76350           pTrigger->pSchema==db->aDb[1].pSchema );
76351       sqlite3DropTriggerPtr(pParse, pTrigger);
76352       pTrigger = pTrigger->pNext;
76353     }
76354
76355 #ifndef SQLITE_OMIT_AUTOINCREMENT
76356     /* Remove any entries of the sqlite_sequence table associated with
76357     ** the table being dropped. This is done before the table is dropped
76358     ** at the btree level, in case the sqlite_sequence table needs to
76359     ** move as a result of the drop (can happen in auto-vacuum mode).
76360     */
76361     if( pTab->tabFlags & TF_Autoincrement ){
76362       sqlite3NestedParse(pParse,
76363         "DELETE FROM %s.sqlite_sequence WHERE name=%Q",
76364         pDb->zName, pTab->zName
76365       );
76366     }
76367 #endif
76368
76369     /* Drop all SQLITE_MASTER table and index entries that refer to the
76370     ** table. The program name loops through the master table and deletes
76371     ** every row that refers to a table of the same name as the one being
76372     ** dropped. Triggers are handled seperately because a trigger can be
76373     ** created in the temp database that refers to a table in another
76374     ** database.
76375     */
76376     sqlite3NestedParse(pParse, 
76377         "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
76378         pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
76379
76380     /* Drop any statistics from the sqlite_stat1 table, if it exists */
76381     if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
76382       sqlite3NestedParse(pParse,
76383         "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q", pDb->zName, pTab->zName
76384       );
76385     }
76386
76387     if( !isView && !IsVirtual(pTab) ){
76388       destroyTable(pParse, pTab);
76389     }
76390
76391     /* Remove the table entry from SQLite's internal schema and modify
76392     ** the schema cookie.
76393     */
76394     if( IsVirtual(pTab) ){
76395       sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
76396     }
76397     sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
76398     sqlite3ChangeCookie(pParse, iDb);
76399   }
76400   sqliteViewResetAll(db, iDb);
76401
76402 exit_drop_table:
76403   sqlite3SrcListDelete(db, pName);
76404 }
76405
76406 /*
76407 ** This routine is called to create a new foreign key on the table
76408 ** currently under construction.  pFromCol determines which columns
76409 ** in the current table point to the foreign key.  If pFromCol==0 then
76410 ** connect the key to the last column inserted.  pTo is the name of
76411 ** the table referred to.  pToCol is a list of tables in the other
76412 ** pTo table that the foreign key points to.  flags contains all
76413 ** information about the conflict resolution algorithms specified
76414 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
76415 **
76416 ** An FKey structure is created and added to the table currently
76417 ** under construction in the pParse->pNewTable field.
76418 **
76419 ** The foreign key is set for IMMEDIATE processing.  A subsequent call
76420 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
76421 */
76422 SQLITE_PRIVATE void sqlite3CreateForeignKey(
76423   Parse *pParse,       /* Parsing context */
76424   ExprList *pFromCol,  /* Columns in this table that point to other table */
76425   Token *pTo,          /* Name of the other table */
76426   ExprList *pToCol,    /* Columns in the other table */
76427   int flags            /* Conflict resolution algorithms. */
76428 ){
76429   sqlite3 *db = pParse->db;
76430 #ifndef SQLITE_OMIT_FOREIGN_KEY
76431   FKey *pFKey = 0;
76432   FKey *pNextTo;
76433   Table *p = pParse->pNewTable;
76434   int nByte;
76435   int i;
76436   int nCol;
76437   char *z;
76438
76439   assert( pTo!=0 );
76440   if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
76441   if( pFromCol==0 ){
76442     int iCol = p->nCol-1;
76443     if( NEVER(iCol<0) ) goto fk_end;
76444     if( pToCol && pToCol->nExpr!=1 ){
76445       sqlite3ErrorMsg(pParse, "foreign key on %s"
76446          " should reference only one column of table %T",
76447          p->aCol[iCol].zName, pTo);
76448       goto fk_end;
76449     }
76450     nCol = 1;
76451   }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
76452     sqlite3ErrorMsg(pParse,
76453         "number of columns in foreign key does not match the number of "
76454         "columns in the referenced table");
76455     goto fk_end;
76456   }else{
76457     nCol = pFromCol->nExpr;
76458   }
76459   nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
76460   if( pToCol ){
76461     for(i=0; i<pToCol->nExpr; i++){
76462       nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
76463     }
76464   }
76465   pFKey = sqlite3DbMallocZero(db, nByte );
76466   if( pFKey==0 ){
76467     goto fk_end;
76468   }
76469   pFKey->pFrom = p;
76470   pFKey->pNextFrom = p->pFKey;
76471   z = (char*)&pFKey->aCol[nCol];
76472   pFKey->zTo = z;
76473   memcpy(z, pTo->z, pTo->n);
76474   z[pTo->n] = 0;
76475   sqlite3Dequote(z);
76476   z += pTo->n+1;
76477   pFKey->nCol = nCol;
76478   if( pFromCol==0 ){
76479     pFKey->aCol[0].iFrom = p->nCol-1;
76480   }else{
76481     for(i=0; i<nCol; i++){
76482       int j;
76483       for(j=0; j<p->nCol; j++){
76484         if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
76485           pFKey->aCol[i].iFrom = j;
76486           break;
76487         }
76488       }
76489       if( j>=p->nCol ){
76490         sqlite3ErrorMsg(pParse, 
76491           "unknown column \"%s\" in foreign key definition", 
76492           pFromCol->a[i].zName);
76493         goto fk_end;
76494       }
76495     }
76496   }
76497   if( pToCol ){
76498     for(i=0; i<nCol; i++){
76499       int n = sqlite3Strlen30(pToCol->a[i].zName);
76500       pFKey->aCol[i].zCol = z;
76501       memcpy(z, pToCol->a[i].zName, n);
76502       z[n] = 0;
76503       z += n+1;
76504     }
76505   }
76506   pFKey->isDeferred = 0;
76507   pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */
76508   pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */
76509
76510   pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash, 
76511       pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey
76512   );
76513   if( pNextTo==pFKey ){
76514     db->mallocFailed = 1;
76515     goto fk_end;
76516   }
76517   if( pNextTo ){
76518     assert( pNextTo->pPrevTo==0 );
76519     pFKey->pNextTo = pNextTo;
76520     pNextTo->pPrevTo = pFKey;
76521   }
76522
76523   /* Link the foreign key to the table as the last step.
76524   */
76525   p->pFKey = pFKey;
76526   pFKey = 0;
76527
76528 fk_end:
76529   sqlite3DbFree(db, pFKey);
76530 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
76531   sqlite3ExprListDelete(db, pFromCol);
76532   sqlite3ExprListDelete(db, pToCol);
76533 }
76534
76535 /*
76536 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
76537 ** clause is seen as part of a foreign key definition.  The isDeferred
76538 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
76539 ** The behavior of the most recently created foreign key is adjusted
76540 ** accordingly.
76541 */
76542 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
76543 #ifndef SQLITE_OMIT_FOREIGN_KEY
76544   Table *pTab;
76545   FKey *pFKey;
76546   if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
76547   assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
76548   pFKey->isDeferred = (u8)isDeferred;
76549 #endif
76550 }
76551
76552 /*
76553 ** Generate code that will erase and refill index *pIdx.  This is
76554 ** used to initialize a newly created index or to recompute the
76555 ** content of an index in response to a REINDEX command.
76556 **
76557 ** if memRootPage is not negative, it means that the index is newly
76558 ** created.  The register specified by memRootPage contains the
76559 ** root page number of the index.  If memRootPage is negative, then
76560 ** the index already exists and must be cleared before being refilled and
76561 ** the root page number of the index is taken from pIndex->tnum.
76562 */
76563 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
76564   Table *pTab = pIndex->pTable;  /* The table that is indexed */
76565   int iTab = pParse->nTab++;     /* Btree cursor used for pTab */
76566   int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */
76567   int addr1;                     /* Address of top of loop */
76568   int tnum;                      /* Root page of index */
76569   Vdbe *v;                       /* Generate code into this virtual machine */
76570   KeyInfo *pKey;                 /* KeyInfo for index */
76571   int regIdxKey;                 /* Registers containing the index key */
76572   int regRecord;                 /* Register holding assemblied index record */
76573   sqlite3 *db = pParse->db;      /* The database connection */
76574   int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
76575
76576 #ifndef SQLITE_OMIT_AUTHORIZATION
76577   if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
76578       db->aDb[iDb].zName ) ){
76579     return;
76580   }
76581 #endif
76582
76583   /* Require a write-lock on the table to perform this operation */
76584   sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
76585
76586   v = sqlite3GetVdbe(pParse);
76587   if( v==0 ) return;
76588   if( memRootPage>=0 ){
76589     tnum = memRootPage;
76590   }else{
76591     tnum = pIndex->tnum;
76592     sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
76593   }
76594   pKey = sqlite3IndexKeyinfo(pParse, pIndex);
76595   sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb, 
76596                     (char *)pKey, P4_KEYINFO_HANDOFF);
76597   if( memRootPage>=0 ){
76598     sqlite3VdbeChangeP5(v, 1);
76599   }
76600   sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
76601   addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
76602   regRecord = sqlite3GetTempReg(pParse);
76603   regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
76604   if( pIndex->onError!=OE_None ){
76605     const int regRowid = regIdxKey + pIndex->nColumn;
76606     const int j2 = sqlite3VdbeCurrentAddr(v) + 2;
76607     void * const pRegKey = SQLITE_INT_TO_PTR(regIdxKey);
76608
76609     /* The registers accessed by the OP_IsUnique opcode were allocated
76610     ** using sqlite3GetTempRange() inside of the sqlite3GenerateIndexKey()
76611     ** call above. Just before that function was freed they were released
76612     ** (made available to the compiler for reuse) using 
76613     ** sqlite3ReleaseTempRange(). So in some ways having the OP_IsUnique
76614     ** opcode use the values stored within seems dangerous. However, since
76615     ** we can be sure that no other temp registers have been allocated
76616     ** since sqlite3ReleaseTempRange() was called, it is safe to do so.
76617     */
76618     sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx, j2, regRowid, pRegKey, P4_INT32);
76619     sqlite3HaltConstraint(
76620         pParse, OE_Abort, "indexed columns are not unique", P4_STATIC);
76621   }
76622   sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
76623   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
76624   sqlite3ReleaseTempReg(pParse, regRecord);
76625   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
76626   sqlite3VdbeJumpHere(v, addr1);
76627   sqlite3VdbeAddOp1(v, OP_Close, iTab);
76628   sqlite3VdbeAddOp1(v, OP_Close, iIdx);
76629 }
76630
76631 /*
76632 ** Create a new index for an SQL table.  pName1.pName2 is the name of the index 
76633 ** and pTblList is the name of the table that is to be indexed.  Both will 
76634 ** be NULL for a primary key or an index that is created to satisfy a
76635 ** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
76636 ** as the table to be indexed.  pParse->pNewTable is a table that is
76637 ** currently being constructed by a CREATE TABLE statement.
76638 **
76639 ** pList is a list of columns to be indexed.  pList will be NULL if this
76640 ** is a primary key or unique-constraint on the most recent column added
76641 ** to the table currently under construction.  
76642 **
76643 ** If the index is created successfully, return a pointer to the new Index
76644 ** structure. This is used by sqlite3AddPrimaryKey() to mark the index
76645 ** as the tables primary key (Index.autoIndex==2).
76646 */
76647 SQLITE_PRIVATE Index *sqlite3CreateIndex(
76648   Parse *pParse,     /* All information about this parse */
76649   Token *pName1,     /* First part of index name. May be NULL */
76650   Token *pName2,     /* Second part of index name. May be NULL */
76651   SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
76652   ExprList *pList,   /* A list of columns to be indexed */
76653   int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
76654   Token *pStart,     /* The CREATE token that begins this statement */
76655   Token *pEnd,       /* The ")" that closes the CREATE INDEX statement */
76656   int sortOrder,     /* Sort order of primary key when pList==NULL */
76657   int ifNotExist     /* Omit error if index already exists */
76658 ){
76659   Index *pRet = 0;     /* Pointer to return */
76660   Table *pTab = 0;     /* Table to be indexed */
76661   Index *pIndex = 0;   /* The index to be created */
76662   char *zName = 0;     /* Name of the index */
76663   int nName;           /* Number of characters in zName */
76664   int i, j;
76665   Token nullId;        /* Fake token for an empty ID list */
76666   DbFixer sFix;        /* For assigning database names to pTable */
76667   int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
76668   sqlite3 *db = pParse->db;
76669   Db *pDb;             /* The specific table containing the indexed database */
76670   int iDb;             /* Index of the database that is being written */
76671   Token *pName = 0;    /* Unqualified name of the index to create */
76672   struct ExprList_item *pListItem; /* For looping over pList */
76673   int nCol;
76674   int nExtra = 0;
76675   char *zExtra;
76676
76677   assert( pStart==0 || pEnd!=0 ); /* pEnd must be non-NULL if pStart is */
76678   assert( pParse->nErr==0 );      /* Never called with prior errors */
76679   if( db->mallocFailed || IN_DECLARE_VTAB ){
76680     goto exit_create_index;
76681   }
76682   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
76683     goto exit_create_index;
76684   }
76685
76686   /*
76687   ** Find the table that is to be indexed.  Return early if not found.
76688   */
76689   if( pTblName!=0 ){
76690
76691     /* Use the two-part index name to determine the database 
76692     ** to search for the table. 'Fix' the table name to this db
76693     ** before looking up the table.
76694     */
76695     assert( pName1 && pName2 );
76696     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
76697     if( iDb<0 ) goto exit_create_index;
76698
76699 #ifndef SQLITE_OMIT_TEMPDB
76700     /* If the index name was unqualified, check if the the table
76701     ** is a temp table. If so, set the database to 1. Do not do this
76702     ** if initialising a database schema.
76703     */
76704     if( !db->init.busy ){
76705       pTab = sqlite3SrcListLookup(pParse, pTblName);
76706       if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
76707         iDb = 1;
76708       }
76709     }
76710 #endif
76711
76712     if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
76713         sqlite3FixSrcList(&sFix, pTblName)
76714     ){
76715       /* Because the parser constructs pTblName from a single identifier,
76716       ** sqlite3FixSrcList can never fail. */
76717       assert(0);
76718     }
76719     pTab = sqlite3LocateTable(pParse, 0, pTblName->a[0].zName, 
76720         pTblName->a[0].zDatabase);
76721     if( !pTab || db->mallocFailed ) goto exit_create_index;
76722     assert( db->aDb[iDb].pSchema==pTab->pSchema );
76723   }else{
76724     assert( pName==0 );
76725     pTab = pParse->pNewTable;
76726     if( !pTab ) goto exit_create_index;
76727     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
76728   }
76729   pDb = &db->aDb[iDb];
76730
76731   assert( pTab!=0 );
76732   assert( pParse->nErr==0 );
76733   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 
76734        && memcmp(&pTab->zName[7],"altertab_",9)!=0 ){
76735     sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
76736     goto exit_create_index;
76737   }
76738 #ifndef SQLITE_OMIT_VIEW
76739   if( pTab->pSelect ){
76740     sqlite3ErrorMsg(pParse, "views may not be indexed");
76741     goto exit_create_index;
76742   }
76743 #endif
76744 #ifndef SQLITE_OMIT_VIRTUALTABLE
76745   if( IsVirtual(pTab) ){
76746     sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
76747     goto exit_create_index;
76748   }
76749 #endif
76750
76751   /*
76752   ** Find the name of the index.  Make sure there is not already another
76753   ** index or table with the same name.  
76754   **
76755   ** Exception:  If we are reading the names of permanent indices from the
76756   ** sqlite_master table (because some other process changed the schema) and
76757   ** one of the index names collides with the name of a temporary table or
76758   ** index, then we will continue to process this index.
76759   **
76760   ** If pName==0 it means that we are
76761   ** dealing with a primary key or UNIQUE constraint.  We have to invent our
76762   ** own name.
76763   */
76764   if( pName ){
76765     zName = sqlite3NameFromToken(db, pName);
76766     if( zName==0 ) goto exit_create_index;
76767     if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
76768       goto exit_create_index;
76769     }
76770     if( !db->init.busy ){
76771       if( sqlite3FindTable(db, zName, 0)!=0 ){
76772         sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
76773         goto exit_create_index;
76774       }
76775     }
76776     if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
76777       if( !ifNotExist ){
76778         sqlite3ErrorMsg(pParse, "index %s already exists", zName);
76779       }
76780       goto exit_create_index;
76781     }
76782   }else{
76783     int n;
76784     Index *pLoop;
76785     for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
76786     zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
76787     if( zName==0 ){
76788       goto exit_create_index;
76789     }
76790   }
76791
76792   /* Check for authorization to create an index.
76793   */
76794 #ifndef SQLITE_OMIT_AUTHORIZATION
76795   {
76796     const char *zDb = pDb->zName;
76797     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
76798       goto exit_create_index;
76799     }
76800     i = SQLITE_CREATE_INDEX;
76801     if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
76802     if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
76803       goto exit_create_index;
76804     }
76805   }
76806 #endif
76807
76808   /* If pList==0, it means this routine was called to make a primary
76809   ** key out of the last column added to the table under construction.
76810   ** So create a fake list to simulate this.
76811   */
76812   if( pList==0 ){
76813     nullId.z = pTab->aCol[pTab->nCol-1].zName;
76814     nullId.n = sqlite3Strlen30((char*)nullId.z);
76815     pList = sqlite3ExprListAppend(pParse, 0, 0);
76816     if( pList==0 ) goto exit_create_index;
76817     sqlite3ExprListSetName(pParse, pList, &nullId, 0);
76818     pList->a[0].sortOrder = (u8)sortOrder;
76819   }
76820
76821   /* Figure out how many bytes of space are required to store explicitly
76822   ** specified collation sequence names.
76823   */
76824   for(i=0; i<pList->nExpr; i++){
76825     Expr *pExpr = pList->a[i].pExpr;
76826     if( pExpr ){
76827       CollSeq *pColl = pExpr->pColl;
76828       /* Either pColl!=0 or there was an OOM failure.  But if an OOM
76829       ** failure we have quit before reaching this point. */
76830       if( ALWAYS(pColl) ){
76831         nExtra += (1 + sqlite3Strlen30(pColl->zName));
76832       }
76833     }
76834   }
76835
76836   /* 
76837   ** Allocate the index structure. 
76838   */
76839   nName = sqlite3Strlen30(zName);
76840   nCol = pList->nExpr;
76841   pIndex = sqlite3DbMallocZero(db, 
76842       sizeof(Index) +              /* Index structure  */
76843       sizeof(int)*nCol +           /* Index.aiColumn   */
76844       sizeof(int)*(nCol+1) +       /* Index.aiRowEst   */
76845       sizeof(char *)*nCol +        /* Index.azColl     */
76846       sizeof(u8)*nCol +            /* Index.aSortOrder */
76847       nName + 1 +                  /* Index.zName      */
76848       nExtra                       /* Collation sequence names */
76849   );
76850   if( db->mallocFailed ){
76851     goto exit_create_index;
76852   }
76853   pIndex->azColl = (char**)(&pIndex[1]);
76854   pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
76855   pIndex->aiRowEst = (unsigned *)(&pIndex->aiColumn[nCol]);
76856   pIndex->aSortOrder = (u8 *)(&pIndex->aiRowEst[nCol+1]);
76857   pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
76858   zExtra = (char *)(&pIndex->zName[nName+1]);
76859   memcpy(pIndex->zName, zName, nName+1);
76860   pIndex->pTable = pTab;
76861   pIndex->nColumn = pList->nExpr;
76862   pIndex->onError = (u8)onError;
76863   pIndex->autoIndex = (u8)(pName==0);
76864   pIndex->pSchema = db->aDb[iDb].pSchema;
76865
76866   /* Check to see if we should honor DESC requests on index columns
76867   */
76868   if( pDb->pSchema->file_format>=4 ){
76869     sortOrderMask = -1;   /* Honor DESC */
76870   }else{
76871     sortOrderMask = 0;    /* Ignore DESC */
76872   }
76873
76874   /* Scan the names of the columns of the table to be indexed and
76875   ** load the column indices into the Index structure.  Report an error
76876   ** if any column is not found.
76877   **
76878   ** TODO:  Add a test to make sure that the same column is not named
76879   ** more than once within the same index.  Only the first instance of
76880   ** the column will ever be used by the optimizer.  Note that using the
76881   ** same column more than once cannot be an error because that would 
76882   ** break backwards compatibility - it needs to be a warning.
76883   */
76884   for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
76885     const char *zColName = pListItem->zName;
76886     Column *pTabCol;
76887     int requestedSortOrder;
76888     char *zColl;                   /* Collation sequence name */
76889
76890     for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
76891       if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
76892     }
76893     if( j>=pTab->nCol ){
76894       sqlite3ErrorMsg(pParse, "table %s has no column named %s",
76895         pTab->zName, zColName);
76896       pParse->checkSchema = 1;
76897       goto exit_create_index;
76898     }
76899     pIndex->aiColumn[i] = j;
76900     /* Justification of the ALWAYS(pListItem->pExpr->pColl):  Because of
76901     ** the way the "idxlist" non-terminal is constructed by the parser,
76902     ** if pListItem->pExpr is not null then either pListItem->pExpr->pColl
76903     ** must exist or else there must have been an OOM error.  But if there
76904     ** was an OOM error, we would never reach this point. */
76905     if( pListItem->pExpr && ALWAYS(pListItem->pExpr->pColl) ){
76906       int nColl;
76907       zColl = pListItem->pExpr->pColl->zName;
76908       nColl = sqlite3Strlen30(zColl) + 1;
76909       assert( nExtra>=nColl );
76910       memcpy(zExtra, zColl, nColl);
76911       zColl = zExtra;
76912       zExtra += nColl;
76913       nExtra -= nColl;
76914     }else{
76915       zColl = pTab->aCol[j].zColl;
76916       if( !zColl ){
76917         zColl = db->pDfltColl->zName;
76918       }
76919     }
76920     if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
76921       goto exit_create_index;
76922     }
76923     pIndex->azColl[i] = zColl;
76924     requestedSortOrder = pListItem->sortOrder & sortOrderMask;
76925     pIndex->aSortOrder[i] = (u8)requestedSortOrder;
76926   }
76927   sqlite3DefaultRowEst(pIndex);
76928
76929   if( pTab==pParse->pNewTable ){
76930     /* This routine has been called to create an automatic index as a
76931     ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
76932     ** a PRIMARY KEY or UNIQUE clause following the column definitions.
76933     ** i.e. one of:
76934     **
76935     ** CREATE TABLE t(x PRIMARY KEY, y);
76936     ** CREATE TABLE t(x, y, UNIQUE(x, y));
76937     **
76938     ** Either way, check to see if the table already has such an index. If
76939     ** so, don't bother creating this one. This only applies to
76940     ** automatically created indices. Users can do as they wish with
76941     ** explicit indices.
76942     **
76943     ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
76944     ** (and thus suppressing the second one) even if they have different
76945     ** sort orders.
76946     **
76947     ** If there are different collating sequences or if the columns of
76948     ** the constraint occur in different orders, then the constraints are
76949     ** considered distinct and both result in separate indices.
76950     */
76951     Index *pIdx;
76952     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
76953       int k;
76954       assert( pIdx->onError!=OE_None );
76955       assert( pIdx->autoIndex );
76956       assert( pIndex->onError!=OE_None );
76957
76958       if( pIdx->nColumn!=pIndex->nColumn ) continue;
76959       for(k=0; k<pIdx->nColumn; k++){
76960         const char *z1;
76961         const char *z2;
76962         if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
76963         z1 = pIdx->azColl[k];
76964         z2 = pIndex->azColl[k];
76965         if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
76966       }
76967       if( k==pIdx->nColumn ){
76968         if( pIdx->onError!=pIndex->onError ){
76969           /* This constraint creates the same index as a previous
76970           ** constraint specified somewhere in the CREATE TABLE statement.
76971           ** However the ON CONFLICT clauses are different. If both this 
76972           ** constraint and the previous equivalent constraint have explicit
76973           ** ON CONFLICT clauses this is an error. Otherwise, use the
76974           ** explicitly specified behaviour for the index.
76975           */
76976           if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
76977             sqlite3ErrorMsg(pParse, 
76978                 "conflicting ON CONFLICT clauses specified", 0);
76979           }
76980           if( pIdx->onError==OE_Default ){
76981             pIdx->onError = pIndex->onError;
76982           }
76983         }
76984         goto exit_create_index;
76985       }
76986     }
76987   }
76988
76989   /* Link the new Index structure to its table and to the other
76990   ** in-memory database structures. 
76991   */
76992   if( db->init.busy ){
76993     Index *p;
76994     p = sqlite3HashInsert(&pIndex->pSchema->idxHash, 
76995                           pIndex->zName, sqlite3Strlen30(pIndex->zName),
76996                           pIndex);
76997     if( p ){
76998       assert( p==pIndex );  /* Malloc must have failed */
76999       db->mallocFailed = 1;
77000       goto exit_create_index;
77001     }
77002     db->flags |= SQLITE_InternChanges;
77003     if( pTblName!=0 ){
77004       pIndex->tnum = db->init.newTnum;
77005     }
77006   }
77007
77008   /* If the db->init.busy is 0 then create the index on disk.  This
77009   ** involves writing the index into the master table and filling in the
77010   ** index with the current table contents.
77011   **
77012   ** The db->init.busy is 0 when the user first enters a CREATE INDEX 
77013   ** command.  db->init.busy is 1 when a database is opened and 
77014   ** CREATE INDEX statements are read out of the master table.  In
77015   ** the latter case the index already exists on disk, which is why
77016   ** we don't want to recreate it.
77017   **
77018   ** If pTblName==0 it means this index is generated as a primary key
77019   ** or UNIQUE constraint of a CREATE TABLE statement.  Since the table
77020   ** has just been created, it contains no data and the index initialization
77021   ** step can be skipped.
77022   */
77023   else{ /* if( db->init.busy==0 ) */
77024     Vdbe *v;
77025     char *zStmt;
77026     int iMem = ++pParse->nMem;
77027
77028     v = sqlite3GetVdbe(pParse);
77029     if( v==0 ) goto exit_create_index;
77030
77031
77032     /* Create the rootpage for the index
77033     */
77034     sqlite3BeginWriteOperation(pParse, 1, iDb);
77035     sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
77036
77037     /* Gather the complete text of the CREATE INDEX statement into
77038     ** the zStmt variable
77039     */
77040     if( pStart ){
77041       assert( pEnd!=0 );
77042       /* A named index with an explicit CREATE INDEX statement */
77043       zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
77044         onError==OE_None ? "" : " UNIQUE",
77045         pEnd->z - pName->z + 1,
77046         pName->z);
77047     }else{
77048       /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
77049       /* zStmt = sqlite3MPrintf(""); */
77050       zStmt = 0;
77051     }
77052
77053     /* Add an entry in sqlite_master for this index
77054     */
77055     sqlite3NestedParse(pParse, 
77056         "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
77057         db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
77058         pIndex->zName,
77059         pTab->zName,
77060         iMem,
77061         zStmt
77062     );
77063     sqlite3DbFree(db, zStmt);
77064
77065     /* Fill the index with data and reparse the schema. Code an OP_Expire
77066     ** to invalidate all pre-compiled statements.
77067     */
77068     if( pTblName ){
77069       sqlite3RefillIndex(pParse, pIndex, iMem);
77070       sqlite3ChangeCookie(pParse, iDb);
77071       sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
77072          sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName), 
77073          P4_DYNAMIC);
77074       sqlite3VdbeAddOp1(v, OP_Expire, 0);
77075     }
77076   }
77077
77078   /* When adding an index to the list of indices for a table, make
77079   ** sure all indices labeled OE_Replace come after all those labeled
77080   ** OE_Ignore.  This is necessary for the correct constraint check
77081   ** processing (in sqlite3GenerateConstraintChecks()) as part of
77082   ** UPDATE and INSERT statements.  
77083   */
77084   if( db->init.busy || pTblName==0 ){
77085     if( onError!=OE_Replace || pTab->pIndex==0
77086          || pTab->pIndex->onError==OE_Replace){
77087       pIndex->pNext = pTab->pIndex;
77088       pTab->pIndex = pIndex;
77089     }else{
77090       Index *pOther = pTab->pIndex;
77091       while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
77092         pOther = pOther->pNext;
77093       }
77094       pIndex->pNext = pOther->pNext;
77095       pOther->pNext = pIndex;
77096     }
77097     pRet = pIndex;
77098     pIndex = 0;
77099   }
77100
77101   /* Clean up before exiting */
77102 exit_create_index:
77103   if( pIndex ){
77104     sqlite3DbFree(db, pIndex->zColAff);
77105     sqlite3DbFree(db, pIndex);
77106   }
77107   sqlite3ExprListDelete(db, pList);
77108   sqlite3SrcListDelete(db, pTblName);
77109   sqlite3DbFree(db, zName);
77110   return pRet;
77111 }
77112
77113 /*
77114 ** Fill the Index.aiRowEst[] array with default information - information
77115 ** to be used when we have not run the ANALYZE command.
77116 **
77117 ** aiRowEst[0] is suppose to contain the number of elements in the index.
77118 ** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
77119 ** number of rows in the table that match any particular value of the
77120 ** first column of the index.  aiRowEst[2] is an estimate of the number
77121 ** of rows that match any particular combiniation of the first 2 columns
77122 ** of the index.  And so forth.  It must always be the case that
77123 *
77124 **           aiRowEst[N]<=aiRowEst[N-1]
77125 **           aiRowEst[N]>=1
77126 **
77127 ** Apart from that, we have little to go on besides intuition as to
77128 ** how aiRowEst[] should be initialized.  The numbers generated here
77129 ** are based on typical values found in actual indices.
77130 */
77131 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
77132   unsigned *a = pIdx->aiRowEst;
77133   int i;
77134   unsigned n;
77135   assert( a!=0 );
77136   a[0] = pIdx->pTable->nRowEst;
77137   if( a[0]<10 ) a[0] = 10;
77138   n = 10;
77139   for(i=1; i<=pIdx->nColumn; i++){
77140     a[i] = n;
77141     if( n>5 ) n--;
77142   }
77143   if( pIdx->onError!=OE_None ){
77144     a[pIdx->nColumn] = 1;
77145   }
77146 }
77147
77148 /*
77149 ** This routine will drop an existing named index.  This routine
77150 ** implements the DROP INDEX statement.
77151 */
77152 SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
77153   Index *pIndex;
77154   Vdbe *v;
77155   sqlite3 *db = pParse->db;
77156   int iDb;
77157
77158   assert( pParse->nErr==0 );   /* Never called with prior errors */
77159   if( db->mallocFailed ){
77160     goto exit_drop_index;
77161   }
77162   assert( pName->nSrc==1 );
77163   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
77164     goto exit_drop_index;
77165   }
77166   pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
77167   if( pIndex==0 ){
77168     if( !ifExists ){
77169       sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
77170     }
77171     pParse->checkSchema = 1;
77172     goto exit_drop_index;
77173   }
77174   if( pIndex->autoIndex ){
77175     sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
77176       "or PRIMARY KEY constraint cannot be dropped", 0);
77177     goto exit_drop_index;
77178   }
77179   iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
77180 #ifndef SQLITE_OMIT_AUTHORIZATION
77181   {
77182     int code = SQLITE_DROP_INDEX;
77183     Table *pTab = pIndex->pTable;
77184     const char *zDb = db->aDb[iDb].zName;
77185     const char *zTab = SCHEMA_TABLE(iDb);
77186     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
77187       goto exit_drop_index;
77188     }
77189     if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
77190     if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
77191       goto exit_drop_index;
77192     }
77193   }
77194 #endif
77195
77196   /* Generate code to remove the index and from the master table */
77197   v = sqlite3GetVdbe(pParse);
77198   if( v ){
77199     sqlite3BeginWriteOperation(pParse, 1, iDb);
77200     sqlite3NestedParse(pParse,
77201        "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
77202        db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
77203        pIndex->zName
77204     );
77205     if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
77206       sqlite3NestedParse(pParse,
77207         "DELETE FROM %Q.sqlite_stat1 WHERE idx=%Q",
77208         db->aDb[iDb].zName, pIndex->zName
77209       );
77210     }
77211     sqlite3ChangeCookie(pParse, iDb);
77212     destroyRootPage(pParse, pIndex->tnum, iDb);
77213     sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
77214   }
77215
77216 exit_drop_index:
77217   sqlite3SrcListDelete(db, pName);
77218 }
77219
77220 /*
77221 ** pArray is a pointer to an array of objects.  Each object in the
77222 ** array is szEntry bytes in size.  This routine allocates a new
77223 ** object on the end of the array.
77224 **
77225 ** *pnEntry is the number of entries already in use.  *pnAlloc is
77226 ** the previously allocated size of the array.  initSize is the
77227 ** suggested initial array size allocation.
77228 **
77229 ** The index of the new entry is returned in *pIdx.
77230 **
77231 ** This routine returns a pointer to the array of objects.  This
77232 ** might be the same as the pArray parameter or it might be a different
77233 ** pointer if the array was resized.
77234 */
77235 SQLITE_PRIVATE void *sqlite3ArrayAllocate(
77236   sqlite3 *db,      /* Connection to notify of malloc failures */
77237   void *pArray,     /* Array of objects.  Might be reallocated */
77238   int szEntry,      /* Size of each object in the array */
77239   int initSize,     /* Suggested initial allocation, in elements */
77240   int *pnEntry,     /* Number of objects currently in use */
77241   int *pnAlloc,     /* Current size of the allocation, in elements */
77242   int *pIdx         /* Write the index of a new slot here */
77243 ){
77244   char *z;
77245   if( *pnEntry >= *pnAlloc ){
77246     void *pNew;
77247     int newSize;
77248     newSize = (*pnAlloc)*2 + initSize;
77249     pNew = sqlite3DbRealloc(db, pArray, newSize*szEntry);
77250     if( pNew==0 ){
77251       *pIdx = -1;
77252       return pArray;
77253     }
77254     *pnAlloc = sqlite3DbMallocSize(db, pNew)/szEntry;
77255     pArray = pNew;
77256   }
77257   z = (char*)pArray;
77258   memset(&z[*pnEntry * szEntry], 0, szEntry);
77259   *pIdx = *pnEntry;
77260   ++*pnEntry;
77261   return pArray;
77262 }
77263
77264 /*
77265 ** Append a new element to the given IdList.  Create a new IdList if
77266 ** need be.
77267 **
77268 ** A new IdList is returned, or NULL if malloc() fails.
77269 */
77270 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
77271   int i;
77272   if( pList==0 ){
77273     pList = sqlite3DbMallocZero(db, sizeof(IdList) );
77274     if( pList==0 ) return 0;
77275     pList->nAlloc = 0;
77276   }
77277   pList->a = sqlite3ArrayAllocate(
77278       db,
77279       pList->a,
77280       sizeof(pList->a[0]),
77281       5,
77282       &pList->nId,
77283       &pList->nAlloc,
77284       &i
77285   );
77286   if( i<0 ){
77287     sqlite3IdListDelete(db, pList);
77288     return 0;
77289   }
77290   pList->a[i].zName = sqlite3NameFromToken(db, pToken);
77291   return pList;
77292 }
77293
77294 /*
77295 ** Delete an IdList.
77296 */
77297 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
77298   int i;
77299   if( pList==0 ) return;
77300   for(i=0; i<pList->nId; i++){
77301     sqlite3DbFree(db, pList->a[i].zName);
77302   }
77303   sqlite3DbFree(db, pList->a);
77304   sqlite3DbFree(db, pList);
77305 }
77306
77307 /*
77308 ** Return the index in pList of the identifier named zId.  Return -1
77309 ** if not found.
77310 */
77311 SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
77312   int i;
77313   if( pList==0 ) return -1;
77314   for(i=0; i<pList->nId; i++){
77315     if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
77316   }
77317   return -1;
77318 }
77319
77320 /*
77321 ** Expand the space allocated for the given SrcList object by
77322 ** creating nExtra new slots beginning at iStart.  iStart is zero based.
77323 ** New slots are zeroed.
77324 **
77325 ** For example, suppose a SrcList initially contains two entries: A,B.
77326 ** To append 3 new entries onto the end, do this:
77327 **
77328 **    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
77329 **
77330 ** After the call above it would contain:  A, B, nil, nil, nil.
77331 ** If the iStart argument had been 1 instead of 2, then the result
77332 ** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
77333 ** the iStart value would be 0.  The result then would
77334 ** be: nil, nil, nil, A, B.
77335 **
77336 ** If a memory allocation fails the SrcList is unchanged.  The
77337 ** db->mallocFailed flag will be set to true.
77338 */
77339 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
77340   sqlite3 *db,       /* Database connection to notify of OOM errors */
77341   SrcList *pSrc,     /* The SrcList to be enlarged */
77342   int nExtra,        /* Number of new slots to add to pSrc->a[] */
77343   int iStart         /* Index in pSrc->a[] of first new slot */
77344 ){
77345   int i;
77346
77347   /* Sanity checking on calling parameters */
77348   assert( iStart>=0 );
77349   assert( nExtra>=1 );
77350   assert( pSrc!=0 );
77351   assert( iStart<=pSrc->nSrc );
77352
77353   /* Allocate additional space if needed */
77354   if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
77355     SrcList *pNew;
77356     int nAlloc = pSrc->nSrc+nExtra;
77357     int nGot;
77358     pNew = sqlite3DbRealloc(db, pSrc,
77359                sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
77360     if( pNew==0 ){
77361       assert( db->mallocFailed );
77362       return pSrc;
77363     }
77364     pSrc = pNew;
77365     nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
77366     pSrc->nAlloc = (u16)nGot;
77367   }
77368
77369   /* Move existing slots that come after the newly inserted slots
77370   ** out of the way */
77371   for(i=pSrc->nSrc-1; i>=iStart; i--){
77372     pSrc->a[i+nExtra] = pSrc->a[i];
77373   }
77374   pSrc->nSrc += (i16)nExtra;
77375
77376   /* Zero the newly allocated slots */
77377   memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
77378   for(i=iStart; i<iStart+nExtra; i++){
77379     pSrc->a[i].iCursor = -1;
77380   }
77381
77382   /* Return a pointer to the enlarged SrcList */
77383   return pSrc;
77384 }
77385
77386
77387 /*
77388 ** Append a new table name to the given SrcList.  Create a new SrcList if
77389 ** need be.  A new entry is created in the SrcList even if pTable is NULL.
77390 **
77391 ** A SrcList is returned, or NULL if there is an OOM error.  The returned
77392 ** SrcList might be the same as the SrcList that was input or it might be
77393 ** a new one.  If an OOM error does occurs, then the prior value of pList
77394 ** that is input to this routine is automatically freed.
77395 **
77396 ** If pDatabase is not null, it means that the table has an optional
77397 ** database name prefix.  Like this:  "database.table".  The pDatabase
77398 ** points to the table name and the pTable points to the database name.
77399 ** The SrcList.a[].zName field is filled with the table name which might
77400 ** come from pTable (if pDatabase is NULL) or from pDatabase.  
77401 ** SrcList.a[].zDatabase is filled with the database name from pTable,
77402 ** or with NULL if no database is specified.
77403 **
77404 ** In other words, if call like this:
77405 **
77406 **         sqlite3SrcListAppend(D,A,B,0);
77407 **
77408 ** Then B is a table name and the database name is unspecified.  If called
77409 ** like this:
77410 **
77411 **         sqlite3SrcListAppend(D,A,B,C);
77412 **
77413 ** Then C is the table name and B is the database name.  If C is defined
77414 ** then so is B.  In other words, we never have a case where:
77415 **
77416 **         sqlite3SrcListAppend(D,A,0,C);
77417 **
77418 ** Both pTable and pDatabase are assumed to be quoted.  They are dequoted
77419 ** before being added to the SrcList.
77420 */
77421 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
77422   sqlite3 *db,        /* Connection to notify of malloc failures */
77423   SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
77424   Token *pTable,      /* Table to append */
77425   Token *pDatabase    /* Database of the table */
77426 ){
77427   struct SrcList_item *pItem;
77428   assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
77429   if( pList==0 ){
77430     pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
77431     if( pList==0 ) return 0;
77432     pList->nAlloc = 1;
77433   }
77434   pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
77435   if( db->mallocFailed ){
77436     sqlite3SrcListDelete(db, pList);
77437     return 0;
77438   }
77439   pItem = &pList->a[pList->nSrc-1];
77440   if( pDatabase && pDatabase->z==0 ){
77441     pDatabase = 0;
77442   }
77443   if( pDatabase ){
77444     Token *pTemp = pDatabase;
77445     pDatabase = pTable;
77446     pTable = pTemp;
77447   }
77448   pItem->zName = sqlite3NameFromToken(db, pTable);
77449   pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
77450   return pList;
77451 }
77452
77453 /*
77454 ** Assign VdbeCursor index numbers to all tables in a SrcList
77455 */
77456 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
77457   int i;
77458   struct SrcList_item *pItem;
77459   assert(pList || pParse->db->mallocFailed );
77460   if( pList ){
77461     for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
77462       if( pItem->iCursor>=0 ) break;
77463       pItem->iCursor = pParse->nTab++;
77464       if( pItem->pSelect ){
77465         sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
77466       }
77467     }
77468   }
77469 }
77470
77471 /*
77472 ** Delete an entire SrcList including all its substructure.
77473 */
77474 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
77475   int i;
77476   struct SrcList_item *pItem;
77477   if( pList==0 ) return;
77478   for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
77479     sqlite3DbFree(db, pItem->zDatabase);
77480     sqlite3DbFree(db, pItem->zName);
77481     sqlite3DbFree(db, pItem->zAlias);
77482     sqlite3DbFree(db, pItem->zIndex);
77483     sqlite3DeleteTable(db, pItem->pTab);
77484     sqlite3SelectDelete(db, pItem->pSelect);
77485     sqlite3ExprDelete(db, pItem->pOn);
77486     sqlite3IdListDelete(db, pItem->pUsing);
77487   }
77488   sqlite3DbFree(db, pList);
77489 }
77490
77491 /*
77492 ** This routine is called by the parser to add a new term to the
77493 ** end of a growing FROM clause.  The "p" parameter is the part of
77494 ** the FROM clause that has already been constructed.  "p" is NULL
77495 ** if this is the first term of the FROM clause.  pTable and pDatabase
77496 ** are the name of the table and database named in the FROM clause term.
77497 ** pDatabase is NULL if the database name qualifier is missing - the
77498 ** usual case.  If the term has a alias, then pAlias points to the
77499 ** alias token.  If the term is a subquery, then pSubquery is the
77500 ** SELECT statement that the subquery encodes.  The pTable and
77501 ** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
77502 ** parameters are the content of the ON and USING clauses.
77503 **
77504 ** Return a new SrcList which encodes is the FROM with the new
77505 ** term added.
77506 */
77507 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
77508   Parse *pParse,          /* Parsing context */
77509   SrcList *p,             /* The left part of the FROM clause already seen */
77510   Token *pTable,          /* Name of the table to add to the FROM clause */
77511   Token *pDatabase,       /* Name of the database containing pTable */
77512   Token *pAlias,          /* The right-hand side of the AS subexpression */
77513   Select *pSubquery,      /* A subquery used in place of a table name */
77514   Expr *pOn,              /* The ON clause of a join */
77515   IdList *pUsing          /* The USING clause of a join */
77516 ){
77517   struct SrcList_item *pItem;
77518   sqlite3 *db = pParse->db;
77519   if( !p && (pOn || pUsing) ){
77520     sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s", 
77521       (pOn ? "ON" : "USING")
77522     );
77523     goto append_from_error;
77524   }
77525   p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
77526   if( p==0 || NEVER(p->nSrc==0) ){
77527     goto append_from_error;
77528   }
77529   pItem = &p->a[p->nSrc-1];
77530   assert( pAlias!=0 );
77531   if( pAlias->n ){
77532     pItem->zAlias = sqlite3NameFromToken(db, pAlias);
77533   }
77534   pItem->pSelect = pSubquery;
77535   pItem->pOn = pOn;
77536   pItem->pUsing = pUsing;
77537   return p;
77538
77539  append_from_error:
77540   assert( p==0 );
77541   sqlite3ExprDelete(db, pOn);
77542   sqlite3IdListDelete(db, pUsing);
77543   sqlite3SelectDelete(db, pSubquery);
77544   return 0;
77545 }
77546
77547 /*
77548 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added 
77549 ** element of the source-list passed as the second argument.
77550 */
77551 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
77552   assert( pIndexedBy!=0 );
77553   if( p && ALWAYS(p->nSrc>0) ){
77554     struct SrcList_item *pItem = &p->a[p->nSrc-1];
77555     assert( pItem->notIndexed==0 && pItem->zIndex==0 );
77556     if( pIndexedBy->n==1 && !pIndexedBy->z ){
77557       /* A "NOT INDEXED" clause was supplied. See parse.y 
77558       ** construct "indexed_opt" for details. */
77559       pItem->notIndexed = 1;
77560     }else{
77561       pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
77562     }
77563   }
77564 }
77565
77566 /*
77567 ** When building up a FROM clause in the parser, the join operator
77568 ** is initially attached to the left operand.  But the code generator
77569 ** expects the join operator to be on the right operand.  This routine
77570 ** Shifts all join operators from left to right for an entire FROM
77571 ** clause.
77572 **
77573 ** Example: Suppose the join is like this:
77574 **
77575 **           A natural cross join B
77576 **
77577 ** The operator is "natural cross join".  The A and B operands are stored
77578 ** in p->a[0] and p->a[1], respectively.  The parser initially stores the
77579 ** operator with A.  This routine shifts that operator over to B.
77580 */
77581 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
77582   if( p && p->a ){
77583     int i;
77584     for(i=p->nSrc-1; i>0; i--){
77585       p->a[i].jointype = p->a[i-1].jointype;
77586     }
77587     p->a[0].jointype = 0;
77588   }
77589 }
77590
77591 /*
77592 ** Begin a transaction
77593 */
77594 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
77595   sqlite3 *db;
77596   Vdbe *v;
77597   int i;
77598
77599   assert( pParse!=0 );
77600   db = pParse->db;
77601   assert( db!=0 );
77602 /*  if( db->aDb[0].pBt==0 ) return; */
77603   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
77604     return;
77605   }
77606   v = sqlite3GetVdbe(pParse);
77607   if( !v ) return;
77608   if( type!=TK_DEFERRED ){
77609     for(i=0; i<db->nDb; i++){
77610       sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
77611       sqlite3VdbeUsesBtree(v, i);
77612     }
77613   }
77614   sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
77615 }
77616
77617 /*
77618 ** Commit a transaction
77619 */
77620 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
77621   sqlite3 *db;
77622   Vdbe *v;
77623
77624   assert( pParse!=0 );
77625   db = pParse->db;
77626   assert( db!=0 );
77627 /*  if( db->aDb[0].pBt==0 ) return; */
77628   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
77629     return;
77630   }
77631   v = sqlite3GetVdbe(pParse);
77632   if( v ){
77633     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
77634   }
77635 }
77636
77637 /*
77638 ** Rollback a transaction
77639 */
77640 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
77641   sqlite3 *db;
77642   Vdbe *v;
77643
77644   assert( pParse!=0 );
77645   db = pParse->db;
77646   assert( db!=0 );
77647 /*  if( db->aDb[0].pBt==0 ) return; */
77648   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
77649     return;
77650   }
77651   v = sqlite3GetVdbe(pParse);
77652   if( v ){
77653     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
77654   }
77655 }
77656
77657 /*
77658 ** This function is called by the parser when it parses a command to create,
77659 ** release or rollback an SQL savepoint. 
77660 */
77661 SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
77662   char *zName = sqlite3NameFromToken(pParse->db, pName);
77663   if( zName ){
77664     Vdbe *v = sqlite3GetVdbe(pParse);
77665 #ifndef SQLITE_OMIT_AUTHORIZATION
77666     static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
77667     assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
77668 #endif
77669     if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
77670       sqlite3DbFree(pParse->db, zName);
77671       return;
77672     }
77673     sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
77674   }
77675 }
77676
77677 /*
77678 ** Make sure the TEMP database is open and available for use.  Return
77679 ** the number of errors.  Leave any error messages in the pParse structure.
77680 */
77681 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
77682   sqlite3 *db = pParse->db;
77683   if( db->aDb[1].pBt==0 && !pParse->explain ){
77684     int rc;
77685     Btree *pBt;
77686     static const int flags = 
77687           SQLITE_OPEN_READWRITE |
77688           SQLITE_OPEN_CREATE |
77689           SQLITE_OPEN_EXCLUSIVE |
77690           SQLITE_OPEN_DELETEONCLOSE |
77691           SQLITE_OPEN_TEMP_DB;
77692
77693     rc = sqlite3BtreeOpen(0, db, &pBt, 0, flags);
77694     if( rc!=SQLITE_OK ){
77695       sqlite3ErrorMsg(pParse, "unable to open a temporary database "
77696         "file for storing temporary tables");
77697       pParse->rc = rc;
77698       return 1;
77699     }
77700     db->aDb[1].pBt = pBt;
77701     assert( db->aDb[1].pSchema );
77702     if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
77703       db->mallocFailed = 1;
77704       return 1;
77705     }
77706   }
77707   return 0;
77708 }
77709
77710 /*
77711 ** Generate VDBE code that will verify the schema cookie and start
77712 ** a read-transaction for all named database files.
77713 **
77714 ** It is important that all schema cookies be verified and all
77715 ** read transactions be started before anything else happens in
77716 ** the VDBE program.  But this routine can be called after much other
77717 ** code has been generated.  So here is what we do:
77718 **
77719 ** The first time this routine is called, we code an OP_Goto that
77720 ** will jump to a subroutine at the end of the program.  Then we
77721 ** record every database that needs its schema verified in the
77722 ** pParse->cookieMask field.  Later, after all other code has been
77723 ** generated, the subroutine that does the cookie verifications and
77724 ** starts the transactions will be coded and the OP_Goto P2 value
77725 ** will be made to point to that subroutine.  The generation of the
77726 ** cookie verification subroutine code happens in sqlite3FinishCoding().
77727 **
77728 ** If iDb<0 then code the OP_Goto only - don't set flag to verify the
77729 ** schema on any databases.  This can be used to position the OP_Goto
77730 ** early in the code, before we know if any database tables will be used.
77731 */
77732 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
77733   Parse *pToplevel = sqlite3ParseToplevel(pParse);
77734
77735   if( pToplevel->cookieGoto==0 ){
77736     Vdbe *v = sqlite3GetVdbe(pToplevel);
77737     if( v==0 ) return;  /* This only happens if there was a prior error */
77738     pToplevel->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
77739   }
77740   if( iDb>=0 ){
77741     sqlite3 *db = pToplevel->db;
77742     int mask;
77743
77744     assert( iDb<db->nDb );
77745     assert( db->aDb[iDb].pBt!=0 || iDb==1 );
77746     assert( iDb<SQLITE_MAX_ATTACHED+2 );
77747     mask = 1<<iDb;
77748     if( (pToplevel->cookieMask & mask)==0 ){
77749       pToplevel->cookieMask |= mask;
77750       pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
77751       if( !OMIT_TEMPDB && iDb==1 ){
77752         sqlite3OpenTempDatabase(pToplevel);
77753       }
77754     }
77755   }
77756 }
77757
77758 /*
77759 ** Generate VDBE code that prepares for doing an operation that
77760 ** might change the database.
77761 **
77762 ** This routine starts a new transaction if we are not already within
77763 ** a transaction.  If we are already within a transaction, then a checkpoint
77764 ** is set if the setStatement parameter is true.  A checkpoint should
77765 ** be set for operations that might fail (due to a constraint) part of
77766 ** the way through and which will need to undo some writes without having to
77767 ** rollback the whole transaction.  For operations where all constraints
77768 ** can be checked before any changes are made to the database, it is never
77769 ** necessary to undo a write and the checkpoint should not be set.
77770 */
77771 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
77772   Parse *pToplevel = sqlite3ParseToplevel(pParse);
77773   sqlite3CodeVerifySchema(pParse, iDb);
77774   pToplevel->writeMask |= 1<<iDb;
77775   pToplevel->isMultiWrite |= setStatement;
77776 }
77777
77778 /*
77779 ** Indicate that the statement currently under construction might write
77780 ** more than one entry (example: deleting one row then inserting another,
77781 ** inserting multiple rows in a table, or inserting a row and index entries.)
77782 ** If an abort occurs after some of these writes have completed, then it will
77783 ** be necessary to undo the completed writes.
77784 */
77785 SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
77786   Parse *pToplevel = sqlite3ParseToplevel(pParse);
77787   pToplevel->isMultiWrite = 1;
77788 }
77789
77790 /* 
77791 ** The code generator calls this routine if is discovers that it is
77792 ** possible to abort a statement prior to completion.  In order to 
77793 ** perform this abort without corrupting the database, we need to make
77794 ** sure that the statement is protected by a statement transaction.
77795 **
77796 ** Technically, we only need to set the mayAbort flag if the
77797 ** isMultiWrite flag was previously set.  There is a time dependency
77798 ** such that the abort must occur after the multiwrite.  This makes
77799 ** some statements involving the REPLACE conflict resolution algorithm
77800 ** go a little faster.  But taking advantage of this time dependency
77801 ** makes it more difficult to prove that the code is correct (in 
77802 ** particular, it prevents us from writing an effective
77803 ** implementation of sqlite3AssertMayAbort()) and so we have chosen
77804 ** to take the safe route and skip the optimization.
77805 */
77806 SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
77807   Parse *pToplevel = sqlite3ParseToplevel(pParse);
77808   pToplevel->mayAbort = 1;
77809 }
77810
77811 /*
77812 ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
77813 ** error. The onError parameter determines which (if any) of the statement
77814 ** and/or current transaction is rolled back.
77815 */
77816 SQLITE_PRIVATE void sqlite3HaltConstraint(Parse *pParse, int onError, char *p4, int p4type){
77817   Vdbe *v = sqlite3GetVdbe(pParse);
77818   if( onError==OE_Abort ){
77819     sqlite3MayAbort(pParse);
77820   }
77821   sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, p4, p4type);
77822 }
77823
77824 /*
77825 ** Check to see if pIndex uses the collating sequence pColl.  Return
77826 ** true if it does and false if it does not.
77827 */
77828 #ifndef SQLITE_OMIT_REINDEX
77829 static int collationMatch(const char *zColl, Index *pIndex){
77830   int i;
77831   assert( zColl!=0 );
77832   for(i=0; i<pIndex->nColumn; i++){
77833     const char *z = pIndex->azColl[i];
77834     assert( z!=0 );
77835     if( 0==sqlite3StrICmp(z, zColl) ){
77836       return 1;
77837     }
77838   }
77839   return 0;
77840 }
77841 #endif
77842
77843 /*
77844 ** Recompute all indices of pTab that use the collating sequence pColl.
77845 ** If pColl==0 then recompute all indices of pTab.
77846 */
77847 #ifndef SQLITE_OMIT_REINDEX
77848 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
77849   Index *pIndex;              /* An index associated with pTab */
77850
77851   for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
77852     if( zColl==0 || collationMatch(zColl, pIndex) ){
77853       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
77854       sqlite3BeginWriteOperation(pParse, 0, iDb);
77855       sqlite3RefillIndex(pParse, pIndex, -1);
77856     }
77857   }
77858 }
77859 #endif
77860
77861 /*
77862 ** Recompute all indices of all tables in all databases where the
77863 ** indices use the collating sequence pColl.  If pColl==0 then recompute
77864 ** all indices everywhere.
77865 */
77866 #ifndef SQLITE_OMIT_REINDEX
77867 static void reindexDatabases(Parse *pParse, char const *zColl){
77868   Db *pDb;                    /* A single database */
77869   int iDb;                    /* The database index number */
77870   sqlite3 *db = pParse->db;   /* The database connection */
77871   HashElem *k;                /* For looping over tables in pDb */
77872   Table *pTab;                /* A table in the database */
77873
77874   for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
77875     assert( pDb!=0 );
77876     for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
77877       pTab = (Table*)sqliteHashData(k);
77878       reindexTable(pParse, pTab, zColl);
77879     }
77880   }
77881 }
77882 #endif
77883
77884 /*
77885 ** Generate code for the REINDEX command.
77886 **
77887 **        REINDEX                            -- 1
77888 **        REINDEX  <collation>               -- 2
77889 **        REINDEX  ?<database>.?<tablename>  -- 3
77890 **        REINDEX  ?<database>.?<indexname>  -- 4
77891 **
77892 ** Form 1 causes all indices in all attached databases to be rebuilt.
77893 ** Form 2 rebuilds all indices in all databases that use the named
77894 ** collating function.  Forms 3 and 4 rebuild the named index or all
77895 ** indices associated with the named table.
77896 */
77897 #ifndef SQLITE_OMIT_REINDEX
77898 SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
77899   CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
77900   char *z;                    /* Name of a table or index */
77901   const char *zDb;            /* Name of the database */
77902   Table *pTab;                /* A table in the database */
77903   Index *pIndex;              /* An index associated with pTab */
77904   int iDb;                    /* The database index number */
77905   sqlite3 *db = pParse->db;   /* The database connection */
77906   Token *pObjName;            /* Name of the table or index to be reindexed */
77907
77908   /* Read the database schema. If an error occurs, leave an error message
77909   ** and code in pParse and return NULL. */
77910   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
77911     return;
77912   }
77913
77914   if( pName1==0 ){
77915     reindexDatabases(pParse, 0);
77916     return;
77917   }else if( NEVER(pName2==0) || pName2->z==0 ){
77918     char *zColl;
77919     assert( pName1->z );
77920     zColl = sqlite3NameFromToken(pParse->db, pName1);
77921     if( !zColl ) return;
77922     pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
77923     if( pColl ){
77924       reindexDatabases(pParse, zColl);
77925       sqlite3DbFree(db, zColl);
77926       return;
77927     }
77928     sqlite3DbFree(db, zColl);
77929   }
77930   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
77931   if( iDb<0 ) return;
77932   z = sqlite3NameFromToken(db, pObjName);
77933   if( z==0 ) return;
77934   zDb = db->aDb[iDb].zName;
77935   pTab = sqlite3FindTable(db, z, zDb);
77936   if( pTab ){
77937     reindexTable(pParse, pTab, 0);
77938     sqlite3DbFree(db, z);
77939     return;
77940   }
77941   pIndex = sqlite3FindIndex(db, z, zDb);
77942   sqlite3DbFree(db, z);
77943   if( pIndex ){
77944     sqlite3BeginWriteOperation(pParse, 0, iDb);
77945     sqlite3RefillIndex(pParse, pIndex, -1);
77946     return;
77947   }
77948   sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
77949 }
77950 #endif
77951
77952 /*
77953 ** Return a dynamicly allocated KeyInfo structure that can be used
77954 ** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
77955 **
77956 ** If successful, a pointer to the new structure is returned. In this case
77957 ** the caller is responsible for calling sqlite3DbFree(db, ) on the returned 
77958 ** pointer. If an error occurs (out of memory or missing collation 
77959 ** sequence), NULL is returned and the state of pParse updated to reflect
77960 ** the error.
77961 */
77962 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
77963   int i;
77964   int nCol = pIdx->nColumn;
77965   int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
77966   sqlite3 *db = pParse->db;
77967   KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes);
77968
77969   if( pKey ){
77970     pKey->db = pParse->db;
77971     pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
77972     assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
77973     for(i=0; i<nCol; i++){
77974       char *zColl = pIdx->azColl[i];
77975       assert( zColl );
77976       pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl);
77977       pKey->aSortOrder[i] = pIdx->aSortOrder[i];
77978     }
77979     pKey->nField = (u16)nCol;
77980   }
77981
77982   if( pParse->nErr ){
77983     sqlite3DbFree(db, pKey);
77984     pKey = 0;
77985   }
77986   return pKey;
77987 }
77988
77989 /************** End of build.c ***********************************************/
77990 /************** Begin file callback.c ****************************************/
77991 /*
77992 ** 2005 May 23 
77993 **
77994 ** The author disclaims copyright to this source code.  In place of
77995 ** a legal notice, here is a blessing:
77996 **
77997 **    May you do good and not evil.
77998 **    May you find forgiveness for yourself and forgive others.
77999 **    May you share freely, never taking more than you give.
78000 **
78001 *************************************************************************
78002 **
78003 ** This file contains functions used to access the internal hash tables
78004 ** of user defined functions and collation sequences.
78005 */
78006
78007
78008 /*
78009 ** Invoke the 'collation needed' callback to request a collation sequence
78010 ** in the encoding enc of name zName, length nName.
78011 */
78012 static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
78013   assert( !db->xCollNeeded || !db->xCollNeeded16 );
78014   if( db->xCollNeeded ){
78015     char *zExternal = sqlite3DbStrDup(db, zName);
78016     if( !zExternal ) return;
78017     db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
78018     sqlite3DbFree(db, zExternal);
78019   }
78020 #ifndef SQLITE_OMIT_UTF16
78021   if( db->xCollNeeded16 ){
78022     char const *zExternal;
78023     sqlite3_value *pTmp = sqlite3ValueNew(db);
78024     sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
78025     zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
78026     if( zExternal ){
78027       db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
78028     }
78029     sqlite3ValueFree(pTmp);
78030   }
78031 #endif
78032 }
78033
78034 /*
78035 ** This routine is called if the collation factory fails to deliver a
78036 ** collation function in the best encoding but there may be other versions
78037 ** of this collation function (for other text encodings) available. Use one
78038 ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
78039 ** possible.
78040 */
78041 static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
78042   CollSeq *pColl2;
78043   char *z = pColl->zName;
78044   int i;
78045   static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
78046   for(i=0; i<3; i++){
78047     pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
78048     if( pColl2->xCmp!=0 ){
78049       memcpy(pColl, pColl2, sizeof(CollSeq));
78050       pColl->xDel = 0;         /* Do not copy the destructor */
78051       return SQLITE_OK;
78052     }
78053   }
78054   return SQLITE_ERROR;
78055 }
78056
78057 /*
78058 ** This function is responsible for invoking the collation factory callback
78059 ** or substituting a collation sequence of a different encoding when the
78060 ** requested collation sequence is not available in the desired encoding.
78061 ** 
78062 ** If it is not NULL, then pColl must point to the database native encoding 
78063 ** collation sequence with name zName, length nName.
78064 **
78065 ** The return value is either the collation sequence to be used in database
78066 ** db for collation type name zName, length nName, or NULL, if no collation
78067 ** sequence can be found.
78068 **
78069 ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
78070 */
78071 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
78072   sqlite3* db,          /* The database connection */
78073   u8 enc,               /* The desired encoding for the collating sequence */
78074   CollSeq *pColl,       /* Collating sequence with native encoding, or NULL */
78075   const char *zName     /* Collating sequence name */
78076 ){
78077   CollSeq *p;
78078
78079   p = pColl;
78080   if( !p ){
78081     p = sqlite3FindCollSeq(db, enc, zName, 0);
78082   }
78083   if( !p || !p->xCmp ){
78084     /* No collation sequence of this type for this encoding is registered.
78085     ** Call the collation factory to see if it can supply us with one.
78086     */
78087     callCollNeeded(db, enc, zName);
78088     p = sqlite3FindCollSeq(db, enc, zName, 0);
78089   }
78090   if( p && !p->xCmp && synthCollSeq(db, p) ){
78091     p = 0;
78092   }
78093   assert( !p || p->xCmp );
78094   return p;
78095 }
78096
78097 /*
78098 ** This routine is called on a collation sequence before it is used to
78099 ** check that it is defined. An undefined collation sequence exists when
78100 ** a database is loaded that contains references to collation sequences
78101 ** that have not been defined by sqlite3_create_collation() etc.
78102 **
78103 ** If required, this routine calls the 'collation needed' callback to
78104 ** request a definition of the collating sequence. If this doesn't work, 
78105 ** an equivalent collating sequence that uses a text encoding different
78106 ** from the main database is substituted, if one is available.
78107 */
78108 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
78109   if( pColl ){
78110     const char *zName = pColl->zName;
78111     sqlite3 *db = pParse->db;
78112     CollSeq *p = sqlite3GetCollSeq(db, ENC(db), pColl, zName);
78113     if( !p ){
78114       sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
78115       pParse->nErr++;
78116       return SQLITE_ERROR;
78117     }
78118     assert( p==pColl );
78119   }
78120   return SQLITE_OK;
78121 }
78122
78123
78124
78125 /*
78126 ** Locate and return an entry from the db.aCollSeq hash table. If the entry
78127 ** specified by zName and nName is not found and parameter 'create' is
78128 ** true, then create a new entry. Otherwise return NULL.
78129 **
78130 ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
78131 ** array of three CollSeq structures. The first is the collation sequence
78132 ** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
78133 **
78134 ** Stored immediately after the three collation sequences is a copy of
78135 ** the collation sequence name. A pointer to this string is stored in
78136 ** each collation sequence structure.
78137 */
78138 static CollSeq *findCollSeqEntry(
78139   sqlite3 *db,          /* Database connection */
78140   const char *zName,    /* Name of the collating sequence */
78141   int create            /* Create a new entry if true */
78142 ){
78143   CollSeq *pColl;
78144   int nName = sqlite3Strlen30(zName);
78145   pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
78146
78147   if( 0==pColl && create ){
78148     pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
78149     if( pColl ){
78150       CollSeq *pDel = 0;
78151       pColl[0].zName = (char*)&pColl[3];
78152       pColl[0].enc = SQLITE_UTF8;
78153       pColl[1].zName = (char*)&pColl[3];
78154       pColl[1].enc = SQLITE_UTF16LE;
78155       pColl[2].zName = (char*)&pColl[3];
78156       pColl[2].enc = SQLITE_UTF16BE;
78157       memcpy(pColl[0].zName, zName, nName);
78158       pColl[0].zName[nName] = 0;
78159       pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
78160
78161       /* If a malloc() failure occurred in sqlite3HashInsert(), it will 
78162       ** return the pColl pointer to be deleted (because it wasn't added
78163       ** to the hash table).
78164       */
78165       assert( pDel==0 || pDel==pColl );
78166       if( pDel!=0 ){
78167         db->mallocFailed = 1;
78168         sqlite3DbFree(db, pDel);
78169         pColl = 0;
78170       }
78171     }
78172   }
78173   return pColl;
78174 }
78175
78176 /*
78177 ** Parameter zName points to a UTF-8 encoded string nName bytes long.
78178 ** Return the CollSeq* pointer for the collation sequence named zName
78179 ** for the encoding 'enc' from the database 'db'.
78180 **
78181 ** If the entry specified is not found and 'create' is true, then create a
78182 ** new entry.  Otherwise return NULL.
78183 **
78184 ** A separate function sqlite3LocateCollSeq() is a wrapper around
78185 ** this routine.  sqlite3LocateCollSeq() invokes the collation factory
78186 ** if necessary and generates an error message if the collating sequence
78187 ** cannot be found.
78188 **
78189 ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
78190 */
78191 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
78192   sqlite3 *db,
78193   u8 enc,
78194   const char *zName,
78195   int create
78196 ){
78197   CollSeq *pColl;
78198   if( zName ){
78199     pColl = findCollSeqEntry(db, zName, create);
78200   }else{
78201     pColl = db->pDfltColl;
78202   }
78203   assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
78204   assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
78205   if( pColl ) pColl += enc-1;
78206   return pColl;
78207 }
78208
78209 /* During the search for the best function definition, this procedure
78210 ** is called to test how well the function passed as the first argument
78211 ** matches the request for a function with nArg arguments in a system
78212 ** that uses encoding enc. The value returned indicates how well the
78213 ** request is matched. A higher value indicates a better match.
78214 **
78215 ** The returned value is always between 0 and 6, as follows:
78216 **
78217 ** 0: Not a match, or if nArg<0 and the function is has no implementation.
78218 ** 1: A variable arguments function that prefers UTF-8 when a UTF-16
78219 **    encoding is requested, or vice versa.
78220 ** 2: A variable arguments function that uses UTF-16BE when UTF-16LE is
78221 **    requested, or vice versa.
78222 ** 3: A variable arguments function using the same text encoding.
78223 ** 4: A function with the exact number of arguments requested that
78224 **    prefers UTF-8 when a UTF-16 encoding is requested, or vice versa.
78225 ** 5: A function with the exact number of arguments requested that
78226 **    prefers UTF-16LE when UTF-16BE is requested, or vice versa.
78227 ** 6: An exact match.
78228 **
78229 */
78230 static int matchQuality(FuncDef *p, int nArg, u8 enc){
78231   int match = 0;
78232   if( p->nArg==-1 || p->nArg==nArg 
78233    || (nArg==-1 && (p->xFunc!=0 || p->xStep!=0))
78234   ){
78235     match = 1;
78236     if( p->nArg==nArg || nArg==-1 ){
78237       match = 4;
78238     }
78239     if( enc==p->iPrefEnc ){
78240       match += 2;
78241     }
78242     else if( (enc==SQLITE_UTF16LE && p->iPrefEnc==SQLITE_UTF16BE) ||
78243              (enc==SQLITE_UTF16BE && p->iPrefEnc==SQLITE_UTF16LE) ){
78244       match += 1;
78245     }
78246   }
78247   return match;
78248 }
78249
78250 /*
78251 ** Search a FuncDefHash for a function with the given name.  Return
78252 ** a pointer to the matching FuncDef if found, or 0 if there is no match.
78253 */
78254 static FuncDef *functionSearch(
78255   FuncDefHash *pHash,  /* Hash table to search */
78256   int h,               /* Hash of the name */
78257   const char *zFunc,   /* Name of function */
78258   int nFunc            /* Number of bytes in zFunc */
78259 ){
78260   FuncDef *p;
78261   for(p=pHash->a[h]; p; p=p->pHash){
78262     if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
78263       return p;
78264     }
78265   }
78266   return 0;
78267 }
78268
78269 /*
78270 ** Insert a new FuncDef into a FuncDefHash hash table.
78271 */
78272 SQLITE_PRIVATE void sqlite3FuncDefInsert(
78273   FuncDefHash *pHash,  /* The hash table into which to insert */
78274   FuncDef *pDef        /* The function definition to insert */
78275 ){
78276   FuncDef *pOther;
78277   int nName = sqlite3Strlen30(pDef->zName);
78278   u8 c1 = (u8)pDef->zName[0];
78279   int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
78280   pOther = functionSearch(pHash, h, pDef->zName, nName);
78281   if( pOther ){
78282     assert( pOther!=pDef && pOther->pNext!=pDef );
78283     pDef->pNext = pOther->pNext;
78284     pOther->pNext = pDef;
78285   }else{
78286     pDef->pNext = 0;
78287     pDef->pHash = pHash->a[h];
78288     pHash->a[h] = pDef;
78289   }
78290 }
78291   
78292   
78293
78294 /*
78295 ** Locate a user function given a name, a number of arguments and a flag
78296 ** indicating whether the function prefers UTF-16 over UTF-8.  Return a
78297 ** pointer to the FuncDef structure that defines that function, or return
78298 ** NULL if the function does not exist.
78299 **
78300 ** If the createFlag argument is true, then a new (blank) FuncDef
78301 ** structure is created and liked into the "db" structure if a
78302 ** no matching function previously existed.  When createFlag is true
78303 ** and the nArg parameter is -1, then only a function that accepts
78304 ** any number of arguments will be returned.
78305 **
78306 ** If createFlag is false and nArg is -1, then the first valid
78307 ** function found is returned.  A function is valid if either xFunc
78308 ** or xStep is non-zero.
78309 **
78310 ** If createFlag is false, then a function with the required name and
78311 ** number of arguments may be returned even if the eTextRep flag does not
78312 ** match that requested.
78313 */
78314 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
78315   sqlite3 *db,       /* An open database */
78316   const char *zName, /* Name of the function.  Not null-terminated */
78317   int nName,         /* Number of characters in the name */
78318   int nArg,          /* Number of arguments.  -1 means any number */
78319   u8 enc,            /* Preferred text encoding */
78320   int createFlag     /* Create new entry if true and does not otherwise exist */
78321 ){
78322   FuncDef *p;         /* Iterator variable */
78323   FuncDef *pBest = 0; /* Best match found so far */
78324   int bestScore = 0;  /* Score of best match */
78325   int h;              /* Hash value */
78326
78327
78328   assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
78329   h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
78330
78331   /* First search for a match amongst the application-defined functions.
78332   */
78333   p = functionSearch(&db->aFunc, h, zName, nName);
78334   while( p ){
78335     int score = matchQuality(p, nArg, enc);
78336     if( score>bestScore ){
78337       pBest = p;
78338       bestScore = score;
78339     }
78340     p = p->pNext;
78341   }
78342
78343   /* If no match is found, search the built-in functions.
78344   **
78345   ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
78346   ** functions even if a prior app-defined function was found.  And give
78347   ** priority to built-in functions.
78348   **
78349   ** Except, if createFlag is true, that means that we are trying to
78350   ** install a new function.  Whatever FuncDef structure is returned it will
78351   ** have fields overwritten with new information appropriate for the
78352   ** new function.  But the FuncDefs for built-in functions are read-only.
78353   ** So we must not search for built-ins when creating a new function.
78354   */ 
78355   if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
78356     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
78357     bestScore = 0;
78358     p = functionSearch(pHash, h, zName, nName);
78359     while( p ){
78360       int score = matchQuality(p, nArg, enc);
78361       if( score>bestScore ){
78362         pBest = p;
78363         bestScore = score;
78364       }
78365       p = p->pNext;
78366     }
78367   }
78368
78369   /* If the createFlag parameter is true and the search did not reveal an
78370   ** exact match for the name, number of arguments and encoding, then add a
78371   ** new entry to the hash table and return it.
78372   */
78373   if( createFlag && (bestScore<6 || pBest->nArg!=nArg) && 
78374       (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
78375     pBest->zName = (char *)&pBest[1];
78376     pBest->nArg = (u16)nArg;
78377     pBest->iPrefEnc = enc;
78378     memcpy(pBest->zName, zName, nName);
78379     pBest->zName[nName] = 0;
78380     sqlite3FuncDefInsert(&db->aFunc, pBest);
78381   }
78382
78383   if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
78384     return pBest;
78385   }
78386   return 0;
78387 }
78388
78389 /*
78390 ** Free all resources held by the schema structure. The void* argument points
78391 ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the 
78392 ** pointer itself, it just cleans up subsiduary resources (i.e. the contents
78393 ** of the schema hash tables).
78394 **
78395 ** The Schema.cache_size variable is not cleared.
78396 */
78397 SQLITE_PRIVATE void sqlite3SchemaFree(void *p){
78398   Hash temp1;
78399   Hash temp2;
78400   HashElem *pElem;
78401   Schema *pSchema = (Schema *)p;
78402
78403   temp1 = pSchema->tblHash;
78404   temp2 = pSchema->trigHash;
78405   sqlite3HashInit(&pSchema->trigHash);
78406   sqlite3HashClear(&pSchema->idxHash);
78407   for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
78408     sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
78409   }
78410   sqlite3HashClear(&temp2);
78411   sqlite3HashInit(&pSchema->tblHash);
78412   for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
78413     Table *pTab = sqliteHashData(pElem);
78414     sqlite3DeleteTable(0, pTab);
78415   }
78416   sqlite3HashClear(&temp1);
78417   sqlite3HashClear(&pSchema->fkeyHash);
78418   pSchema->pSeqTab = 0;
78419   pSchema->flags &= ~DB_SchemaLoaded;
78420 }
78421
78422 /*
78423 ** Find and return the schema associated with a BTree.  Create
78424 ** a new one if necessary.
78425 */
78426 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
78427   Schema * p;
78428   if( pBt ){
78429     p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaFree);
78430   }else{
78431     p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
78432   }
78433   if( !p ){
78434     db->mallocFailed = 1;
78435   }else if ( 0==p->file_format ){
78436     sqlite3HashInit(&p->tblHash);
78437     sqlite3HashInit(&p->idxHash);
78438     sqlite3HashInit(&p->trigHash);
78439     sqlite3HashInit(&p->fkeyHash);
78440     p->enc = SQLITE_UTF8;
78441   }
78442   return p;
78443 }
78444
78445 /************** End of callback.c ********************************************/
78446 /************** Begin file delete.c ******************************************/
78447 /*
78448 ** 2001 September 15
78449 **
78450 ** The author disclaims copyright to this source code.  In place of
78451 ** a legal notice, here is a blessing:
78452 **
78453 **    May you do good and not evil.
78454 **    May you find forgiveness for yourself and forgive others.
78455 **    May you share freely, never taking more than you give.
78456 **
78457 *************************************************************************
78458 ** This file contains C code routines that are called by the parser
78459 ** in order to generate code for DELETE FROM statements.
78460 */
78461
78462 /*
78463 ** Look up every table that is named in pSrc.  If any table is not found,
78464 ** add an error message to pParse->zErrMsg and return NULL.  If all tables
78465 ** are found, return a pointer to the last table.
78466 */
78467 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
78468   struct SrcList_item *pItem = pSrc->a;
78469   Table *pTab;
78470   assert( pItem && pSrc->nSrc==1 );
78471   pTab = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
78472   sqlite3DeleteTable(pParse->db, pItem->pTab);
78473   pItem->pTab = pTab;
78474   if( pTab ){
78475     pTab->nRef++;
78476   }
78477   if( sqlite3IndexedByLookup(pParse, pItem) ){
78478     pTab = 0;
78479   }
78480   return pTab;
78481 }
78482
78483 /*
78484 ** Check to make sure the given table is writable.  If it is not
78485 ** writable, generate an error message and return 1.  If it is
78486 ** writable return 0;
78487 */
78488 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
78489   /* A table is not writable under the following circumstances:
78490   **
78491   **   1) It is a virtual table and no implementation of the xUpdate method
78492   **      has been provided, or
78493   **   2) It is a system table (i.e. sqlite_master), this call is not
78494   **      part of a nested parse and writable_schema pragma has not 
78495   **      been specified.
78496   **
78497   ** In either case leave an error message in pParse and return non-zero.
78498   */
78499   if( ( IsVirtual(pTab) 
78500      && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
78501    || ( (pTab->tabFlags & TF_Readonly)!=0
78502      && (pParse->db->flags & SQLITE_WriteSchema)==0
78503      && pParse->nested==0 )
78504   ){
78505     sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
78506     return 1;
78507   }
78508
78509 #ifndef SQLITE_OMIT_VIEW
78510   if( !viewOk && pTab->pSelect ){
78511     sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
78512     return 1;
78513   }
78514 #endif
78515   return 0;
78516 }
78517
78518
78519 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
78520 /*
78521 ** Evaluate a view and store its result in an ephemeral table.  The
78522 ** pWhere argument is an optional WHERE clause that restricts the
78523 ** set of rows in the view that are to be added to the ephemeral table.
78524 */
78525 SQLITE_PRIVATE void sqlite3MaterializeView(
78526   Parse *pParse,       /* Parsing context */
78527   Table *pView,        /* View definition */
78528   Expr *pWhere,        /* Optional WHERE clause to be added */
78529   int iCur             /* Cursor number for ephemerial table */
78530 ){
78531   SelectDest dest;
78532   Select *pDup;
78533   sqlite3 *db = pParse->db;
78534
78535   pDup = sqlite3SelectDup(db, pView->pSelect, 0);
78536   if( pWhere ){
78537     SrcList *pFrom;
78538     
78539     pWhere = sqlite3ExprDup(db, pWhere, 0);
78540     pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
78541     if( pFrom ){
78542       assert( pFrom->nSrc==1 );
78543       pFrom->a[0].zAlias = sqlite3DbStrDup(db, pView->zName);
78544       pFrom->a[0].pSelect = pDup;
78545       assert( pFrom->a[0].pOn==0 );
78546       assert( pFrom->a[0].pUsing==0 );
78547     }else{
78548       sqlite3SelectDelete(db, pDup);
78549     }
78550     pDup = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
78551   }
78552   sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
78553   sqlite3Select(pParse, pDup, &dest);
78554   sqlite3SelectDelete(db, pDup);
78555 }
78556 #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
78557
78558 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
78559 /*
78560 ** Generate an expression tree to implement the WHERE, ORDER BY,
78561 ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
78562 **
78563 **     DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
78564 **                            \__________________________/
78565 **                               pLimitWhere (pInClause)
78566 */
78567 SQLITE_PRIVATE Expr *sqlite3LimitWhere(
78568   Parse *pParse,               /* The parser context */
78569   SrcList *pSrc,               /* the FROM clause -- which tables to scan */
78570   Expr *pWhere,                /* The WHERE clause.  May be null */
78571   ExprList *pOrderBy,          /* The ORDER BY clause.  May be null */
78572   Expr *pLimit,                /* The LIMIT clause.  May be null */
78573   Expr *pOffset,               /* The OFFSET clause.  May be null */
78574   char *zStmtType              /* Either DELETE or UPDATE.  For error messages. */
78575 ){
78576   Expr *pWhereRowid = NULL;    /* WHERE rowid .. */
78577   Expr *pInClause = NULL;      /* WHERE rowid IN ( select ) */
78578   Expr *pSelectRowid = NULL;   /* SELECT rowid ... */
78579   ExprList *pEList = NULL;     /* Expression list contaning only pSelectRowid */
78580   SrcList *pSelectSrc = NULL;  /* SELECT rowid FROM x ... (dup of pSrc) */
78581   Select *pSelect = NULL;      /* Complete SELECT tree */
78582
78583   /* Check that there isn't an ORDER BY without a LIMIT clause.
78584   */
78585   if( pOrderBy && (pLimit == 0) ) {
78586     sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
78587     pParse->parseError = 1;
78588     goto limit_where_cleanup_2;
78589   }
78590
78591   /* We only need to generate a select expression if there
78592   ** is a limit/offset term to enforce.
78593   */
78594   if( pLimit == 0 ) {
78595     /* if pLimit is null, pOffset will always be null as well. */
78596     assert( pOffset == 0 );
78597     return pWhere;
78598   }
78599
78600   /* Generate a select expression tree to enforce the limit/offset 
78601   ** term for the DELETE or UPDATE statement.  For example:
78602   **   DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
78603   ** becomes:
78604   **   DELETE FROM table_a WHERE rowid IN ( 
78605   **     SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
78606   **   );
78607   */
78608
78609   pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
78610   if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
78611   pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
78612   if( pEList == 0 ) goto limit_where_cleanup_2;
78613
78614   /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
78615   ** and the SELECT subtree. */
78616   pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
78617   if( pSelectSrc == 0 ) {
78618     sqlite3ExprListDelete(pParse->db, pEList);
78619     goto limit_where_cleanup_2;
78620   }
78621
78622   /* generate the SELECT expression tree. */
78623   pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
78624                              pOrderBy,0,pLimit,pOffset);
78625   if( pSelect == 0 ) return 0;
78626
78627   /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
78628   pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
78629   if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
78630   pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
78631   if( pInClause == 0 ) goto limit_where_cleanup_1;
78632
78633   pInClause->x.pSelect = pSelect;
78634   pInClause->flags |= EP_xIsSelect;
78635   sqlite3ExprSetHeight(pParse, pInClause);
78636   return pInClause;
78637
78638   /* something went wrong. clean up anything allocated. */
78639 limit_where_cleanup_1:
78640   sqlite3SelectDelete(pParse->db, pSelect);
78641   return 0;
78642
78643 limit_where_cleanup_2:
78644   sqlite3ExprDelete(pParse->db, pWhere);
78645   sqlite3ExprListDelete(pParse->db, pOrderBy);
78646   sqlite3ExprDelete(pParse->db, pLimit);
78647   sqlite3ExprDelete(pParse->db, pOffset);
78648   return 0;
78649 }
78650 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
78651
78652 /*
78653 ** Generate code for a DELETE FROM statement.
78654 **
78655 **     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
78656 **                 \________/       \________________/
78657 **                  pTabList              pWhere
78658 */
78659 SQLITE_PRIVATE void sqlite3DeleteFrom(
78660   Parse *pParse,         /* The parser context */
78661   SrcList *pTabList,     /* The table from which we should delete things */
78662   Expr *pWhere           /* The WHERE clause.  May be null */
78663 ){
78664   Vdbe *v;               /* The virtual database engine */
78665   Table *pTab;           /* The table from which records will be deleted */
78666   const char *zDb;       /* Name of database holding pTab */
78667   int end, addr = 0;     /* A couple addresses of generated code */
78668   int i;                 /* Loop counter */
78669   WhereInfo *pWInfo;     /* Information about the WHERE clause */
78670   Index *pIdx;           /* For looping over indices of the table */
78671   int iCur;              /* VDBE Cursor number for pTab */
78672   sqlite3 *db;           /* Main database structure */
78673   AuthContext sContext;  /* Authorization context */
78674   NameContext sNC;       /* Name context to resolve expressions in */
78675   int iDb;               /* Database number */
78676   int memCnt = -1;       /* Memory cell used for change counting */
78677   int rcauth;            /* Value returned by authorization callback */
78678
78679 #ifndef SQLITE_OMIT_TRIGGER
78680   int isView;                  /* True if attempting to delete from a view */
78681   Trigger *pTrigger;           /* List of table triggers, if required */
78682 #endif
78683
78684   memset(&sContext, 0, sizeof(sContext));
78685   db = pParse->db;
78686   if( pParse->nErr || db->mallocFailed ){
78687     goto delete_from_cleanup;
78688   }
78689   assert( pTabList->nSrc==1 );
78690
78691   /* Locate the table which we want to delete.  This table has to be
78692   ** put in an SrcList structure because some of the subroutines we
78693   ** will be calling are designed to work with multiple tables and expect
78694   ** an SrcList* parameter instead of just a Table* parameter.
78695   */
78696   pTab = sqlite3SrcListLookup(pParse, pTabList);
78697   if( pTab==0 )  goto delete_from_cleanup;
78698
78699   /* Figure out if we have any triggers and if the table being
78700   ** deleted from is a view
78701   */
78702 #ifndef SQLITE_OMIT_TRIGGER
78703   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
78704   isView = pTab->pSelect!=0;
78705 #else
78706 # define pTrigger 0
78707 # define isView 0
78708 #endif
78709 #ifdef SQLITE_OMIT_VIEW
78710 # undef isView
78711 # define isView 0
78712 #endif
78713
78714   /* If pTab is really a view, make sure it has been initialized.
78715   */
78716   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
78717     goto delete_from_cleanup;
78718   }
78719
78720   if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
78721     goto delete_from_cleanup;
78722   }
78723   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
78724   assert( iDb<db->nDb );
78725   zDb = db->aDb[iDb].zName;
78726   rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
78727   assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
78728   if( rcauth==SQLITE_DENY ){
78729     goto delete_from_cleanup;
78730   }
78731   assert(!isView || pTrigger);
78732
78733   /* Assign  cursor number to the table and all its indices.
78734   */
78735   assert( pTabList->nSrc==1 );
78736   iCur = pTabList->a[0].iCursor = pParse->nTab++;
78737   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
78738     pParse->nTab++;
78739   }
78740
78741   /* Start the view context
78742   */
78743   if( isView ){
78744     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
78745   }
78746
78747   /* Begin generating code.
78748   */
78749   v = sqlite3GetVdbe(pParse);
78750   if( v==0 ){
78751     goto delete_from_cleanup;
78752   }
78753   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
78754   sqlite3BeginWriteOperation(pParse, 1, iDb);
78755
78756   /* If we are trying to delete from a view, realize that view into
78757   ** a ephemeral table.
78758   */
78759 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
78760   if( isView ){
78761     sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
78762   }
78763 #endif
78764
78765   /* Resolve the column names in the WHERE clause.
78766   */
78767   memset(&sNC, 0, sizeof(sNC));
78768   sNC.pParse = pParse;
78769   sNC.pSrcList = pTabList;
78770   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
78771     goto delete_from_cleanup;
78772   }
78773
78774   /* Initialize the counter of the number of rows deleted, if
78775   ** we are counting rows.
78776   */
78777   if( db->flags & SQLITE_CountRows ){
78778     memCnt = ++pParse->nMem;
78779     sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
78780   }
78781
78782 #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
78783   /* Special case: A DELETE without a WHERE clause deletes everything.
78784   ** It is easier just to erase the whole table. Prior to version 3.6.5,
78785   ** this optimization caused the row change count (the value returned by 
78786   ** API function sqlite3_count_changes) to be set incorrectly.  */
78787   if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab) 
78788    && 0==sqlite3FkRequired(pParse, pTab, 0, 0)
78789   ){
78790     assert( !isView );
78791     sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
78792                       pTab->zName, P4_STATIC);
78793     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
78794       assert( pIdx->pSchema==pTab->pSchema );
78795       sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
78796     }
78797   }else
78798 #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
78799   /* The usual case: There is a WHERE clause so we have to scan through
78800   ** the table and pick which records to delete.
78801   */
78802   {
78803     int iRowSet = ++pParse->nMem;   /* Register for rowset of rows to delete */
78804     int iRowid = ++pParse->nMem;    /* Used for storing rowid values. */
78805     int regRowid;                   /* Actual register containing rowids */
78806
78807     /* Collect rowids of every row to be deleted.
78808     */
78809     sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
78810     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,0,WHERE_DUPLICATES_OK);
78811     if( pWInfo==0 ) goto delete_from_cleanup;
78812     regRowid = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, iRowid);
78813     sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, regRowid);
78814     if( db->flags & SQLITE_CountRows ){
78815       sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
78816     }
78817     sqlite3WhereEnd(pWInfo);
78818
78819     /* Delete every item whose key was written to the list during the
78820     ** database scan.  We have to delete items after the scan is complete
78821     ** because deleting an item can change the scan order.  */
78822     end = sqlite3VdbeMakeLabel(v);
78823
78824     /* Unless this is a view, open cursors for the table we are 
78825     ** deleting from and all its indices. If this is a view, then the
78826     ** only effect this statement has is to fire the INSTEAD OF 
78827     ** triggers.  */
78828     if( !isView ){
78829       sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
78830     }
78831
78832     addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, end, iRowid);
78833
78834     /* Delete the row */
78835 #ifndef SQLITE_OMIT_VIRTUALTABLE
78836     if( IsVirtual(pTab) ){
78837       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
78838       sqlite3VtabMakeWritable(pParse, pTab);
78839       sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVTab, P4_VTAB);
78840       sqlite3MayAbort(pParse);
78841     }else
78842 #endif
78843     {
78844       int count = (pParse->nested==0);    /* True to count changes */
78845       sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, count, pTrigger, OE_Default);
78846     }
78847
78848     /* End of the delete loop */
78849     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
78850     sqlite3VdbeResolveLabel(v, end);
78851
78852     /* Close the cursors open on the table and its indexes. */
78853     if( !isView && !IsVirtual(pTab) ){
78854       for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
78855         sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum);
78856       }
78857       sqlite3VdbeAddOp1(v, OP_Close, iCur);
78858     }
78859   }
78860
78861   /* Update the sqlite_sequence table by storing the content of the
78862   ** maximum rowid counter values recorded while inserting into
78863   ** autoincrement tables.
78864   */
78865   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
78866     sqlite3AutoincrementEnd(pParse);
78867   }
78868
78869   /* Return the number of rows that were deleted. If this routine is 
78870   ** generating code because of a call to sqlite3NestedParse(), do not
78871   ** invoke the callback function.
78872   */
78873   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
78874     sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
78875     sqlite3VdbeSetNumCols(v, 1);
78876     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
78877   }
78878
78879 delete_from_cleanup:
78880   sqlite3AuthContextPop(&sContext);
78881   sqlite3SrcListDelete(db, pTabList);
78882   sqlite3ExprDelete(db, pWhere);
78883   return;
78884 }
78885 /* Make sure "isView" and other macros defined above are undefined. Otherwise
78886 ** thely may interfere with compilation of other functions in this file
78887 ** (or in another file, if this file becomes part of the amalgamation).  */
78888 #ifdef isView
78889  #undef isView
78890 #endif
78891 #ifdef pTrigger
78892  #undef pTrigger
78893 #endif
78894
78895 /*
78896 ** This routine generates VDBE code that causes a single row of a
78897 ** single table to be deleted.
78898 **
78899 ** The VDBE must be in a particular state when this routine is called.
78900 ** These are the requirements:
78901 **
78902 **   1.  A read/write cursor pointing to pTab, the table containing the row
78903 **       to be deleted, must be opened as cursor number $iCur.
78904 **
78905 **   2.  Read/write cursors for all indices of pTab must be open as
78906 **       cursor number base+i for the i-th index.
78907 **
78908 **   3.  The record number of the row to be deleted must be stored in
78909 **       memory cell iRowid.
78910 **
78911 ** This routine generates code to remove both the table record and all 
78912 ** index entries that point to that record.
78913 */
78914 SQLITE_PRIVATE void sqlite3GenerateRowDelete(
78915   Parse *pParse,     /* Parsing context */
78916   Table *pTab,       /* Table containing the row to be deleted */
78917   int iCur,          /* Cursor number for the table */
78918   int iRowid,        /* Memory cell that contains the rowid to delete */
78919   int count,         /* If non-zero, increment the row change counter */
78920   Trigger *pTrigger, /* List of triggers to (potentially) fire */
78921   int onconf         /* Default ON CONFLICT policy for triggers */
78922 ){
78923   Vdbe *v = pParse->pVdbe;        /* Vdbe */
78924   int iOld = 0;                   /* First register in OLD.* array */
78925   int iLabel;                     /* Label resolved to end of generated code */
78926
78927   /* Vdbe is guaranteed to have been allocated by this stage. */
78928   assert( v );
78929
78930   /* Seek cursor iCur to the row to delete. If this row no longer exists 
78931   ** (this can happen if a trigger program has already deleted it), do
78932   ** not attempt to delete it or fire any DELETE triggers.  */
78933   iLabel = sqlite3VdbeMakeLabel(v);
78934   sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
78935  
78936   /* If there are any triggers to fire, allocate a range of registers to
78937   ** use for the old.* references in the triggers.  */
78938   if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
78939     u32 mask;                     /* Mask of OLD.* columns in use */
78940     int iCol;                     /* Iterator used while populating OLD.* */
78941
78942     /* TODO: Could use temporary registers here. Also could attempt to
78943     ** avoid copying the contents of the rowid register.  */
78944     mask = sqlite3TriggerColmask(
78945         pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
78946     );
78947     mask |= sqlite3FkOldmask(pParse, pTab);
78948     iOld = pParse->nMem+1;
78949     pParse->nMem += (1 + pTab->nCol);
78950
78951     /* Populate the OLD.* pseudo-table register array. These values will be 
78952     ** used by any BEFORE and AFTER triggers that exist.  */
78953     sqlite3VdbeAddOp2(v, OP_Copy, iRowid, iOld);
78954     for(iCol=0; iCol<pTab->nCol; iCol++){
78955       if( mask==0xffffffff || mask&(1<<iCol) ){
78956         sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol, iOld+iCol+1);
78957       }
78958     }
78959
78960     /* Invoke BEFORE DELETE trigger programs. */
78961     sqlite3CodeRowTrigger(pParse, pTrigger, 
78962         TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
78963     );
78964
78965     /* Seek the cursor to the row to be deleted again. It may be that
78966     ** the BEFORE triggers coded above have already removed the row
78967     ** being deleted. Do not attempt to delete the row a second time, and 
78968     ** do not fire AFTER triggers.  */
78969     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
78970
78971     /* Do FK processing. This call checks that any FK constraints that
78972     ** refer to this table (i.e. constraints attached to other tables) 
78973     ** are not violated by deleting this row.  */
78974     sqlite3FkCheck(pParse, pTab, iOld, 0);
78975   }
78976
78977   /* Delete the index and table entries. Skip this step if pTab is really
78978   ** a view (in which case the only effect of the DELETE statement is to
78979   ** fire the INSTEAD OF triggers).  */ 
78980   if( pTab->pSelect==0 ){
78981     sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0);
78982     sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
78983     if( count ){
78984       sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
78985     }
78986   }
78987
78988   /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
78989   ** handle rows (possibly in other tables) that refer via a foreign key
78990   ** to the row just deleted. */ 
78991   sqlite3FkActions(pParse, pTab, 0, iOld);
78992
78993   /* Invoke AFTER DELETE trigger programs. */
78994   sqlite3CodeRowTrigger(pParse, pTrigger, 
78995       TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
78996   );
78997
78998   /* Jump here if the row had already been deleted before any BEFORE
78999   ** trigger programs were invoked. Or if a trigger program throws a 
79000   ** RAISE(IGNORE) exception.  */
79001   sqlite3VdbeResolveLabel(v, iLabel);
79002 }
79003
79004 /*
79005 ** This routine generates VDBE code that causes the deletion of all
79006 ** index entries associated with a single row of a single table.
79007 **
79008 ** The VDBE must be in a particular state when this routine is called.
79009 ** These are the requirements:
79010 **
79011 **   1.  A read/write cursor pointing to pTab, the table containing the row
79012 **       to be deleted, must be opened as cursor number "iCur".
79013 **
79014 **   2.  Read/write cursors for all indices of pTab must be open as
79015 **       cursor number iCur+i for the i-th index.
79016 **
79017 **   3.  The "iCur" cursor must be pointing to the row that is to be
79018 **       deleted.
79019 */
79020 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
79021   Parse *pParse,     /* Parsing and code generating context */
79022   Table *pTab,       /* Table containing the row to be deleted */
79023   int iCur,          /* Cursor number for the table */
79024   int *aRegIdx       /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
79025 ){
79026   int i;
79027   Index *pIdx;
79028   int r1;
79029
79030   for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
79031     if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue;
79032     r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, 0);
79033     sqlite3VdbeAddOp3(pParse->pVdbe, OP_IdxDelete, iCur+i, r1,pIdx->nColumn+1);
79034   }
79035 }
79036
79037 /*
79038 ** Generate code that will assemble an index key and put it in register
79039 ** regOut.  The key with be for index pIdx which is an index on pTab.
79040 ** iCur is the index of a cursor open on the pTab table and pointing to
79041 ** the entry that needs indexing.
79042 **
79043 ** Return a register number which is the first in a block of
79044 ** registers that holds the elements of the index key.  The
79045 ** block of registers has already been deallocated by the time
79046 ** this routine returns.
79047 */
79048 SQLITE_PRIVATE int sqlite3GenerateIndexKey(
79049   Parse *pParse,     /* Parsing context */
79050   Index *pIdx,       /* The index for which to generate a key */
79051   int iCur,          /* Cursor number for the pIdx->pTable table */
79052   int regOut,        /* Write the new index key to this register */
79053   int doMakeRec      /* Run the OP_MakeRecord instruction if true */
79054 ){
79055   Vdbe *v = pParse->pVdbe;
79056   int j;
79057   Table *pTab = pIdx->pTable;
79058   int regBase;
79059   int nCol;
79060
79061   nCol = pIdx->nColumn;
79062   regBase = sqlite3GetTempRange(pParse, nCol+1);
79063   sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol);
79064   for(j=0; j<nCol; j++){
79065     int idx = pIdx->aiColumn[j];
79066     if( idx==pTab->iPKey ){
79067       sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j);
79068     }else{
79069       sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j);
79070       sqlite3ColumnDefault(v, pTab, idx, -1);
79071     }
79072   }
79073   if( doMakeRec ){
79074     sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut);
79075     sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), 0);
79076   }
79077   sqlite3ReleaseTempRange(pParse, regBase, nCol+1);
79078   return regBase;
79079 }
79080
79081 /************** End of delete.c **********************************************/
79082 /************** Begin file func.c ********************************************/
79083 /*
79084 ** 2002 February 23
79085 **
79086 ** The author disclaims copyright to this source code.  In place of
79087 ** a legal notice, here is a blessing:
79088 **
79089 **    May you do good and not evil.
79090 **    May you find forgiveness for yourself and forgive others.
79091 **    May you share freely, never taking more than you give.
79092 **
79093 *************************************************************************
79094 ** This file contains the C functions that implement various SQL
79095 ** functions of SQLite.  
79096 **
79097 ** There is only one exported symbol in this file - the function
79098 ** sqliteRegisterBuildinFunctions() found at the bottom of the file.
79099 ** All other code has file scope.
79100 */
79101
79102 /*
79103 ** Return the collating function associated with a function.
79104 */
79105 static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
79106   return context->pColl;
79107 }
79108
79109 /*
79110 ** Implementation of the non-aggregate min() and max() functions
79111 */
79112 static void minmaxFunc(
79113   sqlite3_context *context,
79114   int argc,
79115   sqlite3_value **argv
79116 ){
79117   int i;
79118   int mask;    /* 0 for min() or 0xffffffff for max() */
79119   int iBest;
79120   CollSeq *pColl;
79121
79122   assert( argc>1 );
79123   mask = sqlite3_user_data(context)==0 ? 0 : -1;
79124   pColl = sqlite3GetFuncCollSeq(context);
79125   assert( pColl );
79126   assert( mask==-1 || mask==0 );
79127   iBest = 0;
79128   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
79129   for(i=1; i<argc; i++){
79130     if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
79131     if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
79132       testcase( mask==0 );
79133       iBest = i;
79134     }
79135   }
79136   sqlite3_result_value(context, argv[iBest]);
79137 }
79138
79139 /*
79140 ** Return the type of the argument.
79141 */
79142 static void typeofFunc(
79143   sqlite3_context *context,
79144   int NotUsed,
79145   sqlite3_value **argv
79146 ){
79147   const char *z = 0;
79148   UNUSED_PARAMETER(NotUsed);
79149   switch( sqlite3_value_type(argv[0]) ){
79150     case SQLITE_INTEGER: z = "integer"; break;
79151     case SQLITE_TEXT:    z = "text";    break;
79152     case SQLITE_FLOAT:   z = "real";    break;
79153     case SQLITE_BLOB:    z = "blob";    break;
79154     default:             z = "null";    break;
79155   }
79156   sqlite3_result_text(context, z, -1, SQLITE_STATIC);
79157 }
79158
79159
79160 /*
79161 ** Implementation of the length() function
79162 */
79163 static void lengthFunc(
79164   sqlite3_context *context,
79165   int argc,
79166   sqlite3_value **argv
79167 ){
79168   int len;
79169
79170   assert( argc==1 );
79171   UNUSED_PARAMETER(argc);
79172   switch( sqlite3_value_type(argv[0]) ){
79173     case SQLITE_BLOB:
79174     case SQLITE_INTEGER:
79175     case SQLITE_FLOAT: {
79176       sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
79177       break;
79178     }
79179     case SQLITE_TEXT: {
79180       const unsigned char *z = sqlite3_value_text(argv[0]);
79181       if( z==0 ) return;
79182       len = 0;
79183       while( *z ){
79184         len++;
79185         SQLITE_SKIP_UTF8(z);
79186       }
79187       sqlite3_result_int(context, len);
79188       break;
79189     }
79190     default: {
79191       sqlite3_result_null(context);
79192       break;
79193     }
79194   }
79195 }
79196
79197 /*
79198 ** Implementation of the abs() function.
79199 **
79200 ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
79201 ** the numeric argument X. 
79202 */
79203 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
79204   assert( argc==1 );
79205   UNUSED_PARAMETER(argc);
79206   switch( sqlite3_value_type(argv[0]) ){
79207     case SQLITE_INTEGER: {
79208       i64 iVal = sqlite3_value_int64(argv[0]);
79209       if( iVal<0 ){
79210         if( (iVal<<1)==0 ){
79211           /* IMP: R-35460-15084 If X is the integer -9223372036854775807 then
79212           ** abs(X) throws an integer overflow error since there is no
79213           ** equivalent positive 64-bit two complement value. */
79214           sqlite3_result_error(context, "integer overflow", -1);
79215           return;
79216         }
79217         iVal = -iVal;
79218       } 
79219       sqlite3_result_int64(context, iVal);
79220       break;
79221     }
79222     case SQLITE_NULL: {
79223       /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
79224       sqlite3_result_null(context);
79225       break;
79226     }
79227     default: {
79228       /* Because sqlite3_value_double() returns 0.0 if the argument is not
79229       ** something that can be converted into a number, we have:
79230       ** IMP: R-57326-31541 Abs(X) return 0.0 if X is a string or blob that
79231       ** cannot be converted to a numeric value. 
79232       */
79233       double rVal = sqlite3_value_double(argv[0]);
79234       if( rVal<0 ) rVal = -rVal;
79235       sqlite3_result_double(context, rVal);
79236       break;
79237     }
79238   }
79239 }
79240
79241 /*
79242 ** Implementation of the substr() function.
79243 **
79244 ** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
79245 ** p1 is 1-indexed.  So substr(x,1,1) returns the first character
79246 ** of x.  If x is text, then we actually count UTF-8 characters.
79247 ** If x is a blob, then we count bytes.
79248 **
79249 ** If p1 is negative, then we begin abs(p1) from the end of x[].
79250 **
79251 ** If p2 is negative, return the p2 characters preceeding p1.
79252 */
79253 static void substrFunc(
79254   sqlite3_context *context,
79255   int argc,
79256   sqlite3_value **argv
79257 ){
79258   const unsigned char *z;
79259   const unsigned char *z2;
79260   int len;
79261   int p0type;
79262   i64 p1, p2;
79263   int negP2 = 0;
79264
79265   assert( argc==3 || argc==2 );
79266   if( sqlite3_value_type(argv[1])==SQLITE_NULL
79267    || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
79268   ){
79269     return;
79270   }
79271   p0type = sqlite3_value_type(argv[0]);
79272   p1 = sqlite3_value_int(argv[1]);
79273   if( p0type==SQLITE_BLOB ){
79274     len = sqlite3_value_bytes(argv[0]);
79275     z = sqlite3_value_blob(argv[0]);
79276     if( z==0 ) return;
79277     assert( len==sqlite3_value_bytes(argv[0]) );
79278   }else{
79279     z = sqlite3_value_text(argv[0]);
79280     if( z==0 ) return;
79281     len = 0;
79282     if( p1<0 ){
79283       for(z2=z; *z2; len++){
79284         SQLITE_SKIP_UTF8(z2);
79285       }
79286     }
79287   }
79288   if( argc==3 ){
79289     p2 = sqlite3_value_int(argv[2]);
79290     if( p2<0 ){
79291       p2 = -p2;
79292       negP2 = 1;
79293     }
79294   }else{
79295     p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
79296   }
79297   if( p1<0 ){
79298     p1 += len;
79299     if( p1<0 ){
79300       p2 += p1;
79301       if( p2<0 ) p2 = 0;
79302       p1 = 0;
79303     }
79304   }else if( p1>0 ){
79305     p1--;
79306   }else if( p2>0 ){
79307     p2--;
79308   }
79309   if( negP2 ){
79310     p1 -= p2;
79311     if( p1<0 ){
79312       p2 += p1;
79313       p1 = 0;
79314     }
79315   }
79316   assert( p1>=0 && p2>=0 );
79317   if( p0type!=SQLITE_BLOB ){
79318     while( *z && p1 ){
79319       SQLITE_SKIP_UTF8(z);
79320       p1--;
79321     }
79322     for(z2=z; *z2 && p2; p2--){
79323       SQLITE_SKIP_UTF8(z2);
79324     }
79325     sqlite3_result_text(context, (char*)z, (int)(z2-z), SQLITE_TRANSIENT);
79326   }else{
79327     if( p1+p2>len ){
79328       p2 = len-p1;
79329       if( p2<0 ) p2 = 0;
79330     }
79331     sqlite3_result_blob(context, (char*)&z[p1], (int)p2, SQLITE_TRANSIENT);
79332   }
79333 }
79334
79335 /*
79336 ** Implementation of the round() function
79337 */
79338 #ifndef SQLITE_OMIT_FLOATING_POINT
79339 static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
79340   int n = 0;
79341   double r;
79342   char *zBuf;
79343   assert( argc==1 || argc==2 );
79344   if( argc==2 ){
79345     if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
79346     n = sqlite3_value_int(argv[1]);
79347     if( n>30 ) n = 30;
79348     if( n<0 ) n = 0;
79349   }
79350   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
79351   r = sqlite3_value_double(argv[0]);
79352   /* If Y==0 and X will fit in a 64-bit int,
79353   ** handle the rounding directly,
79354   ** otherwise use printf.
79355   */
79356   if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
79357     r = (double)((sqlite_int64)(r+0.5));
79358   }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
79359     r = -(double)((sqlite_int64)((-r)+0.5));
79360   }else{
79361     zBuf = sqlite3_mprintf("%.*f",n,r);
79362     if( zBuf==0 ){
79363       sqlite3_result_error_nomem(context);
79364       return;
79365     }
79366     sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
79367     sqlite3_free(zBuf);
79368   }
79369   sqlite3_result_double(context, r);
79370 }
79371 #endif
79372
79373 /*
79374 ** Allocate nByte bytes of space using sqlite3_malloc(). If the
79375 ** allocation fails, call sqlite3_result_error_nomem() to notify
79376 ** the database handle that malloc() has failed and return NULL.
79377 ** If nByte is larger than the maximum string or blob length, then
79378 ** raise an SQLITE_TOOBIG exception and return NULL.
79379 */
79380 static void *contextMalloc(sqlite3_context *context, i64 nByte){
79381   char *z;
79382   sqlite3 *db = sqlite3_context_db_handle(context);
79383   assert( nByte>0 );
79384   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
79385   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
79386   if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
79387     sqlite3_result_error_toobig(context);
79388     z = 0;
79389   }else{
79390     z = sqlite3Malloc((int)nByte);
79391     if( !z ){
79392       sqlite3_result_error_nomem(context);
79393     }
79394   }
79395   return z;
79396 }
79397
79398 /*
79399 ** Implementation of the upper() and lower() SQL functions.
79400 */
79401 static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
79402   char *z1;
79403   const char *z2;
79404   int i, n;
79405   UNUSED_PARAMETER(argc);
79406   z2 = (char*)sqlite3_value_text(argv[0]);
79407   n = sqlite3_value_bytes(argv[0]);
79408   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
79409   assert( z2==(char*)sqlite3_value_text(argv[0]) );
79410   if( z2 ){
79411     z1 = contextMalloc(context, ((i64)n)+1);
79412     if( z1 ){
79413       memcpy(z1, z2, n+1);
79414       for(i=0; z1[i]; i++){
79415         z1[i] = (char)sqlite3Toupper(z1[i]);
79416       }
79417       sqlite3_result_text(context, z1, -1, sqlite3_free);
79418     }
79419   }
79420 }
79421 static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
79422   u8 *z1;
79423   const char *z2;
79424   int i, n;
79425   UNUSED_PARAMETER(argc);
79426   z2 = (char*)sqlite3_value_text(argv[0]);
79427   n = sqlite3_value_bytes(argv[0]);
79428   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
79429   assert( z2==(char*)sqlite3_value_text(argv[0]) );
79430   if( z2 ){
79431     z1 = contextMalloc(context, ((i64)n)+1);
79432     if( z1 ){
79433       memcpy(z1, z2, n+1);
79434       for(i=0; z1[i]; i++){
79435         z1[i] = sqlite3Tolower(z1[i]);
79436       }
79437       sqlite3_result_text(context, (char *)z1, -1, sqlite3_free);
79438     }
79439   }
79440 }
79441
79442
79443 #if 0  /* This function is never used. */
79444 /*
79445 ** The COALESCE() and IFNULL() functions used to be implemented as shown
79446 ** here.  But now they are implemented as VDBE code so that unused arguments
79447 ** do not have to be computed.  This legacy implementation is retained as
79448 ** comment.
79449 */
79450 /*
79451 ** Implementation of the IFNULL(), NVL(), and COALESCE() functions.  
79452 ** All three do the same thing.  They return the first non-NULL
79453 ** argument.
79454 */
79455 static void ifnullFunc(
79456   sqlite3_context *context,
79457   int argc,
79458   sqlite3_value **argv
79459 ){
79460   int i;
79461   for(i=0; i<argc; i++){
79462     if( SQLITE_NULL!=sqlite3_value_type(argv[i]) ){
79463       sqlite3_result_value(context, argv[i]);
79464       break;
79465     }
79466   }
79467 }
79468 #endif /* NOT USED */
79469 #define ifnullFunc versionFunc   /* Substitute function - never called */
79470
79471 /*
79472 ** Implementation of random().  Return a random integer.  
79473 */
79474 static void randomFunc(
79475   sqlite3_context *context,
79476   int NotUsed,
79477   sqlite3_value **NotUsed2
79478 ){
79479   sqlite_int64 r;
79480   UNUSED_PARAMETER2(NotUsed, NotUsed2);
79481   sqlite3_randomness(sizeof(r), &r);
79482   if( r<0 ){
79483     /* We need to prevent a random number of 0x8000000000000000 
79484     ** (or -9223372036854775808) since when you do abs() of that
79485     ** number of you get the same value back again.  To do this
79486     ** in a way that is testable, mask the sign bit off of negative
79487     ** values, resulting in a positive value.  Then take the 
79488     ** 2s complement of that positive value.  The end result can
79489     ** therefore be no less than -9223372036854775807.
79490     */
79491     r = -(r ^ (((sqlite3_int64)1)<<63));
79492   }
79493   sqlite3_result_int64(context, r);
79494 }
79495
79496 /*
79497 ** Implementation of randomblob(N).  Return a random blob
79498 ** that is N bytes long.
79499 */
79500 static void randomBlob(
79501   sqlite3_context *context,
79502   int argc,
79503   sqlite3_value **argv
79504 ){
79505   int n;
79506   unsigned char *p;
79507   assert( argc==1 );
79508   UNUSED_PARAMETER(argc);
79509   n = sqlite3_value_int(argv[0]);
79510   if( n<1 ){
79511     n = 1;
79512   }
79513   p = contextMalloc(context, n);
79514   if( p ){
79515     sqlite3_randomness(n, p);
79516     sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
79517   }
79518 }
79519
79520 /*
79521 ** Implementation of the last_insert_rowid() SQL function.  The return
79522 ** value is the same as the sqlite3_last_insert_rowid() API function.
79523 */
79524 static void last_insert_rowid(
79525   sqlite3_context *context, 
79526   int NotUsed, 
79527   sqlite3_value **NotUsed2
79528 ){
79529   sqlite3 *db = sqlite3_context_db_handle(context);
79530   UNUSED_PARAMETER2(NotUsed, NotUsed2);
79531   /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
79532   ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
79533   ** function. */
79534   sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
79535 }
79536
79537 /*
79538 ** Implementation of the changes() SQL function.
79539 **
79540 ** IMP: R-62073-11209 The changes() SQL function is a wrapper
79541 ** around the sqlite3_changes() C/C++ function and hence follows the same
79542 ** rules for counting changes.
79543 */
79544 static void changes(
79545   sqlite3_context *context,
79546   int NotUsed,
79547   sqlite3_value **NotUsed2
79548 ){
79549   sqlite3 *db = sqlite3_context_db_handle(context);
79550   UNUSED_PARAMETER2(NotUsed, NotUsed2);
79551   sqlite3_result_int(context, sqlite3_changes(db));
79552 }
79553
79554 /*
79555 ** Implementation of the total_changes() SQL function.  The return value is
79556 ** the same as the sqlite3_total_changes() API function.
79557 */
79558 static void total_changes(
79559   sqlite3_context *context,
79560   int NotUsed,
79561   sqlite3_value **NotUsed2
79562 ){
79563   sqlite3 *db = sqlite3_context_db_handle(context);
79564   UNUSED_PARAMETER2(NotUsed, NotUsed2);
79565   /* IMP: R-52756-41993 This function is a wrapper around the
79566   ** sqlite3_total_changes() C/C++ interface. */
79567   sqlite3_result_int(context, sqlite3_total_changes(db));
79568 }
79569
79570 /*
79571 ** A structure defining how to do GLOB-style comparisons.
79572 */
79573 struct compareInfo {
79574   u8 matchAll;
79575   u8 matchOne;
79576   u8 matchSet;
79577   u8 noCase;
79578 };
79579
79580 /*
79581 ** For LIKE and GLOB matching on EBCDIC machines, assume that every
79582 ** character is exactly one byte in size.  Also, all characters are
79583 ** able to participate in upper-case-to-lower-case mappings in EBCDIC
79584 ** whereas only characters less than 0x80 do in ASCII.
79585 */
79586 #if defined(SQLITE_EBCDIC)
79587 # define sqlite3Utf8Read(A,C)    (*(A++))
79588 # define GlogUpperToLower(A)     A = sqlite3UpperToLower[A]
79589 #else
79590 # define GlogUpperToLower(A)     if( A<0x80 ){ A = sqlite3UpperToLower[A]; }
79591 #endif
79592
79593 static const struct compareInfo globInfo = { '*', '?', '[', 0 };
79594 /* The correct SQL-92 behavior is for the LIKE operator to ignore
79595 ** case.  Thus  'a' LIKE 'A' would be true. */
79596 static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
79597 /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
79598 ** is case sensitive causing 'a' LIKE 'A' to be false */
79599 static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
79600
79601 /*
79602 ** Compare two UTF-8 strings for equality where the first string can
79603 ** potentially be a "glob" expression.  Return true (1) if they
79604 ** are the same and false (0) if they are different.
79605 **
79606 ** Globbing rules:
79607 **
79608 **      '*'       Matches any sequence of zero or more characters.
79609 **
79610 **      '?'       Matches exactly one character.
79611 **
79612 **     [...]      Matches one character from the enclosed list of
79613 **                characters.
79614 **
79615 **     [^...]     Matches one character not in the enclosed list.
79616 **
79617 ** With the [...] and [^...] matching, a ']' character can be included
79618 ** in the list by making it the first character after '[' or '^'.  A
79619 ** range of characters can be specified using '-'.  Example:
79620 ** "[a-z]" matches any single lower-case letter.  To match a '-', make
79621 ** it the last character in the list.
79622 **
79623 ** This routine is usually quick, but can be N**2 in the worst case.
79624 **
79625 ** Hints: to match '*' or '?', put them in "[]".  Like this:
79626 **
79627 **         abc[*]xyz        Matches "abc*xyz" only
79628 */
79629 static int patternCompare(
79630   const u8 *zPattern,              /* The glob pattern */
79631   const u8 *zString,               /* The string to compare against the glob */
79632   const struct compareInfo *pInfo, /* Information about how to do the compare */
79633   const int esc                    /* The escape character */
79634 ){
79635   int c, c2;
79636   int invert;
79637   int seen;
79638   u8 matchOne = pInfo->matchOne;
79639   u8 matchAll = pInfo->matchAll;
79640   u8 matchSet = pInfo->matchSet;
79641   u8 noCase = pInfo->noCase; 
79642   int prevEscape = 0;     /* True if the previous character was 'escape' */
79643
79644   while( (c = sqlite3Utf8Read(zPattern,&zPattern))!=0 ){
79645     if( !prevEscape && c==matchAll ){
79646       while( (c=sqlite3Utf8Read(zPattern,&zPattern)) == matchAll
79647                || c == matchOne ){
79648         if( c==matchOne && sqlite3Utf8Read(zString, &zString)==0 ){
79649           return 0;
79650         }
79651       }
79652       if( c==0 ){
79653         return 1;
79654       }else if( c==esc ){
79655         c = sqlite3Utf8Read(zPattern, &zPattern);
79656         if( c==0 ){
79657           return 0;
79658         }
79659       }else if( c==matchSet ){
79660         assert( esc==0 );         /* This is GLOB, not LIKE */
79661         assert( matchSet<0x80 );  /* '[' is a single-byte character */
79662         while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
79663           SQLITE_SKIP_UTF8(zString);
79664         }
79665         return *zString!=0;
79666       }
79667       while( (c2 = sqlite3Utf8Read(zString,&zString))!=0 ){
79668         if( noCase ){
79669           GlogUpperToLower(c2);
79670           GlogUpperToLower(c);
79671           while( c2 != 0 && c2 != c ){
79672             c2 = sqlite3Utf8Read(zString, &zString);
79673             GlogUpperToLower(c2);
79674           }
79675         }else{
79676           while( c2 != 0 && c2 != c ){
79677             c2 = sqlite3Utf8Read(zString, &zString);
79678           }
79679         }
79680         if( c2==0 ) return 0;
79681         if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
79682       }
79683       return 0;
79684     }else if( !prevEscape && c==matchOne ){
79685       if( sqlite3Utf8Read(zString, &zString)==0 ){
79686         return 0;
79687       }
79688     }else if( c==matchSet ){
79689       int prior_c = 0;
79690       assert( esc==0 );    /* This only occurs for GLOB, not LIKE */
79691       seen = 0;
79692       invert = 0;
79693       c = sqlite3Utf8Read(zString, &zString);
79694       if( c==0 ) return 0;
79695       c2 = sqlite3Utf8Read(zPattern, &zPattern);
79696       if( c2=='^' ){
79697         invert = 1;
79698         c2 = sqlite3Utf8Read(zPattern, &zPattern);
79699       }
79700       if( c2==']' ){
79701         if( c==']' ) seen = 1;
79702         c2 = sqlite3Utf8Read(zPattern, &zPattern);
79703       }
79704       while( c2 && c2!=']' ){
79705         if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
79706           c2 = sqlite3Utf8Read(zPattern, &zPattern);
79707           if( c>=prior_c && c<=c2 ) seen = 1;
79708           prior_c = 0;
79709         }else{
79710           if( c==c2 ){
79711             seen = 1;
79712           }
79713           prior_c = c2;
79714         }
79715         c2 = sqlite3Utf8Read(zPattern, &zPattern);
79716       }
79717       if( c2==0 || (seen ^ invert)==0 ){
79718         return 0;
79719       }
79720     }else if( esc==c && !prevEscape ){
79721       prevEscape = 1;
79722     }else{
79723       c2 = sqlite3Utf8Read(zString, &zString);
79724       if( noCase ){
79725         GlogUpperToLower(c);
79726         GlogUpperToLower(c2);
79727       }
79728       if( c!=c2 ){
79729         return 0;
79730       }
79731       prevEscape = 0;
79732     }
79733   }
79734   return *zString==0;
79735 }
79736
79737 /*
79738 ** Count the number of times that the LIKE operator (or GLOB which is
79739 ** just a variation of LIKE) gets called.  This is used for testing
79740 ** only.
79741 */
79742 #ifdef SQLITE_TEST
79743 SQLITE_API int sqlite3_like_count = 0;
79744 #endif
79745
79746
79747 /*
79748 ** Implementation of the like() SQL function.  This function implements
79749 ** the build-in LIKE operator.  The first argument to the function is the
79750 ** pattern and the second argument is the string.  So, the SQL statements:
79751 **
79752 **       A LIKE B
79753 **
79754 ** is implemented as like(B,A).
79755 **
79756 ** This same function (with a different compareInfo structure) computes
79757 ** the GLOB operator.
79758 */
79759 static void likeFunc(
79760   sqlite3_context *context, 
79761   int argc, 
79762   sqlite3_value **argv
79763 ){
79764   const unsigned char *zA, *zB;
79765   int escape = 0;
79766   int nPat;
79767   sqlite3 *db = sqlite3_context_db_handle(context);
79768
79769   zB = sqlite3_value_text(argv[0]);
79770   zA = sqlite3_value_text(argv[1]);
79771
79772   /* Limit the length of the LIKE or GLOB pattern to avoid problems
79773   ** of deep recursion and N*N behavior in patternCompare().
79774   */
79775   nPat = sqlite3_value_bytes(argv[0]);
79776   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
79777   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
79778   if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
79779     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
79780     return;
79781   }
79782   assert( zB==sqlite3_value_text(argv[0]) );  /* Encoding did not change */
79783
79784   if( argc==3 ){
79785     /* The escape character string must consist of a single UTF-8 character.
79786     ** Otherwise, return an error.
79787     */
79788     const unsigned char *zEsc = sqlite3_value_text(argv[2]);
79789     if( zEsc==0 ) return;
79790     if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
79791       sqlite3_result_error(context, 
79792           "ESCAPE expression must be a single character", -1);
79793       return;
79794     }
79795     escape = sqlite3Utf8Read(zEsc, &zEsc);
79796   }
79797   if( zA && zB ){
79798     struct compareInfo *pInfo = sqlite3_user_data(context);
79799 #ifdef SQLITE_TEST
79800     sqlite3_like_count++;
79801 #endif
79802     
79803     sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
79804   }
79805 }
79806
79807 /*
79808 ** Implementation of the NULLIF(x,y) function.  The result is the first
79809 ** argument if the arguments are different.  The result is NULL if the
79810 ** arguments are equal to each other.
79811 */
79812 static void nullifFunc(
79813   sqlite3_context *context,
79814   int NotUsed,
79815   sqlite3_value **argv
79816 ){
79817   CollSeq *pColl = sqlite3GetFuncCollSeq(context);
79818   UNUSED_PARAMETER(NotUsed);
79819   if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
79820     sqlite3_result_value(context, argv[0]);
79821   }
79822 }
79823
79824 /*
79825 ** Implementation of the sqlite_version() function.  The result is the version
79826 ** of the SQLite library that is running.
79827 */
79828 static void versionFunc(
79829   sqlite3_context *context,
79830   int NotUsed,
79831   sqlite3_value **NotUsed2
79832 ){
79833   UNUSED_PARAMETER2(NotUsed, NotUsed2);
79834   /* IMP: R-48699-48617 This function is an SQL wrapper around the
79835   ** sqlite3_libversion() C-interface. */
79836   sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
79837 }
79838
79839 /*
79840 ** Implementation of the sqlite_source_id() function. The result is a string
79841 ** that identifies the particular version of the source code used to build
79842 ** SQLite.
79843 */
79844 static void sourceidFunc(
79845   sqlite3_context *context,
79846   int NotUsed,
79847   sqlite3_value **NotUsed2
79848 ){
79849   UNUSED_PARAMETER2(NotUsed, NotUsed2);
79850   /* IMP: R-24470-31136 This function is an SQL wrapper around the
79851   ** sqlite3_sourceid() C interface. */
79852   sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
79853 }
79854
79855 /*
79856 ** Implementation of the sqlite_compileoption_used() function.
79857 ** The result is an integer that identifies if the compiler option
79858 ** was used to build SQLite.
79859 */
79860 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
79861 static void compileoptionusedFunc(
79862   sqlite3_context *context,
79863   int argc,
79864   sqlite3_value **argv
79865 ){
79866   const char *zOptName;
79867   assert( argc==1 );
79868   UNUSED_PARAMETER(argc);
79869   /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
79870   ** function is a wrapper around the sqlite3_compileoption_used() C/C++
79871   ** function.
79872   */
79873   if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
79874     sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
79875   }
79876 }
79877 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
79878
79879 /*
79880 ** Implementation of the sqlite_compileoption_get() function. 
79881 ** The result is a string that identifies the compiler options 
79882 ** used to build SQLite.
79883 */
79884 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
79885 static void compileoptiongetFunc(
79886   sqlite3_context *context,
79887   int argc,
79888   sqlite3_value **argv
79889 ){
79890   int n;
79891   assert( argc==1 );
79892   UNUSED_PARAMETER(argc);
79893   /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
79894   ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
79895   */
79896   n = sqlite3_value_int(argv[0]);
79897   sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
79898 }
79899 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
79900
79901 /* Array for converting from half-bytes (nybbles) into ASCII hex
79902 ** digits. */
79903 static const char hexdigits[] = {
79904   '0', '1', '2', '3', '4', '5', '6', '7',
79905   '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' 
79906 };
79907
79908 /*
79909 ** EXPERIMENTAL - This is not an official function.  The interface may
79910 ** change.  This function may disappear.  Do not write code that depends
79911 ** on this function.
79912 **
79913 ** Implementation of the QUOTE() function.  This function takes a single
79914 ** argument.  If the argument is numeric, the return value is the same as
79915 ** the argument.  If the argument is NULL, the return value is the string
79916 ** "NULL".  Otherwise, the argument is enclosed in single quotes with
79917 ** single-quote escapes.
79918 */
79919 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
79920   assert( argc==1 );
79921   UNUSED_PARAMETER(argc);
79922   switch( sqlite3_value_type(argv[0]) ){
79923     case SQLITE_INTEGER:
79924     case SQLITE_FLOAT: {
79925       sqlite3_result_value(context, argv[0]);
79926       break;
79927     }
79928     case SQLITE_BLOB: {
79929       char *zText = 0;
79930       char const *zBlob = sqlite3_value_blob(argv[0]);
79931       int nBlob = sqlite3_value_bytes(argv[0]);
79932       assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
79933       zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4); 
79934       if( zText ){
79935         int i;
79936         for(i=0; i<nBlob; i++){
79937           zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
79938           zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
79939         }
79940         zText[(nBlob*2)+2] = '\'';
79941         zText[(nBlob*2)+3] = '\0';
79942         zText[0] = 'X';
79943         zText[1] = '\'';
79944         sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
79945         sqlite3_free(zText);
79946       }
79947       break;
79948     }
79949     case SQLITE_TEXT: {
79950       int i,j;
79951       u64 n;
79952       const unsigned char *zArg = sqlite3_value_text(argv[0]);
79953       char *z;
79954
79955       if( zArg==0 ) return;
79956       for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
79957       z = contextMalloc(context, ((i64)i)+((i64)n)+3);
79958       if( z ){
79959         z[0] = '\'';
79960         for(i=0, j=1; zArg[i]; i++){
79961           z[j++] = zArg[i];
79962           if( zArg[i]=='\'' ){
79963             z[j++] = '\'';
79964           }
79965         }
79966         z[j++] = '\'';
79967         z[j] = 0;
79968         sqlite3_result_text(context, z, j, sqlite3_free);
79969       }
79970       break;
79971     }
79972     default: {
79973       assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
79974       sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
79975       break;
79976     }
79977   }
79978 }
79979
79980 /*
79981 ** The hex() function.  Interpret the argument as a blob.  Return
79982 ** a hexadecimal rendering as text.
79983 */
79984 static void hexFunc(
79985   sqlite3_context *context,
79986   int argc,
79987   sqlite3_value **argv
79988 ){
79989   int i, n;
79990   const unsigned char *pBlob;
79991   char *zHex, *z;
79992   assert( argc==1 );
79993   UNUSED_PARAMETER(argc);
79994   pBlob = sqlite3_value_blob(argv[0]);
79995   n = sqlite3_value_bytes(argv[0]);
79996   assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
79997   z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
79998   if( zHex ){
79999     for(i=0; i<n; i++, pBlob++){
80000       unsigned char c = *pBlob;
80001       *(z++) = hexdigits[(c>>4)&0xf];
80002       *(z++) = hexdigits[c&0xf];
80003     }
80004     *z = 0;
80005     sqlite3_result_text(context, zHex, n*2, sqlite3_free);
80006   }
80007 }
80008
80009 /*
80010 ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
80011 */
80012 static void zeroblobFunc(
80013   sqlite3_context *context,
80014   int argc,
80015   sqlite3_value **argv
80016 ){
80017   i64 n;
80018   sqlite3 *db = sqlite3_context_db_handle(context);
80019   assert( argc==1 );
80020   UNUSED_PARAMETER(argc);
80021   n = sqlite3_value_int64(argv[0]);
80022   testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH] );
80023   testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
80024   if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
80025     sqlite3_result_error_toobig(context);
80026   }else{
80027     sqlite3_result_zeroblob(context, (int)n); /* IMP: R-00293-64994 */
80028   }
80029 }
80030
80031 /*
80032 ** The replace() function.  Three arguments are all strings: call
80033 ** them A, B, and C. The result is also a string which is derived
80034 ** from A by replacing every occurance of B with C.  The match
80035 ** must be exact.  Collating sequences are not used.
80036 */
80037 static void replaceFunc(
80038   sqlite3_context *context,
80039   int argc,
80040   sqlite3_value **argv
80041 ){
80042   const unsigned char *zStr;        /* The input string A */
80043   const unsigned char *zPattern;    /* The pattern string B */
80044   const unsigned char *zRep;        /* The replacement string C */
80045   unsigned char *zOut;              /* The output */
80046   int nStr;                /* Size of zStr */
80047   int nPattern;            /* Size of zPattern */
80048   int nRep;                /* Size of zRep */
80049   i64 nOut;                /* Maximum size of zOut */
80050   int loopLimit;           /* Last zStr[] that might match zPattern[] */
80051   int i, j;                /* Loop counters */
80052
80053   assert( argc==3 );
80054   UNUSED_PARAMETER(argc);
80055   zStr = sqlite3_value_text(argv[0]);
80056   if( zStr==0 ) return;
80057   nStr = sqlite3_value_bytes(argv[0]);
80058   assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
80059   zPattern = sqlite3_value_text(argv[1]);
80060   if( zPattern==0 ){
80061     assert( sqlite3_value_type(argv[1])==SQLITE_NULL
80062             || sqlite3_context_db_handle(context)->mallocFailed );
80063     return;
80064   }
80065   if( zPattern[0]==0 ){
80066     assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
80067     sqlite3_result_value(context, argv[0]);
80068     return;
80069   }
80070   nPattern = sqlite3_value_bytes(argv[1]);
80071   assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
80072   zRep = sqlite3_value_text(argv[2]);
80073   if( zRep==0 ) return;
80074   nRep = sqlite3_value_bytes(argv[2]);
80075   assert( zRep==sqlite3_value_text(argv[2]) );
80076   nOut = nStr + 1;
80077   assert( nOut<SQLITE_MAX_LENGTH );
80078   zOut = contextMalloc(context, (i64)nOut);
80079   if( zOut==0 ){
80080     return;
80081   }
80082   loopLimit = nStr - nPattern;  
80083   for(i=j=0; i<=loopLimit; i++){
80084     if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
80085       zOut[j++] = zStr[i];
80086     }else{
80087       u8 *zOld;
80088       sqlite3 *db = sqlite3_context_db_handle(context);
80089       nOut += nRep - nPattern;
80090       testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
80091       testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
80092       if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
80093         sqlite3_result_error_toobig(context);
80094         sqlite3_free(zOut);
80095         return;
80096       }
80097       zOld = zOut;
80098       zOut = sqlite3_realloc(zOut, (int)nOut);
80099       if( zOut==0 ){
80100         sqlite3_result_error_nomem(context);
80101         sqlite3_free(zOld);
80102         return;
80103       }
80104       memcpy(&zOut[j], zRep, nRep);
80105       j += nRep;
80106       i += nPattern-1;
80107     }
80108   }
80109   assert( j+nStr-i+1==nOut );
80110   memcpy(&zOut[j], &zStr[i], nStr-i);
80111   j += nStr - i;
80112   assert( j<=nOut );
80113   zOut[j] = 0;
80114   sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
80115 }
80116
80117 /*
80118 ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
80119 ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
80120 */
80121 static void trimFunc(
80122   sqlite3_context *context,
80123   int argc,
80124   sqlite3_value **argv
80125 ){
80126   const unsigned char *zIn;         /* Input string */
80127   const unsigned char *zCharSet;    /* Set of characters to trim */
80128   int nIn;                          /* Number of bytes in input */
80129   int flags;                        /* 1: trimleft  2: trimright  3: trim */
80130   int i;                            /* Loop counter */
80131   unsigned char *aLen = 0;          /* Length of each character in zCharSet */
80132   unsigned char **azChar = 0;       /* Individual characters in zCharSet */
80133   int nChar;                        /* Number of characters in zCharSet */
80134
80135   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
80136     return;
80137   }
80138   zIn = sqlite3_value_text(argv[0]);
80139   if( zIn==0 ) return;
80140   nIn = sqlite3_value_bytes(argv[0]);
80141   assert( zIn==sqlite3_value_text(argv[0]) );
80142   if( argc==1 ){
80143     static const unsigned char lenOne[] = { 1 };
80144     static unsigned char * const azOne[] = { (u8*)" " };
80145     nChar = 1;
80146     aLen = (u8*)lenOne;
80147     azChar = (unsigned char **)azOne;
80148     zCharSet = 0;
80149   }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
80150     return;
80151   }else{
80152     const unsigned char *z;
80153     for(z=zCharSet, nChar=0; *z; nChar++){
80154       SQLITE_SKIP_UTF8(z);
80155     }
80156     if( nChar>0 ){
80157       azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
80158       if( azChar==0 ){
80159         return;
80160       }
80161       aLen = (unsigned char*)&azChar[nChar];
80162       for(z=zCharSet, nChar=0; *z; nChar++){
80163         azChar[nChar] = (unsigned char *)z;
80164         SQLITE_SKIP_UTF8(z);
80165         aLen[nChar] = (u8)(z - azChar[nChar]);
80166       }
80167     }
80168   }
80169   if( nChar>0 ){
80170     flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
80171     if( flags & 1 ){
80172       while( nIn>0 ){
80173         int len = 0;
80174         for(i=0; i<nChar; i++){
80175           len = aLen[i];
80176           if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
80177         }
80178         if( i>=nChar ) break;
80179         zIn += len;
80180         nIn -= len;
80181       }
80182     }
80183     if( flags & 2 ){
80184       while( nIn>0 ){
80185         int len = 0;
80186         for(i=0; i<nChar; i++){
80187           len = aLen[i];
80188           if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
80189         }
80190         if( i>=nChar ) break;
80191         nIn -= len;
80192       }
80193     }
80194     if( zCharSet ){
80195       sqlite3_free(azChar);
80196     }
80197   }
80198   sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
80199 }
80200
80201
80202 /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
80203 ** is only available if the SQLITE_SOUNDEX compile-time option is used
80204 ** when SQLite is built.
80205 */
80206 #ifdef SQLITE_SOUNDEX
80207 /*
80208 ** Compute the soundex encoding of a word.
80209 **
80210 ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
80211 ** soundex encoding of the string X. 
80212 */
80213 static void soundexFunc(
80214   sqlite3_context *context,
80215   int argc,
80216   sqlite3_value **argv
80217 ){
80218   char zResult[8];
80219   const u8 *zIn;
80220   int i, j;
80221   static const unsigned char iCode[] = {
80222     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
80223     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
80224     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
80225     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
80226     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
80227     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
80228     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
80229     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
80230   };
80231   assert( argc==1 );
80232   zIn = (u8*)sqlite3_value_text(argv[0]);
80233   if( zIn==0 ) zIn = (u8*)"";
80234   for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
80235   if( zIn[i] ){
80236     u8 prevcode = iCode[zIn[i]&0x7f];
80237     zResult[0] = sqlite3Toupper(zIn[i]);
80238     for(j=1; j<4 && zIn[i]; i++){
80239       int code = iCode[zIn[i]&0x7f];
80240       if( code>0 ){
80241         if( code!=prevcode ){
80242           prevcode = code;
80243           zResult[j++] = code + '0';
80244         }
80245       }else{
80246         prevcode = 0;
80247       }
80248     }
80249     while( j<4 ){
80250       zResult[j++] = '0';
80251     }
80252     zResult[j] = 0;
80253     sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
80254   }else{
80255     /* IMP: R-64894-50321 The string "?000" is returned if the argument
80256     ** is NULL or contains no ASCII alphabetic characters. */
80257     sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
80258   }
80259 }
80260 #endif /* SQLITE_SOUNDEX */
80261
80262 #ifndef SQLITE_OMIT_LOAD_EXTENSION
80263 /*
80264 ** A function that loads a shared-library extension then returns NULL.
80265 */
80266 static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
80267   const char *zFile = (const char *)sqlite3_value_text(argv[0]);
80268   const char *zProc;
80269   sqlite3 *db = sqlite3_context_db_handle(context);
80270   char *zErrMsg = 0;
80271
80272   if( argc==2 ){
80273     zProc = (const char *)sqlite3_value_text(argv[1]);
80274   }else{
80275     zProc = 0;
80276   }
80277   if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
80278     sqlite3_result_error(context, zErrMsg, -1);
80279     sqlite3_free(zErrMsg);
80280   }
80281 }
80282 #endif
80283
80284
80285 /*
80286 ** An instance of the following structure holds the context of a
80287 ** sum() or avg() aggregate computation.
80288 */
80289 typedef struct SumCtx SumCtx;
80290 struct SumCtx {
80291   double rSum;      /* Floating point sum */
80292   i64 iSum;         /* Integer sum */   
80293   i64 cnt;          /* Number of elements summed */
80294   u8 overflow;      /* True if integer overflow seen */
80295   u8 approx;        /* True if non-integer value was input to the sum */
80296 };
80297
80298 /*
80299 ** Routines used to compute the sum, average, and total.
80300 **
80301 ** The SUM() function follows the (broken) SQL standard which means
80302 ** that it returns NULL if it sums over no inputs.  TOTAL returns
80303 ** 0.0 in that case.  In addition, TOTAL always returns a float where
80304 ** SUM might return an integer if it never encounters a floating point
80305 ** value.  TOTAL never fails, but SUM might through an exception if
80306 ** it overflows an integer.
80307 */
80308 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
80309   SumCtx *p;
80310   int type;
80311   assert( argc==1 );
80312   UNUSED_PARAMETER(argc);
80313   p = sqlite3_aggregate_context(context, sizeof(*p));
80314   type = sqlite3_value_numeric_type(argv[0]);
80315   if( p && type!=SQLITE_NULL ){
80316     p->cnt++;
80317     if( type==SQLITE_INTEGER ){
80318       i64 v = sqlite3_value_int64(argv[0]);
80319       p->rSum += v;
80320       if( (p->approx|p->overflow)==0 ){
80321         i64 iNewSum = p->iSum + v;
80322         int s1 = (int)(p->iSum >> (sizeof(i64)*8-1));
80323         int s2 = (int)(v       >> (sizeof(i64)*8-1));
80324         int s3 = (int)(iNewSum >> (sizeof(i64)*8-1));
80325         p->overflow = ((s1&s2&~s3) | (~s1&~s2&s3))?1:0;
80326         p->iSum = iNewSum;
80327       }
80328     }else{
80329       p->rSum += sqlite3_value_double(argv[0]);
80330       p->approx = 1;
80331     }
80332   }
80333 }
80334 static void sumFinalize(sqlite3_context *context){
80335   SumCtx *p;
80336   p = sqlite3_aggregate_context(context, 0);
80337   if( p && p->cnt>0 ){
80338     if( p->overflow ){
80339       sqlite3_result_error(context,"integer overflow",-1);
80340     }else if( p->approx ){
80341       sqlite3_result_double(context, p->rSum);
80342     }else{
80343       sqlite3_result_int64(context, p->iSum);
80344     }
80345   }
80346 }
80347 static void avgFinalize(sqlite3_context *context){
80348   SumCtx *p;
80349   p = sqlite3_aggregate_context(context, 0);
80350   if( p && p->cnt>0 ){
80351     sqlite3_result_double(context, p->rSum/(double)p->cnt);
80352   }
80353 }
80354 static void totalFinalize(sqlite3_context *context){
80355   SumCtx *p;
80356   p = sqlite3_aggregate_context(context, 0);
80357   /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
80358   sqlite3_result_double(context, p ? p->rSum : (double)0);
80359 }
80360
80361 /*
80362 ** The following structure keeps track of state information for the
80363 ** count() aggregate function.
80364 */
80365 typedef struct CountCtx CountCtx;
80366 struct CountCtx {
80367   i64 n;
80368 };
80369
80370 /*
80371 ** Routines to implement the count() aggregate function.
80372 */
80373 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
80374   CountCtx *p;
80375   p = sqlite3_aggregate_context(context, sizeof(*p));
80376   if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
80377     p->n++;
80378   }
80379
80380 #ifndef SQLITE_OMIT_DEPRECATED
80381   /* The sqlite3_aggregate_count() function is deprecated.  But just to make
80382   ** sure it still operates correctly, verify that its count agrees with our 
80383   ** internal count when using count(*) and when the total count can be
80384   ** expressed as a 32-bit integer. */
80385   assert( argc==1 || p==0 || p->n>0x7fffffff
80386           || p->n==sqlite3_aggregate_count(context) );
80387 #endif
80388 }   
80389 static void countFinalize(sqlite3_context *context){
80390   CountCtx *p;
80391   p = sqlite3_aggregate_context(context, 0);
80392   sqlite3_result_int64(context, p ? p->n : 0);
80393 }
80394
80395 /*
80396 ** Routines to implement min() and max() aggregate functions.
80397 */
80398 static void minmaxStep(
80399   sqlite3_context *context, 
80400   int NotUsed, 
80401   sqlite3_value **argv
80402 ){
80403   Mem *pArg  = (Mem *)argv[0];
80404   Mem *pBest;
80405   UNUSED_PARAMETER(NotUsed);
80406
80407   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
80408   pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
80409   if( !pBest ) return;
80410
80411   if( pBest->flags ){
80412     int max;
80413     int cmp;
80414     CollSeq *pColl = sqlite3GetFuncCollSeq(context);
80415     /* This step function is used for both the min() and max() aggregates,
80416     ** the only difference between the two being that the sense of the
80417     ** comparison is inverted. For the max() aggregate, the
80418     ** sqlite3_user_data() function returns (void *)-1. For min() it
80419     ** returns (void *)db, where db is the sqlite3* database pointer.
80420     ** Therefore the next statement sets variable 'max' to 1 for the max()
80421     ** aggregate, or 0 for min().
80422     */
80423     max = sqlite3_user_data(context)!=0;
80424     cmp = sqlite3MemCompare(pBest, pArg, pColl);
80425     if( (max && cmp<0) || (!max && cmp>0) ){
80426       sqlite3VdbeMemCopy(pBest, pArg);
80427     }
80428   }else{
80429     sqlite3VdbeMemCopy(pBest, pArg);
80430   }
80431 }
80432 static void minMaxFinalize(sqlite3_context *context){
80433   sqlite3_value *pRes;
80434   pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
80435   if( pRes ){
80436     if( ALWAYS(pRes->flags) ){
80437       sqlite3_result_value(context, pRes);
80438     }
80439     sqlite3VdbeMemRelease(pRes);
80440   }
80441 }
80442
80443 /*
80444 ** group_concat(EXPR, ?SEPARATOR?)
80445 */
80446 static void groupConcatStep(
80447   sqlite3_context *context,
80448   int argc,
80449   sqlite3_value **argv
80450 ){
80451   const char *zVal;
80452   StrAccum *pAccum;
80453   const char *zSep;
80454   int nVal, nSep;
80455   assert( argc==1 || argc==2 );
80456   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
80457   pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
80458
80459   if( pAccum ){
80460     sqlite3 *db = sqlite3_context_db_handle(context);
80461     int firstTerm = pAccum->useMalloc==0;
80462     pAccum->useMalloc = 2;
80463     pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
80464     if( !firstTerm ){
80465       if( argc==2 ){
80466         zSep = (char*)sqlite3_value_text(argv[1]);
80467         nSep = sqlite3_value_bytes(argv[1]);
80468       }else{
80469         zSep = ",";
80470         nSep = 1;
80471       }
80472       sqlite3StrAccumAppend(pAccum, zSep, nSep);
80473     }
80474     zVal = (char*)sqlite3_value_text(argv[0]);
80475     nVal = sqlite3_value_bytes(argv[0]);
80476     sqlite3StrAccumAppend(pAccum, zVal, nVal);
80477   }
80478 }
80479 static void groupConcatFinalize(sqlite3_context *context){
80480   StrAccum *pAccum;
80481   pAccum = sqlite3_aggregate_context(context, 0);
80482   if( pAccum ){
80483     if( pAccum->tooBig ){
80484       sqlite3_result_error_toobig(context);
80485     }else if( pAccum->mallocFailed ){
80486       sqlite3_result_error_nomem(context);
80487     }else{    
80488       sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1, 
80489                           sqlite3_free);
80490     }
80491   }
80492 }
80493
80494 /*
80495 ** This routine does per-connection function registration.  Most
80496 ** of the built-in functions above are part of the global function set.
80497 ** This routine only deals with those that are not global.
80498 */
80499 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
80500   int rc = sqlite3_overload_function(db, "MATCH", 2);
80501   assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
80502   if( rc==SQLITE_NOMEM ){
80503     db->mallocFailed = 1;
80504   }
80505 }
80506
80507 /*
80508 ** Set the LIKEOPT flag on the 2-argument function with the given name.
80509 */
80510 static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
80511   FuncDef *pDef;
80512   pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
80513                              2, SQLITE_UTF8, 0);
80514   if( ALWAYS(pDef) ){
80515     pDef->flags = flagVal;
80516   }
80517 }
80518
80519 /*
80520 ** Register the built-in LIKE and GLOB functions.  The caseSensitive
80521 ** parameter determines whether or not the LIKE operator is case
80522 ** sensitive.  GLOB is always case sensitive.
80523 */
80524 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
80525   struct compareInfo *pInfo;
80526   if( caseSensitive ){
80527     pInfo = (struct compareInfo*)&likeInfoAlt;
80528   }else{
80529     pInfo = (struct compareInfo*)&likeInfoNorm;
80530   }
80531   sqlite3CreateFunc(db, "like", 2, SQLITE_ANY, pInfo, likeFunc, 0, 0, 0);
80532   sqlite3CreateFunc(db, "like", 3, SQLITE_ANY, pInfo, likeFunc, 0, 0, 0);
80533   sqlite3CreateFunc(db, "glob", 2, SQLITE_ANY, 
80534       (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
80535   setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
80536   setLikeOptFlag(db, "like", 
80537       caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
80538 }
80539
80540 /*
80541 ** pExpr points to an expression which implements a function.  If
80542 ** it is appropriate to apply the LIKE optimization to that function
80543 ** then set aWc[0] through aWc[2] to the wildcard characters and
80544 ** return TRUE.  If the function is not a LIKE-style function then
80545 ** return FALSE.
80546 */
80547 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
80548   FuncDef *pDef;
80549   if( pExpr->op!=TK_FUNCTION 
80550    || !pExpr->x.pList 
80551    || pExpr->x.pList->nExpr!=2
80552   ){
80553     return 0;
80554   }
80555   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
80556   pDef = sqlite3FindFunction(db, pExpr->u.zToken, 
80557                              sqlite3Strlen30(pExpr->u.zToken),
80558                              2, SQLITE_UTF8, 0);
80559   if( NEVER(pDef==0) || (pDef->flags & SQLITE_FUNC_LIKE)==0 ){
80560     return 0;
80561   }
80562
80563   /* The memcpy() statement assumes that the wildcard characters are
80564   ** the first three statements in the compareInfo structure.  The
80565   ** asserts() that follow verify that assumption
80566   */
80567   memcpy(aWc, pDef->pUserData, 3);
80568   assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
80569   assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
80570   assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
80571   *pIsNocase = (pDef->flags & SQLITE_FUNC_CASE)==0;
80572   return 1;
80573 }
80574
80575 /*
80576 ** All all of the FuncDef structures in the aBuiltinFunc[] array above
80577 ** to the global function hash table.  This occurs at start-time (as
80578 ** a consequence of calling sqlite3_initialize()).
80579 **
80580 ** After this routine runs
80581 */
80582 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
80583   /*
80584   ** The following array holds FuncDef structures for all of the functions
80585   ** defined in this file.
80586   **
80587   ** The array cannot be constant since changes are made to the
80588   ** FuncDef.pHash elements at start-time.  The elements of this array
80589   ** are read-only after initialization is complete.
80590   */
80591   static SQLITE_WSD FuncDef aBuiltinFunc[] = {
80592     FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
80593     FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
80594     FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
80595     FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
80596     FUNCTION(trim,               1, 3, 0, trimFunc         ),
80597     FUNCTION(trim,               2, 3, 0, trimFunc         ),
80598     FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
80599     FUNCTION(min,                0, 0, 1, 0                ),
80600     AGGREGATE(min,               1, 0, 1, minmaxStep,      minMaxFinalize ),
80601     FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
80602     FUNCTION(max,                0, 1, 1, 0                ),
80603     AGGREGATE(max,               1, 1, 1, minmaxStep,      minMaxFinalize ),
80604     FUNCTION(typeof,             1, 0, 0, typeofFunc       ),
80605     FUNCTION(length,             1, 0, 0, lengthFunc       ),
80606     FUNCTION(substr,             2, 0, 0, substrFunc       ),
80607     FUNCTION(substr,             3, 0, 0, substrFunc       ),
80608     FUNCTION(abs,                1, 0, 0, absFunc          ),
80609 #ifndef SQLITE_OMIT_FLOATING_POINT
80610     FUNCTION(round,              1, 0, 0, roundFunc        ),
80611     FUNCTION(round,              2, 0, 0, roundFunc        ),
80612 #endif
80613     FUNCTION(upper,              1, 0, 0, upperFunc        ),
80614     FUNCTION(lower,              1, 0, 0, lowerFunc        ),
80615     FUNCTION(coalesce,           1, 0, 0, 0                ),
80616     FUNCTION(coalesce,           0, 0, 0, 0                ),
80617 /*  FUNCTION(coalesce,          -1, 0, 0, ifnullFunc       ), */
80618     {-1,SQLITE_UTF8,SQLITE_FUNC_COALESCE,0,0,ifnullFunc,0,0,"coalesce",0,0},
80619     FUNCTION(hex,                1, 0, 0, hexFunc          ),
80620 /*  FUNCTION(ifnull,             2, 0, 0, ifnullFunc       ), */
80621     {2,SQLITE_UTF8,SQLITE_FUNC_COALESCE,0,0,ifnullFunc,0,0,"ifnull",0,0},
80622     FUNCTION(random,             0, 0, 0, randomFunc       ),
80623     FUNCTION(randomblob,         1, 0, 0, randomBlob       ),
80624     FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
80625     FUNCTION(sqlite_version,     0, 0, 0, versionFunc      ),
80626     FUNCTION(sqlite_source_id,   0, 0, 0, sourceidFunc     ),
80627 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
80628     FUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc  ),
80629     FUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc  ),
80630 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
80631     FUNCTION(quote,              1, 0, 0, quoteFunc        ),
80632     FUNCTION(last_insert_rowid,  0, 0, 0, last_insert_rowid),
80633     FUNCTION(changes,            0, 0, 0, changes          ),
80634     FUNCTION(total_changes,      0, 0, 0, total_changes    ),
80635     FUNCTION(replace,            3, 0, 0, replaceFunc      ),
80636     FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
80637   #ifdef SQLITE_SOUNDEX
80638     FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
80639   #endif
80640   #ifndef SQLITE_OMIT_LOAD_EXTENSION
80641     FUNCTION(load_extension,     1, 0, 0, loadExt          ),
80642     FUNCTION(load_extension,     2, 0, 0, loadExt          ),
80643   #endif
80644     AGGREGATE(sum,               1, 0, 0, sumStep,         sumFinalize    ),
80645     AGGREGATE(total,             1, 0, 0, sumStep,         totalFinalize    ),
80646     AGGREGATE(avg,               1, 0, 0, sumStep,         avgFinalize    ),
80647  /* AGGREGATE(count,             0, 0, 0, countStep,       countFinalize  ), */
80648     {0,SQLITE_UTF8,SQLITE_FUNC_COUNT,0,0,0,countStep,countFinalize,"count",0,0},
80649     AGGREGATE(count,             1, 0, 0, countStep,       countFinalize  ),
80650     AGGREGATE(group_concat,      1, 0, 0, groupConcatStep, groupConcatFinalize),
80651     AGGREGATE(group_concat,      2, 0, 0, groupConcatStep, groupConcatFinalize),
80652   
80653     LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
80654   #ifdef SQLITE_CASE_SENSITIVE_LIKE
80655     LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
80656     LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
80657   #else
80658     LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
80659     LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
80660   #endif
80661   };
80662
80663   int i;
80664   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
80665   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
80666
80667   for(i=0; i<ArraySize(aBuiltinFunc); i++){
80668     sqlite3FuncDefInsert(pHash, &aFunc[i]);
80669   }
80670   sqlite3RegisterDateTimeFunctions();
80671 #ifndef SQLITE_OMIT_ALTERTABLE
80672   sqlite3AlterFunctions();
80673 #endif
80674 }
80675
80676 /************** End of func.c ************************************************/
80677 /************** Begin file fkey.c ********************************************/
80678 /*
80679 **
80680 ** The author disclaims copyright to this source code.  In place of
80681 ** a legal notice, here is a blessing:
80682 **
80683 **    May you do good and not evil.
80684 **    May you find forgiveness for yourself and forgive others.
80685 **    May you share freely, never taking more than you give.
80686 **
80687 *************************************************************************
80688 ** This file contains code used by the compiler to add foreign key
80689 ** support to compiled SQL statements.
80690 */
80691
80692 #ifndef SQLITE_OMIT_FOREIGN_KEY
80693 #ifndef SQLITE_OMIT_TRIGGER
80694
80695 /*
80696 ** Deferred and Immediate FKs
80697 ** --------------------------
80698 **
80699 ** Foreign keys in SQLite come in two flavours: deferred and immediate.
80700 ** If an immediate foreign key constraint is violated, SQLITE_CONSTRAINT
80701 ** is returned and the current statement transaction rolled back. If a 
80702 ** deferred foreign key constraint is violated, no action is taken 
80703 ** immediately. However if the application attempts to commit the 
80704 ** transaction before fixing the constraint violation, the attempt fails.
80705 **
80706 ** Deferred constraints are implemented using a simple counter associated
80707 ** with the database handle. The counter is set to zero each time a 
80708 ** database transaction is opened. Each time a statement is executed 
80709 ** that causes a foreign key violation, the counter is incremented. Each
80710 ** time a statement is executed that removes an existing violation from
80711 ** the database, the counter is decremented. When the transaction is
80712 ** committed, the commit fails if the current value of the counter is
80713 ** greater than zero. This scheme has two big drawbacks:
80714 **
80715 **   * When a commit fails due to a deferred foreign key constraint, 
80716 **     there is no way to tell which foreign constraint is not satisfied,
80717 **     or which row it is not satisfied for.
80718 **
80719 **   * If the database contains foreign key violations when the 
80720 **     transaction is opened, this may cause the mechanism to malfunction.
80721 **
80722 ** Despite these problems, this approach is adopted as it seems simpler
80723 ** than the alternatives.
80724 **
80725 ** INSERT operations:
80726 **
80727 **   I.1) For each FK for which the table is the child table, search
80728 **        the parent table for a match. If none is found increment the
80729 **        constraint counter.
80730 **
80731 **   I.2) For each FK for which the table is the parent table, 
80732 **        search the child table for rows that correspond to the new
80733 **        row in the parent table. Decrement the counter for each row
80734 **        found (as the constraint is now satisfied).
80735 **
80736 ** DELETE operations:
80737 **
80738 **   D.1) For each FK for which the table is the child table, 
80739 **        search the parent table for a row that corresponds to the 
80740 **        deleted row in the child table. If such a row is not found, 
80741 **        decrement the counter.
80742 **
80743 **   D.2) For each FK for which the table is the parent table, search 
80744 **        the child table for rows that correspond to the deleted row 
80745 **        in the parent table. For each found increment the counter.
80746 **
80747 ** UPDATE operations:
80748 **
80749 **   An UPDATE command requires that all 4 steps above are taken, but only
80750 **   for FK constraints for which the affected columns are actually 
80751 **   modified (values must be compared at runtime).
80752 **
80753 ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
80754 ** This simplifies the implementation a bit.
80755 **
80756 ** For the purposes of immediate FK constraints, the OR REPLACE conflict
80757 ** resolution is considered to delete rows before the new row is inserted.
80758 ** If a delete caused by OR REPLACE violates an FK constraint, an exception
80759 ** is thrown, even if the FK constraint would be satisfied after the new 
80760 ** row is inserted.
80761 **
80762 ** Immediate constraints are usually handled similarly. The only difference 
80763 ** is that the counter used is stored as part of each individual statement
80764 ** object (struct Vdbe). If, after the statement has run, its immediate
80765 ** constraint counter is greater than zero, it returns SQLITE_CONSTRAINT
80766 ** and the statement transaction is rolled back. An exception is an INSERT
80767 ** statement that inserts a single row only (no triggers). In this case,
80768 ** instead of using a counter, an exception is thrown immediately if the
80769 ** INSERT violates a foreign key constraint. This is necessary as such
80770 ** an INSERT does not open a statement transaction.
80771 **
80772 ** TODO: How should dropping a table be handled? How should renaming a 
80773 ** table be handled?
80774 **
80775 **
80776 ** Query API Notes
80777 ** ---------------
80778 **
80779 ** Before coding an UPDATE or DELETE row operation, the code-generator
80780 ** for those two operations needs to know whether or not the operation
80781 ** requires any FK processing and, if so, which columns of the original
80782 ** row are required by the FK processing VDBE code (i.e. if FKs were
80783 ** implemented using triggers, which of the old.* columns would be 
80784 ** accessed). No information is required by the code-generator before
80785 ** coding an INSERT operation. The functions used by the UPDATE/DELETE
80786 ** generation code to query for this information are:
80787 **
80788 **   sqlite3FkRequired() - Test to see if FK processing is required.
80789 **   sqlite3FkOldmask()  - Query for the set of required old.* columns.
80790 **
80791 **
80792 ** Externally accessible module functions
80793 ** --------------------------------------
80794 **
80795 **   sqlite3FkCheck()    - Check for foreign key violations.
80796 **   sqlite3FkActions()  - Code triggers for ON UPDATE/ON DELETE actions.
80797 **   sqlite3FkDelete()   - Delete an FKey structure.
80798 */
80799
80800 /*
80801 ** VDBE Calling Convention
80802 ** -----------------------
80803 **
80804 ** Example:
80805 **
80806 **   For the following INSERT statement:
80807 **
80808 **     CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
80809 **     INSERT INTO t1 VALUES(1, 2, 3.1);
80810 **
80811 **   Register (x):        2    (type integer)
80812 **   Register (x+1):      1    (type integer)
80813 **   Register (x+2):      NULL (type NULL)
80814 **   Register (x+3):      3.1  (type real)
80815 */
80816
80817 /*
80818 ** A foreign key constraint requires that the key columns in the parent
80819 ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
80820 ** Given that pParent is the parent table for foreign key constraint pFKey, 
80821 ** search the schema a unique index on the parent key columns. 
80822 **
80823 ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY 
80824 ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx 
80825 ** is set to point to the unique index. 
80826 ** 
80827 ** If the parent key consists of a single column (the foreign key constraint
80828 ** is not a composite foreign key), output variable *paiCol is set to NULL.
80829 ** Otherwise, it is set to point to an allocated array of size N, where
80830 ** N is the number of columns in the parent key. The first element of the
80831 ** array is the index of the child table column that is mapped by the FK
80832 ** constraint to the parent table column stored in the left-most column
80833 ** of index *ppIdx. The second element of the array is the index of the
80834 ** child table column that corresponds to the second left-most column of
80835 ** *ppIdx, and so on.
80836 **
80837 ** If the required index cannot be found, either because:
80838 **
80839 **   1) The named parent key columns do not exist, or
80840 **
80841 **   2) The named parent key columns do exist, but are not subject to a
80842 **      UNIQUE or PRIMARY KEY constraint, or
80843 **
80844 **   3) No parent key columns were provided explicitly as part of the
80845 **      foreign key definition, and the parent table does not have a
80846 **      PRIMARY KEY, or
80847 **
80848 **   4) No parent key columns were provided explicitly as part of the
80849 **      foreign key definition, and the PRIMARY KEY of the parent table 
80850 **      consists of a a different number of columns to the child key in 
80851 **      the child table.
80852 **
80853 ** then non-zero is returned, and a "foreign key mismatch" error loaded
80854 ** into pParse. If an OOM error occurs, non-zero is returned and the
80855 ** pParse->db->mallocFailed flag is set.
80856 */
80857 static int locateFkeyIndex(
80858   Parse *pParse,                  /* Parse context to store any error in */
80859   Table *pParent,                 /* Parent table of FK constraint pFKey */
80860   FKey *pFKey,                    /* Foreign key to find index for */
80861   Index **ppIdx,                  /* OUT: Unique index on parent table */
80862   int **paiCol                    /* OUT: Map of index columns in pFKey */
80863 ){
80864   Index *pIdx = 0;                    /* Value to return via *ppIdx */
80865   int *aiCol = 0;                     /* Value to return via *paiCol */
80866   int nCol = pFKey->nCol;             /* Number of columns in parent key */
80867   char *zKey = pFKey->aCol[0].zCol;   /* Name of left-most parent key column */
80868
80869   /* The caller is responsible for zeroing output parameters. */
80870   assert( ppIdx && *ppIdx==0 );
80871   assert( !paiCol || *paiCol==0 );
80872   assert( pParse );
80873
80874   /* If this is a non-composite (single column) foreign key, check if it 
80875   ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx 
80876   ** and *paiCol set to zero and return early. 
80877   **
80878   ** Otherwise, for a composite foreign key (more than one column), allocate
80879   ** space for the aiCol array (returned via output parameter *paiCol).
80880   ** Non-composite foreign keys do not require the aiCol array.
80881   */
80882   if( nCol==1 ){
80883     /* The FK maps to the IPK if any of the following are true:
80884     **
80885     **   1) There is an INTEGER PRIMARY KEY column and the FK is implicitly 
80886     **      mapped to the primary key of table pParent, or
80887     **   2) The FK is explicitly mapped to a column declared as INTEGER
80888     **      PRIMARY KEY.
80889     */
80890     if( pParent->iPKey>=0 ){
80891       if( !zKey ) return 0;
80892       if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
80893     }
80894   }else if( paiCol ){
80895     assert( nCol>1 );
80896     aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
80897     if( !aiCol ) return 1;
80898     *paiCol = aiCol;
80899   }
80900
80901   for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
80902     if( pIdx->nColumn==nCol && pIdx->onError!=OE_None ){ 
80903       /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
80904       ** of columns. If each indexed column corresponds to a foreign key
80905       ** column of pFKey, then this index is a winner.  */
80906
80907       if( zKey==0 ){
80908         /* If zKey is NULL, then this foreign key is implicitly mapped to 
80909         ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be 
80910         ** identified by the test (Index.autoIndex==2).  */
80911         if( pIdx->autoIndex==2 ){
80912           if( aiCol ){
80913             int i;
80914             for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
80915           }
80916           break;
80917         }
80918       }else{
80919         /* If zKey is non-NULL, then this foreign key was declared to
80920         ** map to an explicit list of columns in table pParent. Check if this
80921         ** index matches those columns. Also, check that the index uses
80922         ** the default collation sequences for each column. */
80923         int i, j;
80924         for(i=0; i<nCol; i++){
80925           int iCol = pIdx->aiColumn[i];     /* Index of column in parent tbl */
80926           char *zDfltColl;                  /* Def. collation for column */
80927           char *zIdxCol;                    /* Name of indexed column */
80928
80929           /* If the index uses a collation sequence that is different from
80930           ** the default collation sequence for the column, this index is
80931           ** unusable. Bail out early in this case.  */
80932           zDfltColl = pParent->aCol[iCol].zColl;
80933           if( !zDfltColl ){
80934             zDfltColl = "BINARY";
80935           }
80936           if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
80937
80938           zIdxCol = pParent->aCol[iCol].zName;
80939           for(j=0; j<nCol; j++){
80940             if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
80941               if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
80942               break;
80943             }
80944           }
80945           if( j==nCol ) break;
80946         }
80947         if( i==nCol ) break;      /* pIdx is usable */
80948       }
80949     }
80950   }
80951
80952   if( !pIdx ){
80953     if( !pParse->disableTriggers ){
80954       sqlite3ErrorMsg(pParse, "foreign key mismatch");
80955     }
80956     sqlite3DbFree(pParse->db, aiCol);
80957     return 1;
80958   }
80959
80960   *ppIdx = pIdx;
80961   return 0;
80962 }
80963
80964 /*
80965 ** This function is called when a row is inserted into or deleted from the 
80966 ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed 
80967 ** on the child table of pFKey, this function is invoked twice for each row
80968 ** affected - once to "delete" the old row, and then again to "insert" the
80969 ** new row.
80970 **
80971 ** Each time it is called, this function generates VDBE code to locate the
80972 ** row in the parent table that corresponds to the row being inserted into 
80973 ** or deleted from the child table. If the parent row can be found, no 
80974 ** special action is taken. Otherwise, if the parent row can *not* be
80975 ** found in the parent table:
80976 **
80977 **   Operation | FK type   | Action taken
80978 **   --------------------------------------------------------------------------
80979 **   INSERT      immediate   Increment the "immediate constraint counter".
80980 **
80981 **   DELETE      immediate   Decrement the "immediate constraint counter".
80982 **
80983 **   INSERT      deferred    Increment the "deferred constraint counter".
80984 **
80985 **   DELETE      deferred    Decrement the "deferred constraint counter".
80986 **
80987 ** These operations are identified in the comment at the top of this file 
80988 ** (fkey.c) as "I.1" and "D.1".
80989 */
80990 static void fkLookupParent(
80991   Parse *pParse,        /* Parse context */
80992   int iDb,              /* Index of database housing pTab */
80993   Table *pTab,          /* Parent table of FK pFKey */
80994   Index *pIdx,          /* Unique index on parent key columns in pTab */
80995   FKey *pFKey,          /* Foreign key constraint */
80996   int *aiCol,           /* Map from parent key columns to child table columns */
80997   int regData,          /* Address of array containing child table row */
80998   int nIncr,            /* Increment constraint counter by this */
80999   int isIgnore          /* If true, pretend pTab contains all NULL values */
81000 ){
81001   int i;                                    /* Iterator variable */
81002   Vdbe *v = sqlite3GetVdbe(pParse);         /* Vdbe to add code to */
81003   int iCur = pParse->nTab - 1;              /* Cursor number to use */
81004   int iOk = sqlite3VdbeMakeLabel(v);        /* jump here if parent key found */
81005
81006   /* If nIncr is less than zero, then check at runtime if there are any
81007   ** outstanding constraints to resolve. If there are not, there is no need
81008   ** to check if deleting this row resolves any outstanding violations.
81009   **
81010   ** Check if any of the key columns in the child table row are NULL. If 
81011   ** any are, then the constraint is considered satisfied. No need to 
81012   ** search for a matching row in the parent table.  */
81013   if( nIncr<0 ){
81014     sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
81015   }
81016   for(i=0; i<pFKey->nCol; i++){
81017     int iReg = aiCol[i] + regData + 1;
81018     sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk);
81019   }
81020
81021   if( isIgnore==0 ){
81022     if( pIdx==0 ){
81023       /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
81024       ** column of the parent table (table pTab).  */
81025       int iMustBeInt;               /* Address of MustBeInt instruction */
81026       int regTemp = sqlite3GetTempReg(pParse);
81027   
81028       /* Invoke MustBeInt to coerce the child key value to an integer (i.e. 
81029       ** apply the affinity of the parent key). If this fails, then there
81030       ** is no matching parent key. Before using MustBeInt, make a copy of
81031       ** the value. Otherwise, the value inserted into the child key column
81032       ** will have INTEGER affinity applied to it, which may not be correct.  */
81033       sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
81034       iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
81035   
81036       /* If the parent table is the same as the child table, and we are about
81037       ** to increment the constraint-counter (i.e. this is an INSERT operation),
81038       ** then check if the row being inserted matches itself. If so, do not
81039       ** increment the constraint-counter.  */
81040       if( pTab==pFKey->pFrom && nIncr==1 ){
81041         sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp);
81042       }
81043   
81044       sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
81045       sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp);
81046       sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
81047       sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
81048       sqlite3VdbeJumpHere(v, iMustBeInt);
81049       sqlite3ReleaseTempReg(pParse, regTemp);
81050     }else{
81051       int nCol = pFKey->nCol;
81052       int regTemp = sqlite3GetTempRange(pParse, nCol);
81053       int regRec = sqlite3GetTempReg(pParse);
81054       KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
81055   
81056       sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
81057       sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
81058       for(i=0; i<nCol; i++){
81059         sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
81060       }
81061   
81062       /* If the parent table is the same as the child table, and we are about
81063       ** to increment the constraint-counter (i.e. this is an INSERT operation),
81064       ** then check if the row being inserted matches itself. If so, do not
81065       ** increment the constraint-counter.  */
81066       if( pTab==pFKey->pFrom && nIncr==1 ){
81067         int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
81068         for(i=0; i<nCol; i++){
81069           int iChild = aiCol[i]+1+regData;
81070           int iParent = pIdx->aiColumn[i]+1+regData;
81071           sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent);
81072         }
81073         sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
81074       }
81075   
81076       sqlite3VdbeAddOp3(v, OP_MakeRecord, regTemp, nCol, regRec);
81077       sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), 0);
81078       sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0);
81079   
81080       sqlite3ReleaseTempReg(pParse, regRec);
81081       sqlite3ReleaseTempRange(pParse, regTemp, nCol);
81082     }
81083   }
81084
81085   if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
81086     /* Special case: If this is an INSERT statement that will insert exactly
81087     ** one row into the table, raise a constraint immediately instead of
81088     ** incrementing a counter. This is necessary as the VM code is being
81089     ** generated for will not open a statement transaction.  */
81090     assert( nIncr==1 );
81091     sqlite3HaltConstraint(
81092         pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
81093     );
81094   }else{
81095     if( nIncr>0 && pFKey->isDeferred==0 ){
81096       sqlite3ParseToplevel(pParse)->mayAbort = 1;
81097     }
81098     sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
81099   }
81100
81101   sqlite3VdbeResolveLabel(v, iOk);
81102   sqlite3VdbeAddOp1(v, OP_Close, iCur);
81103 }
81104
81105 /*
81106 ** This function is called to generate code executed when a row is deleted
81107 ** from the parent table of foreign key constraint pFKey and, if pFKey is 
81108 ** deferred, when a row is inserted into the same table. When generating
81109 ** code for an SQL UPDATE operation, this function may be called twice -
81110 ** once to "delete" the old row and once to "insert" the new row.
81111 **
81112 ** The code generated by this function scans through the rows in the child
81113 ** table that correspond to the parent table row being deleted or inserted.
81114 ** For each child row found, one of the following actions is taken:
81115 **
81116 **   Operation | FK type   | Action taken
81117 **   --------------------------------------------------------------------------
81118 **   DELETE      immediate   Increment the "immediate constraint counter".
81119 **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
81120 **                           throw a "foreign key constraint failed" exception.
81121 **
81122 **   INSERT      immediate   Decrement the "immediate constraint counter".
81123 **
81124 **   DELETE      deferred    Increment the "deferred constraint counter".
81125 **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
81126 **                           throw a "foreign key constraint failed" exception.
81127 **
81128 **   INSERT      deferred    Decrement the "deferred constraint counter".
81129 **
81130 ** These operations are identified in the comment at the top of this file 
81131 ** (fkey.c) as "I.2" and "D.2".
81132 */
81133 static void fkScanChildren(
81134   Parse *pParse,                  /* Parse context */
81135   SrcList *pSrc,                  /* SrcList containing the table to scan */
81136   Table *pTab,
81137   Index *pIdx,                    /* Foreign key index */
81138   FKey *pFKey,                    /* Foreign key relationship */
81139   int *aiCol,                     /* Map from pIdx cols to child table cols */
81140   int regData,                    /* Referenced table data starts here */
81141   int nIncr                       /* Amount to increment deferred counter by */
81142 ){
81143   sqlite3 *db = pParse->db;       /* Database handle */
81144   int i;                          /* Iterator variable */
81145   Expr *pWhere = 0;               /* WHERE clause to scan with */
81146   NameContext sNameContext;       /* Context used to resolve WHERE clause */
81147   WhereInfo *pWInfo;              /* Context used by sqlite3WhereXXX() */
81148   int iFkIfZero = 0;              /* Address of OP_FkIfZero */
81149   Vdbe *v = sqlite3GetVdbe(pParse);
81150
81151   assert( !pIdx || pIdx->pTable==pTab );
81152
81153   if( nIncr<0 ){
81154     iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
81155   }
81156
81157   /* Create an Expr object representing an SQL expression like:
81158   **
81159   **   <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
81160   **
81161   ** The collation sequence used for the comparison should be that of
81162   ** the parent key columns. The affinity of the parent key column should
81163   ** be applied to each child key value before the comparison takes place.
81164   */
81165   for(i=0; i<pFKey->nCol; i++){
81166     Expr *pLeft;                  /* Value from parent table row */
81167     Expr *pRight;                 /* Column ref to child table */
81168     Expr *pEq;                    /* Expression (pLeft = pRight) */
81169     int iCol;                     /* Index of column in child table */ 
81170     const char *zCol;             /* Name of column in child table */
81171
81172     pLeft = sqlite3Expr(db, TK_REGISTER, 0);
81173     if( pLeft ){
81174       /* Set the collation sequence and affinity of the LHS of each TK_EQ
81175       ** expression to the parent key column defaults.  */
81176       if( pIdx ){
81177         Column *pCol;
81178         iCol = pIdx->aiColumn[i];
81179         pCol = &pTab->aCol[iCol];
81180         if( pTab->iPKey==iCol ) iCol = -1;
81181         pLeft->iTable = regData+iCol+1;
81182         pLeft->affinity = pCol->affinity;
81183         pLeft->pColl = sqlite3LocateCollSeq(pParse, pCol->zColl);
81184       }else{
81185         pLeft->iTable = regData;
81186         pLeft->affinity = SQLITE_AFF_INTEGER;
81187       }
81188     }
81189     iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
81190     assert( iCol>=0 );
81191     zCol = pFKey->pFrom->aCol[iCol].zName;
81192     pRight = sqlite3Expr(db, TK_ID, zCol);
81193     pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
81194     pWhere = sqlite3ExprAnd(db, pWhere, pEq);
81195   }
81196
81197   /* If the child table is the same as the parent table, and this scan
81198   ** is taking place as part of a DELETE operation (operation D.2), omit the
81199   ** row being deleted from the scan by adding ($rowid != rowid) to the WHERE 
81200   ** clause, where $rowid is the rowid of the row being deleted.  */
81201   if( pTab==pFKey->pFrom && nIncr>0 ){
81202     Expr *pEq;                    /* Expression (pLeft = pRight) */
81203     Expr *pLeft;                  /* Value from parent table row */
81204     Expr *pRight;                 /* Column ref to child table */
81205     pLeft = sqlite3Expr(db, TK_REGISTER, 0);
81206     pRight = sqlite3Expr(db, TK_COLUMN, 0);
81207     if( pLeft && pRight ){
81208       pLeft->iTable = regData;
81209       pLeft->affinity = SQLITE_AFF_INTEGER;
81210       pRight->iTable = pSrc->a[0].iCursor;
81211       pRight->iColumn = -1;
81212     }
81213     pEq = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
81214     pWhere = sqlite3ExprAnd(db, pWhere, pEq);
81215   }
81216
81217   /* Resolve the references in the WHERE clause. */
81218   memset(&sNameContext, 0, sizeof(NameContext));
81219   sNameContext.pSrcList = pSrc;
81220   sNameContext.pParse = pParse;
81221   sqlite3ResolveExprNames(&sNameContext, pWhere);
81222
81223   /* Create VDBE to loop through the entries in pSrc that match the WHERE
81224   ** clause. If the constraint is not deferred, throw an exception for
81225   ** each row found. Otherwise, for deferred constraints, increment the
81226   ** deferred constraint counter by nIncr for each row selected.  */
81227   pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0);
81228   if( nIncr>0 && pFKey->isDeferred==0 ){
81229     sqlite3ParseToplevel(pParse)->mayAbort = 1;
81230   }
81231   sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
81232   if( pWInfo ){
81233     sqlite3WhereEnd(pWInfo);
81234   }
81235
81236   /* Clean up the WHERE clause constructed above. */
81237   sqlite3ExprDelete(db, pWhere);
81238   if( iFkIfZero ){
81239     sqlite3VdbeJumpHere(v, iFkIfZero);
81240   }
81241 }
81242
81243 /*
81244 ** This function returns a pointer to the head of a linked list of FK
81245 ** constraints for which table pTab is the parent table. For example,
81246 ** given the following schema:
81247 **
81248 **   CREATE TABLE t1(a PRIMARY KEY);
81249 **   CREATE TABLE t2(b REFERENCES t1(a);
81250 **
81251 ** Calling this function with table "t1" as an argument returns a pointer
81252 ** to the FKey structure representing the foreign key constraint on table
81253 ** "t2". Calling this function with "t2" as the argument would return a
81254 ** NULL pointer (as there are no FK constraints for which t2 is the parent
81255 ** table).
81256 */
81257 SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
81258   int nName = sqlite3Strlen30(pTab->zName);
81259   return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName);
81260 }
81261
81262 /*
81263 ** The second argument is a Trigger structure allocated by the 
81264 ** fkActionTrigger() routine. This function deletes the Trigger structure
81265 ** and all of its sub-components.
81266 **
81267 ** The Trigger structure or any of its sub-components may be allocated from
81268 ** the lookaside buffer belonging to database handle dbMem.
81269 */
81270 static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
81271   if( p ){
81272     TriggerStep *pStep = p->step_list;
81273     sqlite3ExprDelete(dbMem, pStep->pWhere);
81274     sqlite3ExprListDelete(dbMem, pStep->pExprList);
81275     sqlite3SelectDelete(dbMem, pStep->pSelect);
81276     sqlite3ExprDelete(dbMem, p->pWhen);
81277     sqlite3DbFree(dbMem, p);
81278   }
81279 }
81280
81281 /*
81282 ** This function is called to generate code that runs when table pTab is
81283 ** being dropped from the database. The SrcList passed as the second argument
81284 ** to this function contains a single entry guaranteed to resolve to
81285 ** table pTab.
81286 **
81287 ** Normally, no code is required. However, if either
81288 **
81289 **   (a) The table is the parent table of a FK constraint, or
81290 **   (b) The table is the child table of a deferred FK constraint and it is
81291 **       determined at runtime that there are outstanding deferred FK 
81292 **       constraint violations in the database,
81293 **
81294 ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
81295 ** the table from the database. Triggers are disabled while running this
81296 ** DELETE, but foreign key actions are not.
81297 */
81298 SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
81299   sqlite3 *db = pParse->db;
81300   if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
81301     int iSkip = 0;
81302     Vdbe *v = sqlite3GetVdbe(pParse);
81303
81304     assert( v );                  /* VDBE has already been allocated */
81305     if( sqlite3FkReferences(pTab)==0 ){
81306       /* Search for a deferred foreign key constraint for which this table
81307       ** is the child table. If one cannot be found, return without 
81308       ** generating any VDBE code. If one can be found, then jump over
81309       ** the entire DELETE if there are no outstanding deferred constraints
81310       ** when this statement is run.  */
81311       FKey *p;
81312       for(p=pTab->pFKey; p; p=p->pNextFrom){
81313         if( p->isDeferred ) break;
81314       }
81315       if( !p ) return;
81316       iSkip = sqlite3VdbeMakeLabel(v);
81317       sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip);
81318     }
81319
81320     pParse->disableTriggers = 1;
81321     sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
81322     pParse->disableTriggers = 0;
81323
81324     /* If the DELETE has generated immediate foreign key constraint 
81325     ** violations, halt the VDBE and return an error at this point, before
81326     ** any modifications to the schema are made. This is because statement
81327     ** transactions are not able to rollback schema changes.  */
81328     sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
81329     sqlite3HaltConstraint(
81330         pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
81331     );
81332
81333     if( iSkip ){
81334       sqlite3VdbeResolveLabel(v, iSkip);
81335     }
81336   }
81337 }
81338
81339 /*
81340 ** This function is called when inserting, deleting or updating a row of
81341 ** table pTab to generate VDBE code to perform foreign key constraint 
81342 ** processing for the operation.
81343 **
81344 ** For a DELETE operation, parameter regOld is passed the index of the
81345 ** first register in an array of (pTab->nCol+1) registers containing the
81346 ** rowid of the row being deleted, followed by each of the column values
81347 ** of the row being deleted, from left to right. Parameter regNew is passed
81348 ** zero in this case.
81349 **
81350 ** For an INSERT operation, regOld is passed zero and regNew is passed the
81351 ** first register of an array of (pTab->nCol+1) registers containing the new
81352 ** row data.
81353 **
81354 ** For an UPDATE operation, this function is called twice. Once before
81355 ** the original record is deleted from the table using the calling convention
81356 ** described for DELETE. Then again after the original record is deleted
81357 ** but before the new record is inserted using the INSERT convention. 
81358 */
81359 SQLITE_PRIVATE void sqlite3FkCheck(
81360   Parse *pParse,                  /* Parse context */
81361   Table *pTab,                    /* Row is being deleted from this table */ 
81362   int regOld,                     /* Previous row data is stored here */
81363   int regNew                      /* New row data is stored here */
81364 ){
81365   sqlite3 *db = pParse->db;       /* Database handle */
81366   Vdbe *v;                        /* VM to write code to */
81367   FKey *pFKey;                    /* Used to iterate through FKs */
81368   int iDb;                        /* Index of database containing pTab */
81369   const char *zDb;                /* Name of database containing pTab */
81370   int isIgnoreErrors = pParse->disableTriggers;
81371
81372   /* Exactly one of regOld and regNew should be non-zero. */
81373   assert( (regOld==0)!=(regNew==0) );
81374
81375   /* If foreign-keys are disabled, this function is a no-op. */
81376   if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
81377
81378   v = sqlite3GetVdbe(pParse);
81379   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
81380   zDb = db->aDb[iDb].zName;
81381
81382   /* Loop through all the foreign key constraints for which pTab is the
81383   ** child table (the table that the foreign key definition is part of).  */
81384   for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
81385     Table *pTo;                   /* Parent table of foreign key pFKey */
81386     Index *pIdx = 0;              /* Index on key columns in pTo */
81387     int *aiFree = 0;
81388     int *aiCol;
81389     int iCol;
81390     int i;
81391     int isIgnore = 0;
81392
81393     /* Find the parent table of this foreign key. Also find a unique index 
81394     ** on the parent key columns in the parent table. If either of these 
81395     ** schema items cannot be located, set an error in pParse and return 
81396     ** early.  */
81397     if( pParse->disableTriggers ){
81398       pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
81399     }else{
81400       pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
81401     }
81402     if( !pTo || locateFkeyIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
81403       if( !isIgnoreErrors || db->mallocFailed ) return;
81404       continue;
81405     }
81406     assert( pFKey->nCol==1 || (aiFree && pIdx) );
81407
81408     if( aiFree ){
81409       aiCol = aiFree;
81410     }else{
81411       iCol = pFKey->aCol[0].iFrom;
81412       aiCol = &iCol;
81413     }
81414     for(i=0; i<pFKey->nCol; i++){
81415       if( aiCol[i]==pTab->iPKey ){
81416         aiCol[i] = -1;
81417       }
81418 #ifndef SQLITE_OMIT_AUTHORIZATION
81419       /* Request permission to read the parent key columns. If the 
81420       ** authorization callback returns SQLITE_IGNORE, behave as if any
81421       ** values read from the parent table are NULL. */
81422       if( db->xAuth ){
81423         int rcauth;
81424         char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
81425         rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
81426         isIgnore = (rcauth==SQLITE_IGNORE);
81427       }
81428 #endif
81429     }
81430
81431     /* Take a shared-cache advisory read-lock on the parent table. Allocate 
81432     ** a cursor to use to search the unique index on the parent key columns 
81433     ** in the parent table.  */
81434     sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
81435     pParse->nTab++;
81436
81437     if( regOld!=0 ){
81438       /* A row is being removed from the child table. Search for the parent.
81439       ** If the parent does not exist, removing the child row resolves an 
81440       ** outstanding foreign key constraint violation. */
81441       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1,isIgnore);
81442     }
81443     if( regNew!=0 ){
81444       /* A row is being added to the child table. If a parent row cannot
81445       ** be found, adding the child row has violated the FK constraint. */ 
81446       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1,isIgnore);
81447     }
81448
81449     sqlite3DbFree(db, aiFree);
81450   }
81451
81452   /* Loop through all the foreign key constraints that refer to this table */
81453   for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
81454     Index *pIdx = 0;              /* Foreign key index for pFKey */
81455     SrcList *pSrc;
81456     int *aiCol = 0;
81457
81458     if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
81459       assert( regOld==0 && regNew!=0 );
81460       /* Inserting a single row into a parent table cannot cause an immediate
81461       ** foreign key violation. So do nothing in this case.  */
81462       continue;
81463     }
81464
81465     if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
81466       if( !isIgnoreErrors || db->mallocFailed ) return;
81467       continue;
81468     }
81469     assert( aiCol || pFKey->nCol==1 );
81470
81471     /* Create a SrcList structure containing a single table (the table 
81472     ** the foreign key that refers to this table is attached to). This
81473     ** is required for the sqlite3WhereXXX() interface.  */
81474     pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
81475     if( pSrc ){
81476       struct SrcList_item *pItem = pSrc->a;
81477       pItem->pTab = pFKey->pFrom;
81478       pItem->zName = pFKey->pFrom->zName;
81479       pItem->pTab->nRef++;
81480       pItem->iCursor = pParse->nTab++;
81481   
81482       if( regNew!=0 ){
81483         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
81484       }
81485       if( regOld!=0 ){
81486         /* If there is a RESTRICT action configured for the current operation
81487         ** on the parent table of this FK, then throw an exception 
81488         ** immediately if the FK constraint is violated, even if this is a
81489         ** deferred trigger. That's what RESTRICT means. To defer checking
81490         ** the constraint, the FK should specify NO ACTION (represented
81491         ** using OE_None). NO ACTION is the default.  */
81492         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
81493       }
81494       pItem->zName = 0;
81495       sqlite3SrcListDelete(db, pSrc);
81496     }
81497     sqlite3DbFree(db, aiCol);
81498   }
81499 }
81500
81501 #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
81502
81503 /*
81504 ** This function is called before generating code to update or delete a 
81505 ** row contained in table pTab.
81506 */
81507 SQLITE_PRIVATE u32 sqlite3FkOldmask(
81508   Parse *pParse,                  /* Parse context */
81509   Table *pTab                     /* Table being modified */
81510 ){
81511   u32 mask = 0;
81512   if( pParse->db->flags&SQLITE_ForeignKeys ){
81513     FKey *p;
81514     int i;
81515     for(p=pTab->pFKey; p; p=p->pNextFrom){
81516       for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
81517     }
81518     for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
81519       Index *pIdx = 0;
81520       locateFkeyIndex(pParse, pTab, p, &pIdx, 0);
81521       if( pIdx ){
81522         for(i=0; i<pIdx->nColumn; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
81523       }
81524     }
81525   }
81526   return mask;
81527 }
81528
81529 /*
81530 ** This function is called before generating code to update or delete a 
81531 ** row contained in table pTab. If the operation is a DELETE, then
81532 ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
81533 ** to an array of size N, where N is the number of columns in table pTab.
81534 ** If the i'th column is not modified by the UPDATE, then the corresponding 
81535 ** entry in the aChange[] array is set to -1. If the column is modified,
81536 ** the value is 0 or greater. Parameter chngRowid is set to true if the
81537 ** UPDATE statement modifies the rowid fields of the table.
81538 **
81539 ** If any foreign key processing will be required, this function returns
81540 ** true. If there is no foreign key related processing, this function 
81541 ** returns false.
81542 */
81543 SQLITE_PRIVATE int sqlite3FkRequired(
81544   Parse *pParse,                  /* Parse context */
81545   Table *pTab,                    /* Table being modified */
81546   int *aChange,                   /* Non-NULL for UPDATE operations */
81547   int chngRowid                   /* True for UPDATE that affects rowid */
81548 ){
81549   if( pParse->db->flags&SQLITE_ForeignKeys ){
81550     if( !aChange ){
81551       /* A DELETE operation. Foreign key processing is required if the 
81552       ** table in question is either the child or parent table for any 
81553       ** foreign key constraint.  */
81554       return (sqlite3FkReferences(pTab) || pTab->pFKey);
81555     }else{
81556       /* This is an UPDATE. Foreign key processing is only required if the
81557       ** operation modifies one or more child or parent key columns. */
81558       int i;
81559       FKey *p;
81560
81561       /* Check if any child key columns are being modified. */
81562       for(p=pTab->pFKey; p; p=p->pNextFrom){
81563         for(i=0; i<p->nCol; i++){
81564           int iChildKey = p->aCol[i].iFrom;
81565           if( aChange[iChildKey]>=0 ) return 1;
81566           if( iChildKey==pTab->iPKey && chngRowid ) return 1;
81567         }
81568       }
81569
81570       /* Check if any parent key columns are being modified. */
81571       for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
81572         for(i=0; i<p->nCol; i++){
81573           char *zKey = p->aCol[i].zCol;
81574           int iKey;
81575           for(iKey=0; iKey<pTab->nCol; iKey++){
81576             Column *pCol = &pTab->aCol[iKey];
81577             if( (zKey ? !sqlite3StrICmp(pCol->zName, zKey) : pCol->isPrimKey) ){
81578               if( aChange[iKey]>=0 ) return 1;
81579               if( iKey==pTab->iPKey && chngRowid ) return 1;
81580             }
81581           }
81582         }
81583       }
81584     }
81585   }
81586   return 0;
81587 }
81588
81589 /*
81590 ** This function is called when an UPDATE or DELETE operation is being 
81591 ** compiled on table pTab, which is the parent table of foreign-key pFKey.
81592 ** If the current operation is an UPDATE, then the pChanges parameter is
81593 ** passed a pointer to the list of columns being modified. If it is a
81594 ** DELETE, pChanges is passed a NULL pointer.
81595 **
81596 ** It returns a pointer to a Trigger structure containing a trigger
81597 ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
81598 ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
81599 ** returned (these actions require no special handling by the triggers
81600 ** sub-system, code for them is created by fkScanChildren()).
81601 **
81602 ** For example, if pFKey is the foreign key and pTab is table "p" in 
81603 ** the following schema:
81604 **
81605 **   CREATE TABLE p(pk PRIMARY KEY);
81606 **   CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
81607 **
81608 ** then the returned trigger structure is equivalent to:
81609 **
81610 **   CREATE TRIGGER ... DELETE ON p BEGIN
81611 **     DELETE FROM c WHERE ck = old.pk;
81612 **   END;
81613 **
81614 ** The returned pointer is cached as part of the foreign key object. It
81615 ** is eventually freed along with the rest of the foreign key object by 
81616 ** sqlite3FkDelete().
81617 */
81618 static Trigger *fkActionTrigger(
81619   Parse *pParse,                  /* Parse context */
81620   Table *pTab,                    /* Table being updated or deleted from */
81621   FKey *pFKey,                    /* Foreign key to get action for */
81622   ExprList *pChanges              /* Change-list for UPDATE, NULL for DELETE */
81623 ){
81624   sqlite3 *db = pParse->db;       /* Database handle */
81625   int action;                     /* One of OE_None, OE_Cascade etc. */
81626   Trigger *pTrigger;              /* Trigger definition to return */
81627   int iAction = (pChanges!=0);    /* 1 for UPDATE, 0 for DELETE */
81628
81629   action = pFKey->aAction[iAction];
81630   pTrigger = pFKey->apTrigger[iAction];
81631
81632   if( action!=OE_None && !pTrigger ){
81633     u8 enableLookaside;           /* Copy of db->lookaside.bEnabled */
81634     char const *zFrom;            /* Name of child table */
81635     int nFrom;                    /* Length in bytes of zFrom */
81636     Index *pIdx = 0;              /* Parent key index for this FK */
81637     int *aiCol = 0;               /* child table cols -> parent key cols */
81638     TriggerStep *pStep = 0;        /* First (only) step of trigger program */
81639     Expr *pWhere = 0;             /* WHERE clause of trigger step */
81640     ExprList *pList = 0;          /* Changes list if ON UPDATE CASCADE */
81641     Select *pSelect = 0;          /* If RESTRICT, "SELECT RAISE(...)" */
81642     int i;                        /* Iterator variable */
81643     Expr *pWhen = 0;              /* WHEN clause for the trigger */
81644
81645     if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
81646     assert( aiCol || pFKey->nCol==1 );
81647
81648     for(i=0; i<pFKey->nCol; i++){
81649       Token tOld = { "old", 3 };  /* Literal "old" token */
81650       Token tNew = { "new", 3 };  /* Literal "new" token */
81651       Token tFromCol;             /* Name of column in child table */
81652       Token tToCol;               /* Name of column in parent table */
81653       int iFromCol;               /* Idx of column in child table */
81654       Expr *pEq;                  /* tFromCol = OLD.tToCol */
81655
81656       iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
81657       assert( iFromCol>=0 );
81658       tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
81659       tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
81660
81661       tToCol.n = sqlite3Strlen30(tToCol.z);
81662       tFromCol.n = sqlite3Strlen30(tFromCol.z);
81663
81664       /* Create the expression "OLD.zToCol = zFromCol". It is important
81665       ** that the "OLD.zToCol" term is on the LHS of the = operator, so
81666       ** that the affinity and collation sequence associated with the
81667       ** parent table are used for the comparison. */
81668       pEq = sqlite3PExpr(pParse, TK_EQ,
81669           sqlite3PExpr(pParse, TK_DOT, 
81670             sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
81671             sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
81672           , 0),
81673           sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol)
81674       , 0);
81675       pWhere = sqlite3ExprAnd(db, pWhere, pEq);
81676
81677       /* For ON UPDATE, construct the next term of the WHEN clause.
81678       ** The final WHEN clause will be like this:
81679       **
81680       **    WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
81681       */
81682       if( pChanges ){
81683         pEq = sqlite3PExpr(pParse, TK_IS,
81684             sqlite3PExpr(pParse, TK_DOT, 
81685               sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
81686               sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
81687               0),
81688             sqlite3PExpr(pParse, TK_DOT, 
81689               sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
81690               sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
81691               0),
81692             0);
81693         pWhen = sqlite3ExprAnd(db, pWhen, pEq);
81694       }
81695   
81696       if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
81697         Expr *pNew;
81698         if( action==OE_Cascade ){
81699           pNew = sqlite3PExpr(pParse, TK_DOT, 
81700             sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
81701             sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
81702           , 0);
81703         }else if( action==OE_SetDflt ){
81704           Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
81705           if( pDflt ){
81706             pNew = sqlite3ExprDup(db, pDflt, 0);
81707           }else{
81708             pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
81709           }
81710         }else{
81711           pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
81712         }
81713         pList = sqlite3ExprListAppend(pParse, pList, pNew);
81714         sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
81715       }
81716     }
81717     sqlite3DbFree(db, aiCol);
81718
81719     zFrom = pFKey->pFrom->zName;
81720     nFrom = sqlite3Strlen30(zFrom);
81721
81722     if( action==OE_Restrict ){
81723       Token tFrom;
81724       Expr *pRaise; 
81725
81726       tFrom.z = zFrom;
81727       tFrom.n = nFrom;
81728       pRaise = sqlite3Expr(db, TK_RAISE, "foreign key constraint failed");
81729       if( pRaise ){
81730         pRaise->affinity = OE_Abort;
81731       }
81732       pSelect = sqlite3SelectNew(pParse, 
81733           sqlite3ExprListAppend(pParse, 0, pRaise),
81734           sqlite3SrcListAppend(db, 0, &tFrom, 0),
81735           pWhere,
81736           0, 0, 0, 0, 0, 0
81737       );
81738       pWhere = 0;
81739     }
81740
81741     /* Disable lookaside memory allocation */
81742     enableLookaside = db->lookaside.bEnabled;
81743     db->lookaside.bEnabled = 0;
81744
81745     pTrigger = (Trigger *)sqlite3DbMallocZero(db, 
81746         sizeof(Trigger) +         /* struct Trigger */
81747         sizeof(TriggerStep) +     /* Single step in trigger program */
81748         nFrom + 1                 /* Space for pStep->target.z */
81749     );
81750     if( pTrigger ){
81751       pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
81752       pStep->target.z = (char *)&pStep[1];
81753       pStep->target.n = nFrom;
81754       memcpy((char *)pStep->target.z, zFrom, nFrom);
81755   
81756       pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
81757       pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
81758       pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
81759       if( pWhen ){
81760         pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
81761         pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
81762       }
81763     }
81764
81765     /* Re-enable the lookaside buffer, if it was disabled earlier. */
81766     db->lookaside.bEnabled = enableLookaside;
81767
81768     sqlite3ExprDelete(db, pWhere);
81769     sqlite3ExprDelete(db, pWhen);
81770     sqlite3ExprListDelete(db, pList);
81771     sqlite3SelectDelete(db, pSelect);
81772     if( db->mallocFailed==1 ){
81773       fkTriggerDelete(db, pTrigger);
81774       return 0;
81775     }
81776
81777     switch( action ){
81778       case OE_Restrict:
81779         pStep->op = TK_SELECT; 
81780         break;
81781       case OE_Cascade: 
81782         if( !pChanges ){ 
81783           pStep->op = TK_DELETE; 
81784           break; 
81785         }
81786       default:
81787         pStep->op = TK_UPDATE;
81788     }
81789     pStep->pTrig = pTrigger;
81790     pTrigger->pSchema = pTab->pSchema;
81791     pTrigger->pTabSchema = pTab->pSchema;
81792     pFKey->apTrigger[iAction] = pTrigger;
81793     pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
81794   }
81795
81796   return pTrigger;
81797 }
81798
81799 /*
81800 ** This function is called when deleting or updating a row to implement
81801 ** any required CASCADE, SET NULL or SET DEFAULT actions.
81802 */
81803 SQLITE_PRIVATE void sqlite3FkActions(
81804   Parse *pParse,                  /* Parse context */
81805   Table *pTab,                    /* Table being updated or deleted from */
81806   ExprList *pChanges,             /* Change-list for UPDATE, NULL for DELETE */
81807   int regOld                      /* Address of array containing old row */
81808 ){
81809   /* If foreign-key support is enabled, iterate through all FKs that 
81810   ** refer to table pTab. If there is an action associated with the FK 
81811   ** for this operation (either update or delete), invoke the associated 
81812   ** trigger sub-program.  */
81813   if( pParse->db->flags&SQLITE_ForeignKeys ){
81814     FKey *pFKey;                  /* Iterator variable */
81815     for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
81816       Trigger *pAction = fkActionTrigger(pParse, pTab, pFKey, pChanges);
81817       if( pAction ){
81818         sqlite3CodeRowTriggerDirect(pParse, pAction, pTab, regOld, OE_Abort, 0);
81819       }
81820     }
81821   }
81822 }
81823
81824 #endif /* ifndef SQLITE_OMIT_TRIGGER */
81825
81826 /*
81827 ** Free all memory associated with foreign key definitions attached to
81828 ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
81829 ** hash table.
81830 */
81831 SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
81832   FKey *pFKey;                    /* Iterator variable */
81833   FKey *pNext;                    /* Copy of pFKey->pNextFrom */
81834
81835   for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
81836
81837     /* Remove the FK from the fkeyHash hash table. */
81838     if( !db || db->pnBytesFreed==0 ){
81839       if( pFKey->pPrevTo ){
81840         pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
81841       }else{
81842         void *p = (void *)pFKey->pNextTo;
81843         const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
81844         sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), p);
81845       }
81846       if( pFKey->pNextTo ){
81847         pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
81848       }
81849     }
81850
81851     /* EV: R-30323-21917 Each foreign key constraint in SQLite is
81852     ** classified as either immediate or deferred.
81853     */
81854     assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
81855
81856     /* Delete any triggers created to implement actions for this FK. */
81857 #ifndef SQLITE_OMIT_TRIGGER
81858     fkTriggerDelete(db, pFKey->apTrigger[0]);
81859     fkTriggerDelete(db, pFKey->apTrigger[1]);
81860 #endif
81861
81862     pNext = pFKey->pNextFrom;
81863     sqlite3DbFree(db, pFKey);
81864   }
81865 }
81866 #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
81867
81868 /************** End of fkey.c ************************************************/
81869 /************** Begin file insert.c ******************************************/
81870 /*
81871 ** 2001 September 15
81872 **
81873 ** The author disclaims copyright to this source code.  In place of
81874 ** a legal notice, here is a blessing:
81875 **
81876 **    May you do good and not evil.
81877 **    May you find forgiveness for yourself and forgive others.
81878 **    May you share freely, never taking more than you give.
81879 **
81880 *************************************************************************
81881 ** This file contains C code routines that are called by the parser
81882 ** to handle INSERT statements in SQLite.
81883 */
81884
81885 /*
81886 ** Generate code that will open a table for reading.
81887 */
81888 SQLITE_PRIVATE void sqlite3OpenTable(
81889   Parse *p,       /* Generate code into this VDBE */
81890   int iCur,       /* The cursor number of the table */
81891   int iDb,        /* The database index in sqlite3.aDb[] */
81892   Table *pTab,    /* The table to be opened */
81893   int opcode      /* OP_OpenRead or OP_OpenWrite */
81894 ){
81895   Vdbe *v;
81896   if( IsVirtual(pTab) ) return;
81897   v = sqlite3GetVdbe(p);
81898   assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
81899   sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
81900   sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
81901   sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(pTab->nCol), P4_INT32);
81902   VdbeComment((v, "%s", pTab->zName));
81903 }
81904
81905 /*
81906 ** Return a pointer to the column affinity string associated with index
81907 ** pIdx. A column affinity string has one character for each column in 
81908 ** the table, according to the affinity of the column:
81909 **
81910 **  Character      Column affinity
81911 **  ------------------------------
81912 **  'a'            TEXT
81913 **  'b'            NONE
81914 **  'c'            NUMERIC
81915 **  'd'            INTEGER
81916 **  'e'            REAL
81917 **
81918 ** An extra 'b' is appended to the end of the string to cover the
81919 ** rowid that appears as the last column in every index.
81920 **
81921 ** Memory for the buffer containing the column index affinity string
81922 ** is managed along with the rest of the Index structure. It will be
81923 ** released when sqlite3DeleteIndex() is called.
81924 */
81925 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
81926   if( !pIdx->zColAff ){
81927     /* The first time a column affinity string for a particular index is
81928     ** required, it is allocated and populated here. It is then stored as
81929     ** a member of the Index structure for subsequent use.
81930     **
81931     ** The column affinity string will eventually be deleted by
81932     ** sqliteDeleteIndex() when the Index structure itself is cleaned
81933     ** up.
81934     */
81935     int n;
81936     Table *pTab = pIdx->pTable;
81937     sqlite3 *db = sqlite3VdbeDb(v);
81938     pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+2);
81939     if( !pIdx->zColAff ){
81940       db->mallocFailed = 1;
81941       return 0;
81942     }
81943     for(n=0; n<pIdx->nColumn; n++){
81944       pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
81945     }
81946     pIdx->zColAff[n++] = SQLITE_AFF_NONE;
81947     pIdx->zColAff[n] = 0;
81948   }
81949  
81950   return pIdx->zColAff;
81951 }
81952
81953 /*
81954 ** Set P4 of the most recently inserted opcode to a column affinity
81955 ** string for table pTab. A column affinity string has one character
81956 ** for each column indexed by the index, according to the affinity of the
81957 ** column:
81958 **
81959 **  Character      Column affinity
81960 **  ------------------------------
81961 **  'a'            TEXT
81962 **  'b'            NONE
81963 **  'c'            NUMERIC
81964 **  'd'            INTEGER
81965 **  'e'            REAL
81966 */
81967 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
81968   /* The first time a column affinity string for a particular table
81969   ** is required, it is allocated and populated here. It is then 
81970   ** stored as a member of the Table structure for subsequent use.
81971   **
81972   ** The column affinity string will eventually be deleted by
81973   ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
81974   */
81975   if( !pTab->zColAff ){
81976     char *zColAff;
81977     int i;
81978     sqlite3 *db = sqlite3VdbeDb(v);
81979
81980     zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
81981     if( !zColAff ){
81982       db->mallocFailed = 1;
81983       return;
81984     }
81985
81986     for(i=0; i<pTab->nCol; i++){
81987       zColAff[i] = pTab->aCol[i].affinity;
81988     }
81989     zColAff[pTab->nCol] = '\0';
81990
81991     pTab->zColAff = zColAff;
81992   }
81993
81994   sqlite3VdbeChangeP4(v, -1, pTab->zColAff, 0);
81995 }
81996
81997 /*
81998 ** Return non-zero if the table pTab in database iDb or any of its indices
81999 ** have been opened at any point in the VDBE program beginning at location
82000 ** iStartAddr throught the end of the program.  This is used to see if 
82001 ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can 
82002 ** run without using temporary table for the results of the SELECT. 
82003 */
82004 static int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){
82005   Vdbe *v = sqlite3GetVdbe(p);
82006   int i;
82007   int iEnd = sqlite3VdbeCurrentAddr(v);
82008 #ifndef SQLITE_OMIT_VIRTUALTABLE
82009   VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
82010 #endif
82011
82012   for(i=iStartAddr; i<iEnd; i++){
82013     VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
82014     assert( pOp!=0 );
82015     if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
82016       Index *pIndex;
82017       int tnum = pOp->p2;
82018       if( tnum==pTab->tnum ){
82019         return 1;
82020       }
82021       for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
82022         if( tnum==pIndex->tnum ){
82023           return 1;
82024         }
82025       }
82026     }
82027 #ifndef SQLITE_OMIT_VIRTUALTABLE
82028     if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
82029       assert( pOp->p4.pVtab!=0 );
82030       assert( pOp->p4type==P4_VTAB );
82031       return 1;
82032     }
82033 #endif
82034   }
82035   return 0;
82036 }
82037
82038 #ifndef SQLITE_OMIT_AUTOINCREMENT
82039 /*
82040 ** Locate or create an AutoincInfo structure associated with table pTab
82041 ** which is in database iDb.  Return the register number for the register
82042 ** that holds the maximum rowid.
82043 **
82044 ** There is at most one AutoincInfo structure per table even if the
82045 ** same table is autoincremented multiple times due to inserts within
82046 ** triggers.  A new AutoincInfo structure is created if this is the
82047 ** first use of table pTab.  On 2nd and subsequent uses, the original
82048 ** AutoincInfo structure is used.
82049 **
82050 ** Three memory locations are allocated:
82051 **
82052 **   (1)  Register to hold the name of the pTab table.
82053 **   (2)  Register to hold the maximum ROWID of pTab.
82054 **   (3)  Register to hold the rowid in sqlite_sequence of pTab
82055 **
82056 ** The 2nd register is the one that is returned.  That is all the
82057 ** insert routine needs to know about.
82058 */
82059 static int autoIncBegin(
82060   Parse *pParse,      /* Parsing context */
82061   int iDb,            /* Index of the database holding pTab */
82062   Table *pTab         /* The table we are writing to */
82063 ){
82064   int memId = 0;      /* Register holding maximum rowid */
82065   if( pTab->tabFlags & TF_Autoincrement ){
82066     Parse *pToplevel = sqlite3ParseToplevel(pParse);
82067     AutoincInfo *pInfo;
82068
82069     pInfo = pToplevel->pAinc;
82070     while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
82071     if( pInfo==0 ){
82072       pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
82073       if( pInfo==0 ) return 0;
82074       pInfo->pNext = pToplevel->pAinc;
82075       pToplevel->pAinc = pInfo;
82076       pInfo->pTab = pTab;
82077       pInfo->iDb = iDb;
82078       pToplevel->nMem++;                  /* Register to hold name of table */
82079       pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
82080       pToplevel->nMem++;                  /* Rowid in sqlite_sequence */
82081     }
82082     memId = pInfo->regCtr;
82083   }
82084   return memId;
82085 }
82086
82087 /*
82088 ** This routine generates code that will initialize all of the
82089 ** register used by the autoincrement tracker.  
82090 */
82091 SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
82092   AutoincInfo *p;            /* Information about an AUTOINCREMENT */
82093   sqlite3 *db = pParse->db;  /* The database connection */
82094   Db *pDb;                   /* Database only autoinc table */
82095   int memId;                 /* Register holding max rowid */
82096   int addr;                  /* A VDBE address */
82097   Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
82098
82099   /* This routine is never called during trigger-generation.  It is
82100   ** only called from the top-level */
82101   assert( pParse->pTriggerTab==0 );
82102   assert( pParse==sqlite3ParseToplevel(pParse) );
82103
82104   assert( v );   /* We failed long ago if this is not so */
82105   for(p = pParse->pAinc; p; p = p->pNext){
82106     pDb = &db->aDb[p->iDb];
82107     memId = p->regCtr;
82108     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
82109     addr = sqlite3VdbeCurrentAddr(v);
82110     sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
82111     sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9);
82112     sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
82113     sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
82114     sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
82115     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
82116     sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
82117     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
82118     sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2);
82119     sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
82120     sqlite3VdbeAddOp0(v, OP_Close);
82121   }
82122 }
82123
82124 /*
82125 ** Update the maximum rowid for an autoincrement calculation.
82126 **
82127 ** This routine should be called when the top of the stack holds a
82128 ** new rowid that is about to be inserted.  If that new rowid is
82129 ** larger than the maximum rowid in the memId memory cell, then the
82130 ** memory cell is updated.  The stack is unchanged.
82131 */
82132 static void autoIncStep(Parse *pParse, int memId, int regRowid){
82133   if( memId>0 ){
82134     sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
82135   }
82136 }
82137
82138 /*
82139 ** This routine generates the code needed to write autoincrement
82140 ** maximum rowid values back into the sqlite_sequence register.
82141 ** Every statement that might do an INSERT into an autoincrement
82142 ** table (either directly or through triggers) needs to call this
82143 ** routine just before the "exit" code.
82144 */
82145 SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
82146   AutoincInfo *p;
82147   Vdbe *v = pParse->pVdbe;
82148   sqlite3 *db = pParse->db;
82149
82150   assert( v );
82151   for(p = pParse->pAinc; p; p = p->pNext){
82152     Db *pDb = &db->aDb[p->iDb];
82153     int j1, j2, j3, j4, j5;
82154     int iRec;
82155     int memId = p->regCtr;
82156
82157     iRec = sqlite3GetTempReg(pParse);
82158     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
82159     j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
82160     j2 = sqlite3VdbeAddOp0(v, OP_Rewind);
82161     j3 = sqlite3VdbeAddOp3(v, OP_Column, 0, 0, iRec);
82162     j4 = sqlite3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec);
82163     sqlite3VdbeAddOp2(v, OP_Next, 0, j3);
82164     sqlite3VdbeJumpHere(v, j2);
82165     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
82166     j5 = sqlite3VdbeAddOp0(v, OP_Goto);
82167     sqlite3VdbeJumpHere(v, j4);
82168     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
82169     sqlite3VdbeJumpHere(v, j1);
82170     sqlite3VdbeJumpHere(v, j5);
82171     sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
82172     sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
82173     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
82174     sqlite3VdbeAddOp0(v, OP_Close);
82175     sqlite3ReleaseTempReg(pParse, iRec);
82176   }
82177 }
82178 #else
82179 /*
82180 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
82181 ** above are all no-ops
82182 */
82183 # define autoIncBegin(A,B,C) (0)
82184 # define autoIncStep(A,B,C)
82185 #endif /* SQLITE_OMIT_AUTOINCREMENT */
82186
82187
82188 /* Forward declaration */
82189 static int xferOptimization(
82190   Parse *pParse,        /* Parser context */
82191   Table *pDest,         /* The table we are inserting into */
82192   Select *pSelect,      /* A SELECT statement to use as the data source */
82193   int onError,          /* How to handle constraint errors */
82194   int iDbDest           /* The database of pDest */
82195 );
82196
82197 /*
82198 ** This routine is call to handle SQL of the following forms:
82199 **
82200 **    insert into TABLE (IDLIST) values(EXPRLIST)
82201 **    insert into TABLE (IDLIST) select
82202 **
82203 ** The IDLIST following the table name is always optional.  If omitted,
82204 ** then a list of all columns for the table is substituted.  The IDLIST
82205 ** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
82206 **
82207 ** The pList parameter holds EXPRLIST in the first form of the INSERT
82208 ** statement above, and pSelect is NULL.  For the second form, pList is
82209 ** NULL and pSelect is a pointer to the select statement used to generate
82210 ** data for the insert.
82211 **
82212 ** The code generated follows one of four templates.  For a simple
82213 ** select with data coming from a VALUES clause, the code executes
82214 ** once straight down through.  Pseudo-code follows (we call this
82215 ** the "1st template"):
82216 **
82217 **         open write cursor to <table> and its indices
82218 **         puts VALUES clause expressions onto the stack
82219 **         write the resulting record into <table>
82220 **         cleanup
82221 **
82222 ** The three remaining templates assume the statement is of the form
82223 **
82224 **   INSERT INTO <table> SELECT ...
82225 **
82226 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
82227 ** in other words if the SELECT pulls all columns from a single table
82228 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
82229 ** if <table2> and <table1> are distinct tables but have identical
82230 ** schemas, including all the same indices, then a special optimization
82231 ** is invoked that copies raw records from <table2> over to <table1>.
82232 ** See the xferOptimization() function for the implementation of this
82233 ** template.  This is the 2nd template.
82234 **
82235 **         open a write cursor to <table>
82236 **         open read cursor on <table2>
82237 **         transfer all records in <table2> over to <table>
82238 **         close cursors
82239 **         foreach index on <table>
82240 **           open a write cursor on the <table> index
82241 **           open a read cursor on the corresponding <table2> index
82242 **           transfer all records from the read to the write cursors
82243 **           close cursors
82244 **         end foreach
82245 **
82246 ** The 3rd template is for when the second template does not apply
82247 ** and the SELECT clause does not read from <table> at any time.
82248 ** The generated code follows this template:
82249 **
82250 **         EOF <- 0
82251 **         X <- A
82252 **         goto B
82253 **      A: setup for the SELECT
82254 **         loop over the rows in the SELECT
82255 **           load values into registers R..R+n
82256 **           yield X
82257 **         end loop
82258 **         cleanup after the SELECT
82259 **         EOF <- 1
82260 **         yield X
82261 **         goto A
82262 **      B: open write cursor to <table> and its indices
82263 **      C: yield X
82264 **         if EOF goto D
82265 **         insert the select result into <table> from R..R+n
82266 **         goto C
82267 **      D: cleanup
82268 **
82269 ** The 4th template is used if the insert statement takes its
82270 ** values from a SELECT but the data is being inserted into a table
82271 ** that is also read as part of the SELECT.  In the third form,
82272 ** we have to use a intermediate table to store the results of
82273 ** the select.  The template is like this:
82274 **
82275 **         EOF <- 0
82276 **         X <- A
82277 **         goto B
82278 **      A: setup for the SELECT
82279 **         loop over the tables in the SELECT
82280 **           load value into register R..R+n
82281 **           yield X
82282 **         end loop
82283 **         cleanup after the SELECT
82284 **         EOF <- 1
82285 **         yield X
82286 **         halt-error
82287 **      B: open temp table
82288 **      L: yield X
82289 **         if EOF goto M
82290 **         insert row from R..R+n into temp table
82291 **         goto L
82292 **      M: open write cursor to <table> and its indices
82293 **         rewind temp table
82294 **      C: loop over rows of intermediate table
82295 **           transfer values form intermediate table into <table>
82296 **         end loop
82297 **      D: cleanup
82298 */
82299 SQLITE_PRIVATE void sqlite3Insert(
82300   Parse *pParse,        /* Parser context */
82301   SrcList *pTabList,    /* Name of table into which we are inserting */
82302   ExprList *pList,      /* List of values to be inserted */
82303   Select *pSelect,      /* A SELECT statement to use as the data source */
82304   IdList *pColumn,      /* Column names corresponding to IDLIST. */
82305   int onError           /* How to handle constraint errors */
82306 ){
82307   sqlite3 *db;          /* The main database structure */
82308   Table *pTab;          /* The table to insert into.  aka TABLE */
82309   char *zTab;           /* Name of the table into which we are inserting */
82310   const char *zDb;      /* Name of the database holding this table */
82311   int i, j, idx;        /* Loop counters */
82312   Vdbe *v;              /* Generate code into this virtual machine */
82313   Index *pIdx;          /* For looping over indices of the table */
82314   int nColumn;          /* Number of columns in the data */
82315   int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
82316   int baseCur = 0;      /* VDBE Cursor number for pTab */
82317   int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
82318   int endOfLoop;        /* Label for the end of the insertion loop */
82319   int useTempTable = 0; /* Store SELECT results in intermediate table */
82320   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
82321   int addrInsTop = 0;   /* Jump to label "D" */
82322   int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
82323   int addrSelect = 0;   /* Address of coroutine that implements the SELECT */
82324   SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
82325   int iDb;              /* Index of database holding TABLE */
82326   Db *pDb;              /* The database containing table being inserted into */
82327   int appendFlag = 0;   /* True if the insert is likely to be an append */
82328
82329   /* Register allocations */
82330   int regFromSelect = 0;/* Base register for data coming from SELECT */
82331   int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
82332   int regRowCount = 0;  /* Memory cell used for the row counter */
82333   int regIns;           /* Block of regs holding rowid+data being inserted */
82334   int regRowid;         /* registers holding insert rowid */
82335   int regData;          /* register holding first column to insert */
82336   int regRecord;        /* Holds the assemblied row record */
82337   int regEof = 0;       /* Register recording end of SELECT data */
82338   int *aRegIdx = 0;     /* One register allocated to each index */
82339
82340 #ifndef SQLITE_OMIT_TRIGGER
82341   int isView;                 /* True if attempting to insert into a view */
82342   Trigger *pTrigger;          /* List of triggers on pTab, if required */
82343   int tmask;                  /* Mask of trigger times */
82344 #endif
82345
82346   db = pParse->db;
82347   memset(&dest, 0, sizeof(dest));
82348   if( pParse->nErr || db->mallocFailed ){
82349     goto insert_cleanup;
82350   }
82351
82352   /* Locate the table into which we will be inserting new information.
82353   */
82354   assert( pTabList->nSrc==1 );
82355   zTab = pTabList->a[0].zName;
82356   if( NEVER(zTab==0) ) goto insert_cleanup;
82357   pTab = sqlite3SrcListLookup(pParse, pTabList);
82358   if( pTab==0 ){
82359     goto insert_cleanup;
82360   }
82361   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
82362   assert( iDb<db->nDb );
82363   pDb = &db->aDb[iDb];
82364   zDb = pDb->zName;
82365   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
82366     goto insert_cleanup;
82367   }
82368
82369   /* Figure out if we have any triggers and if the table being
82370   ** inserted into is a view
82371   */
82372 #ifndef SQLITE_OMIT_TRIGGER
82373   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
82374   isView = pTab->pSelect!=0;
82375 #else
82376 # define pTrigger 0
82377 # define tmask 0
82378 # define isView 0
82379 #endif
82380 #ifdef SQLITE_OMIT_VIEW
82381 # undef isView
82382 # define isView 0
82383 #endif
82384   assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
82385
82386   /* If pTab is really a view, make sure it has been initialized.
82387   ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual 
82388   ** module table).
82389   */
82390   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
82391     goto insert_cleanup;
82392   }
82393
82394   /* Ensure that:
82395   *  (a) the table is not read-only, 
82396   *  (b) that if it is a view then ON INSERT triggers exist
82397   */
82398   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
82399     goto insert_cleanup;
82400   }
82401
82402   /* Allocate a VDBE
82403   */
82404   v = sqlite3GetVdbe(pParse);
82405   if( v==0 ) goto insert_cleanup;
82406   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
82407   sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
82408
82409 #ifndef SQLITE_OMIT_XFER_OPT
82410   /* If the statement is of the form
82411   **
82412   **       INSERT INTO <table1> SELECT * FROM <table2>;
82413   **
82414   ** Then special optimizations can be applied that make the transfer
82415   ** very fast and which reduce fragmentation of indices.
82416   **
82417   ** This is the 2nd template.
82418   */
82419   if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
82420     assert( !pTrigger );
82421     assert( pList==0 );
82422     goto insert_end;
82423   }
82424 #endif /* SQLITE_OMIT_XFER_OPT */
82425
82426   /* If this is an AUTOINCREMENT table, look up the sequence number in the
82427   ** sqlite_sequence table and store it in memory cell regAutoinc.
82428   */
82429   regAutoinc = autoIncBegin(pParse, iDb, pTab);
82430
82431   /* Figure out how many columns of data are supplied.  If the data
82432   ** is coming from a SELECT statement, then generate a co-routine that
82433   ** produces a single row of the SELECT on each invocation.  The
82434   ** co-routine is the common header to the 3rd and 4th templates.
82435   */
82436   if( pSelect ){
82437     /* Data is coming from a SELECT.  Generate code to implement that SELECT
82438     ** as a co-routine.  The code is common to both the 3rd and 4th
82439     ** templates:
82440     **
82441     **         EOF <- 0
82442     **         X <- A
82443     **         goto B
82444     **      A: setup for the SELECT
82445     **         loop over the tables in the SELECT
82446     **           load value into register R..R+n
82447     **           yield X
82448     **         end loop
82449     **         cleanup after the SELECT
82450     **         EOF <- 1
82451     **         yield X
82452     **         halt-error
82453     **
82454     ** On each invocation of the co-routine, it puts a single row of the
82455     ** SELECT result into registers dest.iMem...dest.iMem+dest.nMem-1.
82456     ** (These output registers are allocated by sqlite3Select().)  When
82457     ** the SELECT completes, it sets the EOF flag stored in regEof.
82458     */
82459     int rc, j1;
82460
82461     regEof = ++pParse->nMem;
82462     sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof);      /* EOF <- 0 */
82463     VdbeComment((v, "SELECT eof flag"));
82464     sqlite3SelectDestInit(&dest, SRT_Coroutine, ++pParse->nMem);
82465     addrSelect = sqlite3VdbeCurrentAddr(v)+2;
82466     sqlite3VdbeAddOp2(v, OP_Integer, addrSelect-1, dest.iParm);
82467     j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
82468     VdbeComment((v, "Jump over SELECT coroutine"));
82469
82470     /* Resolve the expressions in the SELECT statement and execute it. */
82471     rc = sqlite3Select(pParse, pSelect, &dest);
82472     assert( pParse->nErr==0 || rc );
82473     if( rc || NEVER(pParse->nErr) || db->mallocFailed ){
82474       goto insert_cleanup;
82475     }
82476     sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof);         /* EOF <- 1 */
82477     sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);   /* yield X */
82478     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
82479     VdbeComment((v, "End of SELECT coroutine"));
82480     sqlite3VdbeJumpHere(v, j1);                          /* label B: */
82481
82482     regFromSelect = dest.iMem;
82483     assert( pSelect->pEList );
82484     nColumn = pSelect->pEList->nExpr;
82485     assert( dest.nMem==nColumn );
82486
82487     /* Set useTempTable to TRUE if the result of the SELECT statement
82488     ** should be written into a temporary table (template 4).  Set to
82489     ** FALSE if each* row of the SELECT can be written directly into
82490     ** the destination table (template 3).
82491     **
82492     ** A temp table must be used if the table being updated is also one
82493     ** of the tables being read by the SELECT statement.  Also use a 
82494     ** temp table in the case of row triggers.
82495     */
82496     if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){
82497       useTempTable = 1;
82498     }
82499
82500     if( useTempTable ){
82501       /* Invoke the coroutine to extract information from the SELECT
82502       ** and add it to a transient table srcTab.  The code generated
82503       ** here is from the 4th template:
82504       **
82505       **      B: open temp table
82506       **      L: yield X
82507       **         if EOF goto M
82508       **         insert row from R..R+n into temp table
82509       **         goto L
82510       **      M: ...
82511       */
82512       int regRec;          /* Register to hold packed record */
82513       int regTempRowid;    /* Register to hold temp table ROWID */
82514       int addrTop;         /* Label "L" */
82515       int addrIf;          /* Address of jump to M */
82516
82517       srcTab = pParse->nTab++;
82518       regRec = sqlite3GetTempReg(pParse);
82519       regTempRowid = sqlite3GetTempReg(pParse);
82520       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
82521       addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
82522       addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
82523       sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
82524       sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
82525       sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
82526       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
82527       sqlite3VdbeJumpHere(v, addrIf);
82528       sqlite3ReleaseTempReg(pParse, regRec);
82529       sqlite3ReleaseTempReg(pParse, regTempRowid);
82530     }
82531   }else{
82532     /* This is the case if the data for the INSERT is coming from a VALUES
82533     ** clause
82534     */
82535     NameContext sNC;
82536     memset(&sNC, 0, sizeof(sNC));
82537     sNC.pParse = pParse;
82538     srcTab = -1;
82539     assert( useTempTable==0 );
82540     nColumn = pList ? pList->nExpr : 0;
82541     for(i=0; i<nColumn; i++){
82542       if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
82543         goto insert_cleanup;
82544       }
82545     }
82546   }
82547
82548   /* Make sure the number of columns in the source data matches the number
82549   ** of columns to be inserted into the table.
82550   */
82551   if( IsVirtual(pTab) ){
82552     for(i=0; i<pTab->nCol; i++){
82553       nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
82554     }
82555   }
82556   if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
82557     sqlite3ErrorMsg(pParse, 
82558        "table %S has %d columns but %d values were supplied",
82559        pTabList, 0, pTab->nCol-nHidden, nColumn);
82560     goto insert_cleanup;
82561   }
82562   if( pColumn!=0 && nColumn!=pColumn->nId ){
82563     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
82564     goto insert_cleanup;
82565   }
82566
82567   /* If the INSERT statement included an IDLIST term, then make sure
82568   ** all elements of the IDLIST really are columns of the table and 
82569   ** remember the column indices.
82570   **
82571   ** If the table has an INTEGER PRIMARY KEY column and that column
82572   ** is named in the IDLIST, then record in the keyColumn variable
82573   ** the index into IDLIST of the primary key column.  keyColumn is
82574   ** the index of the primary key as it appears in IDLIST, not as
82575   ** is appears in the original table.  (The index of the primary
82576   ** key in the original table is pTab->iPKey.)
82577   */
82578   if( pColumn ){
82579     for(i=0; i<pColumn->nId; i++){
82580       pColumn->a[i].idx = -1;
82581     }
82582     for(i=0; i<pColumn->nId; i++){
82583       for(j=0; j<pTab->nCol; j++){
82584         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
82585           pColumn->a[i].idx = j;
82586           if( j==pTab->iPKey ){
82587             keyColumn = i;
82588           }
82589           break;
82590         }
82591       }
82592       if( j>=pTab->nCol ){
82593         if( sqlite3IsRowid(pColumn->a[i].zName) ){
82594           keyColumn = i;
82595         }else{
82596           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
82597               pTabList, 0, pColumn->a[i].zName);
82598           pParse->checkSchema = 1;
82599           goto insert_cleanup;
82600         }
82601       }
82602     }
82603   }
82604
82605   /* If there is no IDLIST term but the table has an integer primary
82606   ** key, the set the keyColumn variable to the primary key column index
82607   ** in the original table definition.
82608   */
82609   if( pColumn==0 && nColumn>0 ){
82610     keyColumn = pTab->iPKey;
82611   }
82612     
82613   /* Initialize the count of rows to be inserted
82614   */
82615   if( db->flags & SQLITE_CountRows ){
82616     regRowCount = ++pParse->nMem;
82617     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
82618   }
82619
82620   /* If this is not a view, open the table and and all indices */
82621   if( !isView ){
82622     int nIdx;
82623
82624     baseCur = pParse->nTab;
82625     nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
82626     aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
82627     if( aRegIdx==0 ){
82628       goto insert_cleanup;
82629     }
82630     for(i=0; i<nIdx; i++){
82631       aRegIdx[i] = ++pParse->nMem;
82632     }
82633   }
82634
82635   /* This is the top of the main insertion loop */
82636   if( useTempTable ){
82637     /* This block codes the top of loop only.  The complete loop is the
82638     ** following pseudocode (template 4):
82639     **
82640     **         rewind temp table
82641     **      C: loop over rows of intermediate table
82642     **           transfer values form intermediate table into <table>
82643     **         end loop
82644     **      D: ...
82645     */
82646     addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
82647     addrCont = sqlite3VdbeCurrentAddr(v);
82648   }else if( pSelect ){
82649     /* This block codes the top of loop only.  The complete loop is the
82650     ** following pseudocode (template 3):
82651     **
82652     **      C: yield X
82653     **         if EOF goto D
82654     **         insert the select result into <table> from R..R+n
82655     **         goto C
82656     **      D: ...
82657     */
82658     addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
82659     addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
82660   }
82661
82662   /* Allocate registers for holding the rowid of the new row,
82663   ** the content of the new row, and the assemblied row record.
82664   */
82665   regRecord = ++pParse->nMem;
82666   regRowid = regIns = pParse->nMem+1;
82667   pParse->nMem += pTab->nCol + 1;
82668   if( IsVirtual(pTab) ){
82669     regRowid++;
82670     pParse->nMem++;
82671   }
82672   regData = regRowid+1;
82673
82674   /* Run the BEFORE and INSTEAD OF triggers, if there are any
82675   */
82676   endOfLoop = sqlite3VdbeMakeLabel(v);
82677   if( tmask & TRIGGER_BEFORE ){
82678     int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
82679
82680     /* build the NEW.* reference row.  Note that if there is an INTEGER
82681     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
82682     ** translated into a unique ID for the row.  But on a BEFORE trigger,
82683     ** we do not know what the unique ID will be (because the insert has
82684     ** not happened yet) so we substitute a rowid of -1
82685     */
82686     if( keyColumn<0 ){
82687       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
82688     }else{
82689       int j1;
82690       if( useTempTable ){
82691         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regCols);
82692       }else{
82693         assert( pSelect==0 );  /* Otherwise useTempTable is true */
82694         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regCols);
82695       }
82696       j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols);
82697       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
82698       sqlite3VdbeJumpHere(v, j1);
82699       sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols);
82700     }
82701
82702     /* Cannot have triggers on a virtual table. If it were possible,
82703     ** this block would have to account for hidden column.
82704     */
82705     assert( !IsVirtual(pTab) );
82706
82707     /* Create the new column data
82708     */
82709     for(i=0; i<pTab->nCol; i++){
82710       if( pColumn==0 ){
82711         j = i;
82712       }else{
82713         for(j=0; j<pColumn->nId; j++){
82714           if( pColumn->a[j].idx==i ) break;
82715         }
82716       }
82717       if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
82718         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
82719       }else if( useTempTable ){
82720         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1); 
82721       }else{
82722         assert( pSelect==0 ); /* Otherwise useTempTable is true */
82723         sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
82724       }
82725     }
82726
82727     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
82728     ** do not attempt any conversions before assembling the record.
82729     ** If this is a real table, attempt conversions as required by the
82730     ** table column affinities.
82731     */
82732     if( !isView ){
82733       sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol);
82734       sqlite3TableAffinityStr(v, pTab);
82735     }
82736
82737     /* Fire BEFORE or INSTEAD OF triggers */
82738     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE, 
82739         pTab, regCols-pTab->nCol-1, onError, endOfLoop);
82740
82741     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
82742   }
82743
82744   /* Push the record number for the new entry onto the stack.  The
82745   ** record number is a randomly generate integer created by NewRowid
82746   ** except when the table has an INTEGER PRIMARY KEY column, in which
82747   ** case the record number is the same as that column. 
82748   */
82749   if( !isView ){
82750     if( IsVirtual(pTab) ){
82751       /* The row that the VUpdate opcode will delete: none */
82752       sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
82753     }
82754     if( keyColumn>=0 ){
82755       if( useTempTable ){
82756         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
82757       }else if( pSelect ){
82758         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
82759       }else{
82760         VdbeOp *pOp;
82761         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
82762         pOp = sqlite3VdbeGetOp(v, -1);
82763         if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
82764           appendFlag = 1;
82765           pOp->opcode = OP_NewRowid;
82766           pOp->p1 = baseCur;
82767           pOp->p2 = regRowid;
82768           pOp->p3 = regAutoinc;
82769         }
82770       }
82771       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
82772       ** to generate a unique primary key value.
82773       */
82774       if( !appendFlag ){
82775         int j1;
82776         if( !IsVirtual(pTab) ){
82777           j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
82778           sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
82779           sqlite3VdbeJumpHere(v, j1);
82780         }else{
82781           j1 = sqlite3VdbeCurrentAddr(v);
82782           sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
82783         }
82784         sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
82785       }
82786     }else if( IsVirtual(pTab) ){
82787       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
82788     }else{
82789       sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
82790       appendFlag = 1;
82791     }
82792     autoIncStep(pParse, regAutoinc, regRowid);
82793
82794     /* Push onto the stack, data for all columns of the new entry, beginning
82795     ** with the first column.
82796     */
82797     nHidden = 0;
82798     for(i=0; i<pTab->nCol; i++){
82799       int iRegStore = regRowid+1+i;
82800       if( i==pTab->iPKey ){
82801         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
82802         ** Whenever this column is read, the record number will be substituted
82803         ** in its place.  So will fill this column with a NULL to avoid
82804         ** taking up data space with information that will never be used. */
82805         sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
82806         continue;
82807       }
82808       if( pColumn==0 ){
82809         if( IsHiddenColumn(&pTab->aCol[i]) ){
82810           assert( IsVirtual(pTab) );
82811           j = -1;
82812           nHidden++;
82813         }else{
82814           j = i - nHidden;
82815         }
82816       }else{
82817         for(j=0; j<pColumn->nId; j++){
82818           if( pColumn->a[j].idx==i ) break;
82819         }
82820       }
82821       if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
82822         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
82823       }else if( useTempTable ){
82824         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore); 
82825       }else if( pSelect ){
82826         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
82827       }else{
82828         sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
82829       }
82830     }
82831
82832     /* Generate code to check constraints and generate index keys and
82833     ** do the insertion.
82834     */
82835 #ifndef SQLITE_OMIT_VIRTUALTABLE
82836     if( IsVirtual(pTab) ){
82837       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
82838       sqlite3VtabMakeWritable(pParse, pTab);
82839       sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
82840       sqlite3MayAbort(pParse);
82841     }else
82842 #endif
82843     {
82844       int isReplace;    /* Set to true if constraints may cause a replace */
82845       sqlite3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx,
82846           keyColumn>=0, 0, onError, endOfLoop, &isReplace
82847       );
82848       sqlite3FkCheck(pParse, pTab, 0, regIns);
82849       sqlite3CompleteInsertion(
82850           pParse, pTab, baseCur, regIns, aRegIdx, 0, appendFlag, isReplace==0
82851       );
82852     }
82853   }
82854
82855   /* Update the count of rows that are inserted
82856   */
82857   if( (db->flags & SQLITE_CountRows)!=0 ){
82858     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
82859   }
82860
82861   if( pTrigger ){
82862     /* Code AFTER triggers */
82863     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER, 
82864         pTab, regData-2-pTab->nCol, onError, endOfLoop);
82865   }
82866
82867   /* The bottom of the main insertion loop, if the data source
82868   ** is a SELECT statement.
82869   */
82870   sqlite3VdbeResolveLabel(v, endOfLoop);
82871   if( useTempTable ){
82872     sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
82873     sqlite3VdbeJumpHere(v, addrInsTop);
82874     sqlite3VdbeAddOp1(v, OP_Close, srcTab);
82875   }else if( pSelect ){
82876     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
82877     sqlite3VdbeJumpHere(v, addrInsTop);
82878   }
82879
82880   if( !IsVirtual(pTab) && !isView ){
82881     /* Close all tables opened */
82882     sqlite3VdbeAddOp1(v, OP_Close, baseCur);
82883     for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
82884       sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
82885     }
82886   }
82887
82888 insert_end:
82889   /* Update the sqlite_sequence table by storing the content of the
82890   ** maximum rowid counter values recorded while inserting into
82891   ** autoincrement tables.
82892   */
82893   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
82894     sqlite3AutoincrementEnd(pParse);
82895   }
82896
82897   /*
82898   ** Return the number of rows inserted. If this routine is 
82899   ** generating code because of a call to sqlite3NestedParse(), do not
82900   ** invoke the callback function.
82901   */
82902   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
82903     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
82904     sqlite3VdbeSetNumCols(v, 1);
82905     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
82906   }
82907
82908 insert_cleanup:
82909   sqlite3SrcListDelete(db, pTabList);
82910   sqlite3ExprListDelete(db, pList);
82911   sqlite3SelectDelete(db, pSelect);
82912   sqlite3IdListDelete(db, pColumn);
82913   sqlite3DbFree(db, aRegIdx);
82914 }
82915
82916 /* Make sure "isView" and other macros defined above are undefined. Otherwise
82917 ** thely may interfere with compilation of other functions in this file
82918 ** (or in another file, if this file becomes part of the amalgamation).  */
82919 #ifdef isView
82920  #undef isView
82921 #endif
82922 #ifdef pTrigger
82923  #undef pTrigger
82924 #endif
82925 #ifdef tmask
82926  #undef tmask
82927 #endif
82928
82929
82930 /*
82931 ** Generate code to do constraint checks prior to an INSERT or an UPDATE.
82932 **
82933 ** The input is a range of consecutive registers as follows:
82934 **
82935 **    1.  The rowid of the row after the update.
82936 **
82937 **    2.  The data in the first column of the entry after the update.
82938 **
82939 **    i.  Data from middle columns...
82940 **
82941 **    N.  The data in the last column of the entry after the update.
82942 **
82943 ** The regRowid parameter is the index of the register containing (1).
82944 **
82945 ** If isUpdate is true and rowidChng is non-zero, then rowidChng contains
82946 ** the address of a register containing the rowid before the update takes
82947 ** place. isUpdate is true for UPDATEs and false for INSERTs. If isUpdate
82948 ** is false, indicating an INSERT statement, then a non-zero rowidChng 
82949 ** indicates that the rowid was explicitly specified as part of the
82950 ** INSERT statement. If rowidChng is false, it means that  the rowid is
82951 ** computed automatically in an insert or that the rowid value is not 
82952 ** modified by an update.
82953 **
82954 ** The code generated by this routine store new index entries into
82955 ** registers identified by aRegIdx[].  No index entry is created for
82956 ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
82957 ** the same as the order of indices on the linked list of indices
82958 ** attached to the table.
82959 **
82960 ** This routine also generates code to check constraints.  NOT NULL,
82961 ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
82962 ** then the appropriate action is performed.  There are five possible
82963 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
82964 **
82965 **  Constraint type  Action       What Happens
82966 **  ---------------  ----------   ----------------------------------------
82967 **  any              ROLLBACK     The current transaction is rolled back and
82968 **                                sqlite3_exec() returns immediately with a
82969 **                                return code of SQLITE_CONSTRAINT.
82970 **
82971 **  any              ABORT        Back out changes from the current command
82972 **                                only (do not do a complete rollback) then
82973 **                                cause sqlite3_exec() to return immediately
82974 **                                with SQLITE_CONSTRAINT.
82975 **
82976 **  any              FAIL         Sqlite_exec() returns immediately with a
82977 **                                return code of SQLITE_CONSTRAINT.  The
82978 **                                transaction is not rolled back and any
82979 **                                prior changes are retained.
82980 **
82981 **  any              IGNORE       The record number and data is popped from
82982 **                                the stack and there is an immediate jump
82983 **                                to label ignoreDest.
82984 **
82985 **  NOT NULL         REPLACE      The NULL value is replace by the default
82986 **                                value for that column.  If the default value
82987 **                                is NULL, the action is the same as ABORT.
82988 **
82989 **  UNIQUE           REPLACE      The other row that conflicts with the row
82990 **                                being inserted is removed.
82991 **
82992 **  CHECK            REPLACE      Illegal.  The results in an exception.
82993 **
82994 ** Which action to take is determined by the overrideError parameter.
82995 ** Or if overrideError==OE_Default, then the pParse->onError parameter
82996 ** is used.  Or if pParse->onError==OE_Default then the onError value
82997 ** for the constraint is used.
82998 **
82999 ** The calling routine must open a read/write cursor for pTab with
83000 ** cursor number "baseCur".  All indices of pTab must also have open
83001 ** read/write cursors with cursor number baseCur+i for the i-th cursor.
83002 ** Except, if there is no possibility of a REPLACE action then
83003 ** cursors do not need to be open for indices where aRegIdx[i]==0.
83004 */
83005 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
83006   Parse *pParse,      /* The parser context */
83007   Table *pTab,        /* the table into which we are inserting */
83008   int baseCur,        /* Index of a read/write cursor pointing at pTab */
83009   int regRowid,       /* Index of the range of input registers */
83010   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
83011   int rowidChng,      /* True if the rowid might collide with existing entry */
83012   int isUpdate,       /* True for UPDATE, False for INSERT */
83013   int overrideError,  /* Override onError to this if not OE_Default */
83014   int ignoreDest,     /* Jump to this label on an OE_Ignore resolution */
83015   int *pbMayReplace   /* OUT: Set to true if constraint may cause a replace */
83016 ){
83017   int i;              /* loop counter */
83018   Vdbe *v;            /* VDBE under constrution */
83019   int nCol;           /* Number of columns */
83020   int onError;        /* Conflict resolution strategy */
83021   int j1;             /* Addresss of jump instruction */
83022   int j2 = 0, j3;     /* Addresses of jump instructions */
83023   int regData;        /* Register containing first data column */
83024   int iCur;           /* Table cursor number */
83025   Index *pIdx;         /* Pointer to one of the indices */
83026   int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
83027   int regOldRowid = (rowidChng && isUpdate) ? rowidChng : regRowid;
83028
83029   v = sqlite3GetVdbe(pParse);
83030   assert( v!=0 );
83031   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
83032   nCol = pTab->nCol;
83033   regData = regRowid + 1;
83034
83035   /* Test all NOT NULL constraints.
83036   */
83037   for(i=0; i<nCol; i++){
83038     if( i==pTab->iPKey ){
83039       continue;
83040     }
83041     onError = pTab->aCol[i].notNull;
83042     if( onError==OE_None ) continue;
83043     if( overrideError!=OE_Default ){
83044       onError = overrideError;
83045     }else if( onError==OE_Default ){
83046       onError = OE_Abort;
83047     }
83048     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
83049       onError = OE_Abort;
83050     }
83051     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
83052         || onError==OE_Ignore || onError==OE_Replace );
83053     switch( onError ){
83054       case OE_Abort:
83055         sqlite3MayAbort(pParse);
83056       case OE_Rollback:
83057       case OE_Fail: {
83058         char *zMsg;
83059         j1 = sqlite3VdbeAddOp3(v, OP_HaltIfNull,
83060                                   SQLITE_CONSTRAINT, onError, regData+i);
83061         zMsg = sqlite3MPrintf(pParse->db, "%s.%s may not be NULL",
83062                               pTab->zName, pTab->aCol[i].zName);
83063         sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
83064         break;
83065       }
83066       case OE_Ignore: {
83067         sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
83068         break;
83069       }
83070       default: {
83071         assert( onError==OE_Replace );
83072         j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
83073         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
83074         sqlite3VdbeJumpHere(v, j1);
83075         break;
83076       }
83077     }
83078   }
83079
83080   /* Test all CHECK constraints
83081   */
83082 #ifndef SQLITE_OMIT_CHECK
83083   if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
83084     int allOk = sqlite3VdbeMakeLabel(v);
83085     pParse->ckBase = regData;
83086     sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, SQLITE_JUMPIFNULL);
83087     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
83088     if( onError==OE_Ignore ){
83089       sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
83090     }else{
83091       if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
83092       sqlite3HaltConstraint(pParse, onError, 0, 0);
83093     }
83094     sqlite3VdbeResolveLabel(v, allOk);
83095   }
83096 #endif /* !defined(SQLITE_OMIT_CHECK) */
83097
83098   /* If we have an INTEGER PRIMARY KEY, make sure the primary key
83099   ** of the new record does not previously exist.  Except, if this
83100   ** is an UPDATE and the primary key is not changing, that is OK.
83101   */
83102   if( rowidChng ){
83103     onError = pTab->keyConf;
83104     if( overrideError!=OE_Default ){
83105       onError = overrideError;
83106     }else if( onError==OE_Default ){
83107       onError = OE_Abort;
83108     }
83109     
83110     if( isUpdate ){
83111       j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, rowidChng);
83112     }
83113     j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
83114     switch( onError ){
83115       default: {
83116         onError = OE_Abort;
83117         /* Fall thru into the next case */
83118       }
83119       case OE_Rollback:
83120       case OE_Abort:
83121       case OE_Fail: {
83122         sqlite3HaltConstraint(
83123           pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
83124         break;
83125       }
83126       case OE_Replace: {
83127         /* If there are DELETE triggers on this table and the
83128         ** recursive-triggers flag is set, call GenerateRowDelete() to
83129         ** remove the conflicting row from the the table. This will fire
83130         ** the triggers and remove both the table and index b-tree entries.
83131         **
83132         ** Otherwise, if there are no triggers or the recursive-triggers
83133         ** flag is not set, but the table has one or more indexes, call 
83134         ** GenerateRowIndexDelete(). This removes the index b-tree entries 
83135         ** only. The table b-tree entry will be replaced by the new entry 
83136         ** when it is inserted.  
83137         **
83138         ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
83139         ** also invoke MultiWrite() to indicate that this VDBE may require
83140         ** statement rollback (if the statement is aborted after the delete
83141         ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
83142         ** but being more selective here allows statements like:
83143         **
83144         **   REPLACE INTO t(rowid) VALUES($newrowid)
83145         **
83146         ** to run without a statement journal if there are no indexes on the
83147         ** table.
83148         */
83149         Trigger *pTrigger = 0;
83150         if( pParse->db->flags&SQLITE_RecTriggers ){
83151           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
83152         }
83153         if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
83154           sqlite3MultiWrite(pParse);
83155           sqlite3GenerateRowDelete(
83156               pParse, pTab, baseCur, regRowid, 0, pTrigger, OE_Replace
83157           );
83158         }else if( pTab->pIndex ){
83159           sqlite3MultiWrite(pParse);
83160           sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
83161         }
83162         seenReplace = 1;
83163         break;
83164       }
83165       case OE_Ignore: {
83166         assert( seenReplace==0 );
83167         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
83168         break;
83169       }
83170     }
83171     sqlite3VdbeJumpHere(v, j3);
83172     if( isUpdate ){
83173       sqlite3VdbeJumpHere(v, j2);
83174     }
83175   }
83176
83177   /* Test all UNIQUE constraints by creating entries for each UNIQUE
83178   ** index and making sure that duplicate entries do not already exist.
83179   ** Add the new records to the indices as we go.
83180   */
83181   for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
83182     int regIdx;
83183     int regR;
83184
83185     if( aRegIdx[iCur]==0 ) continue;  /* Skip unused indices */
83186
83187     /* Create a key for accessing the index entry */
83188     regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
83189     for(i=0; i<pIdx->nColumn; i++){
83190       int idx = pIdx->aiColumn[i];
83191       if( idx==pTab->iPKey ){
83192         sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
83193       }else{
83194         sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
83195       }
83196     }
83197     sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
83198     sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
83199     sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), 0);
83200     sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
83201
83202     /* Find out what action to take in case there is an indexing conflict */
83203     onError = pIdx->onError;
83204     if( onError==OE_None ){ 
83205       sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
83206       continue;  /* pIdx is not a UNIQUE index */
83207     }
83208     if( overrideError!=OE_Default ){
83209       onError = overrideError;
83210     }else if( onError==OE_Default ){
83211       onError = OE_Abort;
83212     }
83213     if( seenReplace ){
83214       if( onError==OE_Ignore ) onError = OE_Replace;
83215       else if( onError==OE_Fail ) onError = OE_Abort;
83216     }
83217     
83218     /* Check to see if the new index entry will be unique */
83219     regR = sqlite3GetTempReg(pParse);
83220     sqlite3VdbeAddOp2(v, OP_SCopy, regOldRowid, regR);
83221     j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
83222                            regR, SQLITE_INT_TO_PTR(regIdx),
83223                            P4_INT32);
83224     sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
83225
83226     /* Generate code that executes if the new index entry is not unique */
83227     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
83228         || onError==OE_Ignore || onError==OE_Replace );
83229     switch( onError ){
83230       case OE_Rollback:
83231       case OE_Abort:
83232       case OE_Fail: {
83233         int j;
83234         StrAccum errMsg;
83235         const char *zSep;
83236         char *zErr;
83237
83238         sqlite3StrAccumInit(&errMsg, 0, 0, 200);
83239         errMsg.db = pParse->db;
83240         zSep = pIdx->nColumn>1 ? "columns " : "column ";
83241         for(j=0; j<pIdx->nColumn; j++){
83242           char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
83243           sqlite3StrAccumAppend(&errMsg, zSep, -1);
83244           zSep = ", ";
83245           sqlite3StrAccumAppend(&errMsg, zCol, -1);
83246         }
83247         sqlite3StrAccumAppend(&errMsg,
83248             pIdx->nColumn>1 ? " are not unique" : " is not unique", -1);
83249         zErr = sqlite3StrAccumFinish(&errMsg);
83250         sqlite3HaltConstraint(pParse, onError, zErr, 0);
83251         sqlite3DbFree(errMsg.db, zErr);
83252         break;
83253       }
83254       case OE_Ignore: {
83255         assert( seenReplace==0 );
83256         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
83257         break;
83258       }
83259       default: {
83260         Trigger *pTrigger = 0;
83261         assert( onError==OE_Replace );
83262         sqlite3MultiWrite(pParse);
83263         if( pParse->db->flags&SQLITE_RecTriggers ){
83264           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
83265         }
83266         sqlite3GenerateRowDelete(
83267             pParse, pTab, baseCur, regR, 0, pTrigger, OE_Replace
83268         );
83269         seenReplace = 1;
83270         break;
83271       }
83272     }
83273     sqlite3VdbeJumpHere(v, j3);
83274     sqlite3ReleaseTempReg(pParse, regR);
83275   }
83276   
83277   if( pbMayReplace ){
83278     *pbMayReplace = seenReplace;
83279   }
83280 }
83281
83282 /*
83283 ** This routine generates code to finish the INSERT or UPDATE operation
83284 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
83285 ** A consecutive range of registers starting at regRowid contains the
83286 ** rowid and the content to be inserted.
83287 **
83288 ** The arguments to this routine should be the same as the first six
83289 ** arguments to sqlite3GenerateConstraintChecks.
83290 */
83291 SQLITE_PRIVATE void sqlite3CompleteInsertion(
83292   Parse *pParse,      /* The parser context */
83293   Table *pTab,        /* the table into which we are inserting */
83294   int baseCur,        /* Index of a read/write cursor pointing at pTab */
83295   int regRowid,       /* Range of content */
83296   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
83297   int isUpdate,       /* True for UPDATE, False for INSERT */
83298   int appendBias,     /* True if this is likely to be an append */
83299   int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
83300 ){
83301   int i;
83302   Vdbe *v;
83303   int nIdx;
83304   Index *pIdx;
83305   u8 pik_flags;
83306   int regData;
83307   int regRec;
83308
83309   v = sqlite3GetVdbe(pParse);
83310   assert( v!=0 );
83311   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
83312   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
83313   for(i=nIdx-1; i>=0; i--){
83314     if( aRegIdx[i]==0 ) continue;
83315     sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
83316     if( useSeekResult ){
83317       sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
83318     }
83319   }
83320   regData = regRowid + 1;
83321   regRec = sqlite3GetTempReg(pParse);
83322   sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
83323   sqlite3TableAffinityStr(v, pTab);
83324   sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
83325   if( pParse->nested ){
83326     pik_flags = 0;
83327   }else{
83328     pik_flags = OPFLAG_NCHANGE;
83329     pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
83330   }
83331   if( appendBias ){
83332     pik_flags |= OPFLAG_APPEND;
83333   }
83334   if( useSeekResult ){
83335     pik_flags |= OPFLAG_USESEEKRESULT;
83336   }
83337   sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
83338   if( !pParse->nested ){
83339     sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
83340   }
83341   sqlite3VdbeChangeP5(v, pik_flags);
83342 }
83343
83344 /*
83345 ** Generate code that will open cursors for a table and for all
83346 ** indices of that table.  The "baseCur" parameter is the cursor number used
83347 ** for the table.  Indices are opened on subsequent cursors.
83348 **
83349 ** Return the number of indices on the table.
83350 */
83351 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
83352   Parse *pParse,   /* Parsing context */
83353   Table *pTab,     /* Table to be opened */
83354   int baseCur,     /* Cursor number assigned to the table */
83355   int op           /* OP_OpenRead or OP_OpenWrite */
83356 ){
83357   int i;
83358   int iDb;
83359   Index *pIdx;
83360   Vdbe *v;
83361
83362   if( IsVirtual(pTab) ) return 0;
83363   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
83364   v = sqlite3GetVdbe(pParse);
83365   assert( v!=0 );
83366   sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
83367   for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
83368     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
83369     assert( pIdx->pSchema==pTab->pSchema );
83370     sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
83371                       (char*)pKey, P4_KEYINFO_HANDOFF);
83372     VdbeComment((v, "%s", pIdx->zName));
83373   }
83374   if( pParse->nTab<baseCur+i ){
83375     pParse->nTab = baseCur+i;
83376   }
83377   return i-1;
83378 }
83379
83380
83381 #ifdef SQLITE_TEST
83382 /*
83383 ** The following global variable is incremented whenever the
83384 ** transfer optimization is used.  This is used for testing
83385 ** purposes only - to make sure the transfer optimization really
83386 ** is happening when it is suppose to.
83387 */
83388 SQLITE_API int sqlite3_xferopt_count;
83389 #endif /* SQLITE_TEST */
83390
83391
83392 #ifndef SQLITE_OMIT_XFER_OPT
83393 /*
83394 ** Check to collation names to see if they are compatible.
83395 */
83396 static int xferCompatibleCollation(const char *z1, const char *z2){
83397   if( z1==0 ){
83398     return z2==0;
83399   }
83400   if( z2==0 ){
83401     return 0;
83402   }
83403   return sqlite3StrICmp(z1, z2)==0;
83404 }
83405
83406
83407 /*
83408 ** Check to see if index pSrc is compatible as a source of data
83409 ** for index pDest in an insert transfer optimization.  The rules
83410 ** for a compatible index:
83411 **
83412 **    *   The index is over the same set of columns
83413 **    *   The same DESC and ASC markings occurs on all columns
83414 **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
83415 **    *   The same collating sequence on each column
83416 */
83417 static int xferCompatibleIndex(Index *pDest, Index *pSrc){
83418   int i;
83419   assert( pDest && pSrc );
83420   assert( pDest->pTable!=pSrc->pTable );
83421   if( pDest->nColumn!=pSrc->nColumn ){
83422     return 0;   /* Different number of columns */
83423   }
83424   if( pDest->onError!=pSrc->onError ){
83425     return 0;   /* Different conflict resolution strategies */
83426   }
83427   for(i=0; i<pSrc->nColumn; i++){
83428     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
83429       return 0;   /* Different columns indexed */
83430     }
83431     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
83432       return 0;   /* Different sort orders */
83433     }
83434     if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
83435       return 0;   /* Different collating sequences */
83436     }
83437   }
83438
83439   /* If no test above fails then the indices must be compatible */
83440   return 1;
83441 }
83442
83443 /*
83444 ** Attempt the transfer optimization on INSERTs of the form
83445 **
83446 **     INSERT INTO tab1 SELECT * FROM tab2;
83447 **
83448 ** This optimization is only attempted if
83449 **
83450 **    (1)  tab1 and tab2 have identical schemas including all the
83451 **         same indices and constraints
83452 **
83453 **    (2)  tab1 and tab2 are different tables
83454 **
83455 **    (3)  There must be no triggers on tab1
83456 **
83457 **    (4)  The result set of the SELECT statement is "*"
83458 **
83459 **    (5)  The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
83460 **         or LIMIT clause.
83461 **
83462 **    (6)  The SELECT statement is a simple (not a compound) select that
83463 **         contains only tab2 in its FROM clause
83464 **
83465 ** This method for implementing the INSERT transfers raw records from
83466 ** tab2 over to tab1.  The columns are not decoded.  Raw records from
83467 ** the indices of tab2 are transfered to tab1 as well.  In so doing,
83468 ** the resulting tab1 has much less fragmentation.
83469 **
83470 ** This routine returns TRUE if the optimization is attempted.  If any
83471 ** of the conditions above fail so that the optimization should not
83472 ** be attempted, then this routine returns FALSE.
83473 */
83474 static int xferOptimization(
83475   Parse *pParse,        /* Parser context */
83476   Table *pDest,         /* The table we are inserting into */
83477   Select *pSelect,      /* A SELECT statement to use as the data source */
83478   int onError,          /* How to handle constraint errors */
83479   int iDbDest           /* The database of pDest */
83480 ){
83481   ExprList *pEList;                /* The result set of the SELECT */
83482   Table *pSrc;                     /* The table in the FROM clause of SELECT */
83483   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
83484   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
83485   int i;                           /* Loop counter */
83486   int iDbSrc;                      /* The database of pSrc */
83487   int iSrc, iDest;                 /* Cursors from source and destination */
83488   int addr1, addr2;                /* Loop addresses */
83489   int emptyDestTest;               /* Address of test for empty pDest */
83490   int emptySrcTest;                /* Address of test for empty pSrc */
83491   Vdbe *v;                         /* The VDBE we are building */
83492   KeyInfo *pKey;                   /* Key information for an index */
83493   int regAutoinc;                  /* Memory register used by AUTOINC */
83494   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
83495   int regData, regRowid;           /* Registers holding data and rowid */
83496
83497   if( pSelect==0 ){
83498     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
83499   }
83500   if( sqlite3TriggerList(pParse, pDest) ){
83501     return 0;   /* tab1 must not have triggers */
83502   }
83503 #ifndef SQLITE_OMIT_VIRTUALTABLE
83504   if( pDest->tabFlags & TF_Virtual ){
83505     return 0;   /* tab1 must not be a virtual table */
83506   }
83507 #endif
83508   if( onError==OE_Default ){
83509     onError = OE_Abort;
83510   }
83511   if( onError!=OE_Abort && onError!=OE_Rollback ){
83512     return 0;   /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
83513   }
83514   assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
83515   if( pSelect->pSrc->nSrc!=1 ){
83516     return 0;   /* FROM clause must have exactly one term */
83517   }
83518   if( pSelect->pSrc->a[0].pSelect ){
83519     return 0;   /* FROM clause cannot contain a subquery */
83520   }
83521   if( pSelect->pWhere ){
83522     return 0;   /* SELECT may not have a WHERE clause */
83523   }
83524   if( pSelect->pOrderBy ){
83525     return 0;   /* SELECT may not have an ORDER BY clause */
83526   }
83527   /* Do not need to test for a HAVING clause.  If HAVING is present but
83528   ** there is no ORDER BY, we will get an error. */
83529   if( pSelect->pGroupBy ){
83530     return 0;   /* SELECT may not have a GROUP BY clause */
83531   }
83532   if( pSelect->pLimit ){
83533     return 0;   /* SELECT may not have a LIMIT clause */
83534   }
83535   assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
83536   if( pSelect->pPrior ){
83537     return 0;   /* SELECT may not be a compound query */
83538   }
83539   if( pSelect->selFlags & SF_Distinct ){
83540     return 0;   /* SELECT may not be DISTINCT */
83541   }
83542   pEList = pSelect->pEList;
83543   assert( pEList!=0 );
83544   if( pEList->nExpr!=1 ){
83545     return 0;   /* The result set must have exactly one column */
83546   }
83547   assert( pEList->a[0].pExpr );
83548   if( pEList->a[0].pExpr->op!=TK_ALL ){
83549     return 0;   /* The result set must be the special operator "*" */
83550   }
83551
83552   /* At this point we have established that the statement is of the
83553   ** correct syntactic form to participate in this optimization.  Now
83554   ** we have to check the semantics.
83555   */
83556   pItem = pSelect->pSrc->a;
83557   pSrc = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
83558   if( pSrc==0 ){
83559     return 0;   /* FROM clause does not contain a real table */
83560   }
83561   if( pSrc==pDest ){
83562     return 0;   /* tab1 and tab2 may not be the same table */
83563   }
83564 #ifndef SQLITE_OMIT_VIRTUALTABLE
83565   if( pSrc->tabFlags & TF_Virtual ){
83566     return 0;   /* tab2 must not be a virtual table */
83567   }
83568 #endif
83569   if( pSrc->pSelect ){
83570     return 0;   /* tab2 may not be a view */
83571   }
83572   if( pDest->nCol!=pSrc->nCol ){
83573     return 0;   /* Number of columns must be the same in tab1 and tab2 */
83574   }
83575   if( pDest->iPKey!=pSrc->iPKey ){
83576     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
83577   }
83578   for(i=0; i<pDest->nCol; i++){
83579     if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
83580       return 0;    /* Affinity must be the same on all columns */
83581     }
83582     if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
83583       return 0;    /* Collating sequence must be the same on all columns */
83584     }
83585     if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
83586       return 0;    /* tab2 must be NOT NULL if tab1 is */
83587     }
83588   }
83589   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
83590     if( pDestIdx->onError!=OE_None ){
83591       destHasUniqueIdx = 1;
83592     }
83593     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
83594       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
83595     }
83596     if( pSrcIdx==0 ){
83597       return 0;    /* pDestIdx has no corresponding index in pSrc */
83598     }
83599   }
83600 #ifndef SQLITE_OMIT_CHECK
83601   if( pDest->pCheck && sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
83602     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
83603   }
83604 #endif
83605
83606   /* If we get this far, it means either:
83607   **
83608   **    *   We can always do the transfer if the table contains an
83609   **        an integer primary key
83610   **
83611   **    *   We can conditionally do the transfer if the destination
83612   **        table is empty.
83613   */
83614 #ifdef SQLITE_TEST
83615   sqlite3_xferopt_count++;
83616 #endif
83617   iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
83618   v = sqlite3GetVdbe(pParse);
83619   sqlite3CodeVerifySchema(pParse, iDbSrc);
83620   iSrc = pParse->nTab++;
83621   iDest = pParse->nTab++;
83622   regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
83623   sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
83624   if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
83625     /* If tables do not have an INTEGER PRIMARY KEY and there
83626     ** are indices to be copied and the destination is not empty,
83627     ** we have to disallow the transfer optimization because the
83628     ** the rowids might change which will mess up indexing.
83629     **
83630     ** Or if the destination has a UNIQUE index and is not empty,
83631     ** we also disallow the transfer optimization because we cannot
83632     ** insure that all entries in the union of DEST and SRC will be
83633     ** unique.
83634     */
83635     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
83636     emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
83637     sqlite3VdbeJumpHere(v, addr1);
83638   }else{
83639     emptyDestTest = 0;
83640   }
83641   sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
83642   emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
83643   regData = sqlite3GetTempReg(pParse);
83644   regRowid = sqlite3GetTempReg(pParse);
83645   if( pDest->iPKey>=0 ){
83646     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
83647     addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
83648     sqlite3HaltConstraint(
83649         pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
83650     sqlite3VdbeJumpHere(v, addr2);
83651     autoIncStep(pParse, regAutoinc, regRowid);
83652   }else if( pDest->pIndex==0 ){
83653     addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
83654   }else{
83655     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
83656     assert( (pDest->tabFlags & TF_Autoincrement)==0 );
83657   }
83658   sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
83659   sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
83660   sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
83661   sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
83662   sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
83663   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
83664     for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
83665       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
83666     }
83667     assert( pSrcIdx );
83668     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
83669     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
83670     pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
83671     sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
83672                       (char*)pKey, P4_KEYINFO_HANDOFF);
83673     VdbeComment((v, "%s", pSrcIdx->zName));
83674     pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
83675     sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
83676                       (char*)pKey, P4_KEYINFO_HANDOFF);
83677     VdbeComment((v, "%s", pDestIdx->zName));
83678     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
83679     sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
83680     sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
83681     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
83682     sqlite3VdbeJumpHere(v, addr1);
83683   }
83684   sqlite3VdbeJumpHere(v, emptySrcTest);
83685   sqlite3ReleaseTempReg(pParse, regRowid);
83686   sqlite3ReleaseTempReg(pParse, regData);
83687   sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
83688   sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
83689   if( emptyDestTest ){
83690     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
83691     sqlite3VdbeJumpHere(v, emptyDestTest);
83692     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
83693     return 0;
83694   }else{
83695     return 1;
83696   }
83697 }
83698 #endif /* SQLITE_OMIT_XFER_OPT */
83699
83700 /************** End of insert.c **********************************************/
83701 /************** Begin file legacy.c ******************************************/
83702 /*
83703 ** 2001 September 15
83704 **
83705 ** The author disclaims copyright to this source code.  In place of
83706 ** a legal notice, here is a blessing:
83707 **
83708 **    May you do good and not evil.
83709 **    May you find forgiveness for yourself and forgive others.
83710 **    May you share freely, never taking more than you give.
83711 **
83712 *************************************************************************
83713 ** Main file for the SQLite library.  The routines in this file
83714 ** implement the programmer interface to the library.  Routines in
83715 ** other files are for internal use by SQLite and should not be
83716 ** accessed by users of the library.
83717 */
83718
83719
83720 /*
83721 ** Execute SQL code.  Return one of the SQLITE_ success/failure
83722 ** codes.  Also write an error message into memory obtained from
83723 ** malloc() and make *pzErrMsg point to that message.
83724 **
83725 ** If the SQL is a query, then for each row in the query result
83726 ** the xCallback() function is called.  pArg becomes the first
83727 ** argument to xCallback().  If xCallback=NULL then no callback
83728 ** is invoked, even for queries.
83729 */
83730 SQLITE_API int sqlite3_exec(
83731   sqlite3 *db,                /* The database on which the SQL executes */
83732   const char *zSql,           /* The SQL to be executed */
83733   sqlite3_callback xCallback, /* Invoke this callback routine */
83734   void *pArg,                 /* First argument to xCallback() */
83735   char **pzErrMsg             /* Write error messages here */
83736 ){
83737   int rc = SQLITE_OK;         /* Return code */
83738   const char *zLeftover;      /* Tail of unprocessed SQL */
83739   sqlite3_stmt *pStmt = 0;    /* The current SQL statement */
83740   char **azCols = 0;          /* Names of result columns */
83741   int nRetry = 0;             /* Number of retry attempts */
83742   int callbackIsInit;         /* True if callback data is initialized */
83743
83744   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
83745   if( zSql==0 ) zSql = "";
83746
83747   sqlite3_mutex_enter(db->mutex);
83748   sqlite3Error(db, SQLITE_OK, 0);
83749   while( (rc==SQLITE_OK || (rc==SQLITE_SCHEMA && (++nRetry)<2)) && zSql[0] ){
83750     int nCol;
83751     char **azVals = 0;
83752
83753     pStmt = 0;
83754     rc = sqlite3_prepare(db, zSql, -1, &pStmt, &zLeftover);
83755     assert( rc==SQLITE_OK || pStmt==0 );
83756     if( rc!=SQLITE_OK ){
83757       continue;
83758     }
83759     if( !pStmt ){
83760       /* this happens for a comment or white-space */
83761       zSql = zLeftover;
83762       continue;
83763     }
83764
83765     callbackIsInit = 0;
83766     nCol = sqlite3_column_count(pStmt);
83767
83768     while( 1 ){
83769       int i;
83770       rc = sqlite3_step(pStmt);
83771
83772       /* Invoke the callback function if required */
83773       if( xCallback && (SQLITE_ROW==rc || 
83774           (SQLITE_DONE==rc && !callbackIsInit
83775                            && db->flags&SQLITE_NullCallback)) ){
83776         if( !callbackIsInit ){
83777           azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
83778           if( azCols==0 ){
83779             goto exec_out;
83780           }
83781           for(i=0; i<nCol; i++){
83782             azCols[i] = (char *)sqlite3_column_name(pStmt, i);
83783             /* sqlite3VdbeSetColName() installs column names as UTF8
83784             ** strings so there is no way for sqlite3_column_name() to fail. */
83785             assert( azCols[i]!=0 );
83786           }
83787           callbackIsInit = 1;
83788         }
83789         if( rc==SQLITE_ROW ){
83790           azVals = &azCols[nCol];
83791           for(i=0; i<nCol; i++){
83792             azVals[i] = (char *)sqlite3_column_text(pStmt, i);
83793             if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
83794               db->mallocFailed = 1;
83795               goto exec_out;
83796             }
83797           }
83798         }
83799         if( xCallback(pArg, nCol, azVals, azCols) ){
83800           rc = SQLITE_ABORT;
83801           sqlite3VdbeFinalize((Vdbe *)pStmt);
83802           pStmt = 0;
83803           sqlite3Error(db, SQLITE_ABORT, 0);
83804           goto exec_out;
83805         }
83806       }
83807
83808       if( rc!=SQLITE_ROW ){
83809         rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
83810         pStmt = 0;
83811         if( rc!=SQLITE_SCHEMA ){
83812           nRetry = 0;
83813           zSql = zLeftover;
83814           while( sqlite3Isspace(zSql[0]) ) zSql++;
83815         }
83816         break;
83817       }
83818     }
83819
83820     sqlite3DbFree(db, azCols);
83821     azCols = 0;
83822   }
83823
83824 exec_out:
83825   if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
83826   sqlite3DbFree(db, azCols);
83827
83828   rc = sqlite3ApiExit(db, rc);
83829   if( rc!=SQLITE_OK && ALWAYS(rc==sqlite3_errcode(db)) && pzErrMsg ){
83830     int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
83831     *pzErrMsg = sqlite3Malloc(nErrMsg);
83832     if( *pzErrMsg ){
83833       memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
83834     }else{
83835       rc = SQLITE_NOMEM;
83836       sqlite3Error(db, SQLITE_NOMEM, 0);
83837     }
83838   }else if( pzErrMsg ){
83839     *pzErrMsg = 0;
83840   }
83841
83842   assert( (rc&db->errMask)==rc );
83843   sqlite3_mutex_leave(db->mutex);
83844   return rc;
83845 }
83846
83847 /************** End of legacy.c **********************************************/
83848 /************** Begin file loadext.c *****************************************/
83849 /*
83850 ** 2006 June 7
83851 **
83852 ** The author disclaims copyright to this source code.  In place of
83853 ** a legal notice, here is a blessing:
83854 **
83855 **    May you do good and not evil.
83856 **    May you find forgiveness for yourself and forgive others.
83857 **    May you share freely, never taking more than you give.
83858 **
83859 *************************************************************************
83860 ** This file contains code used to dynamically load extensions into
83861 ** the SQLite library.
83862 */
83863
83864 #ifndef SQLITE_CORE
83865   #define SQLITE_CORE 1  /* Disable the API redefinition in sqlite3ext.h */
83866 #endif
83867 /************** Include sqlite3ext.h in the middle of loadext.c **************/
83868 /************** Begin file sqlite3ext.h **************************************/
83869 /*
83870 ** 2006 June 7
83871 **
83872 ** The author disclaims copyright to this source code.  In place of
83873 ** a legal notice, here is a blessing:
83874 **
83875 **    May you do good and not evil.
83876 **    May you find forgiveness for yourself and forgive others.
83877 **    May you share freely, never taking more than you give.
83878 **
83879 *************************************************************************
83880 ** This header file defines the SQLite interface for use by
83881 ** shared libraries that want to be imported as extensions into
83882 ** an SQLite instance.  Shared libraries that intend to be loaded
83883 ** as extensions by SQLite should #include this file instead of 
83884 ** sqlite3.h.
83885 */
83886 #ifndef _SQLITE3EXT_H_
83887 #define _SQLITE3EXT_H_
83888
83889 typedef struct sqlite3_api_routines sqlite3_api_routines;
83890
83891 /*
83892 ** The following structure holds pointers to all of the SQLite API
83893 ** routines.
83894 **
83895 ** WARNING:  In order to maintain backwards compatibility, add new
83896 ** interfaces to the end of this structure only.  If you insert new
83897 ** interfaces in the middle of this structure, then older different
83898 ** versions of SQLite will not be able to load each others' shared
83899 ** libraries!
83900 */
83901 struct sqlite3_api_routines {
83902   void * (*aggregate_context)(sqlite3_context*,int nBytes);
83903   int  (*aggregate_count)(sqlite3_context*);
83904   int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
83905   int  (*bind_double)(sqlite3_stmt*,int,double);
83906   int  (*bind_int)(sqlite3_stmt*,int,int);
83907   int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
83908   int  (*bind_null)(sqlite3_stmt*,int);
83909   int  (*bind_parameter_count)(sqlite3_stmt*);
83910   int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
83911   const char * (*bind_parameter_name)(sqlite3_stmt*,int);
83912   int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
83913   int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
83914   int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
83915   int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
83916   int  (*busy_timeout)(sqlite3*,int ms);
83917   int  (*changes)(sqlite3*);
83918   int  (*close)(sqlite3*);
83919   int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const char*));
83920   int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const void*));
83921   const void * (*column_blob)(sqlite3_stmt*,int iCol);
83922   int  (*column_bytes)(sqlite3_stmt*,int iCol);
83923   int  (*column_bytes16)(sqlite3_stmt*,int iCol);
83924   int  (*column_count)(sqlite3_stmt*pStmt);
83925   const char * (*column_database_name)(sqlite3_stmt*,int);
83926   const void * (*column_database_name16)(sqlite3_stmt*,int);
83927   const char * (*column_decltype)(sqlite3_stmt*,int i);
83928   const void * (*column_decltype16)(sqlite3_stmt*,int);
83929   double  (*column_double)(sqlite3_stmt*,int iCol);
83930   int  (*column_int)(sqlite3_stmt*,int iCol);
83931   sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);
83932   const char * (*column_name)(sqlite3_stmt*,int);
83933   const void * (*column_name16)(sqlite3_stmt*,int);
83934   const char * (*column_origin_name)(sqlite3_stmt*,int);
83935   const void * (*column_origin_name16)(sqlite3_stmt*,int);
83936   const char * (*column_table_name)(sqlite3_stmt*,int);
83937   const void * (*column_table_name16)(sqlite3_stmt*,int);
83938   const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
83939   const void * (*column_text16)(sqlite3_stmt*,int iCol);
83940   int  (*column_type)(sqlite3_stmt*,int iCol);
83941   sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
83942   void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
83943   int  (*complete)(const char*sql);
83944   int  (*complete16)(const void*sql);
83945   int  (*create_collation)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*));
83946   int  (*create_collation16)(sqlite3*,const void*,int,void*,int(*)(void*,int,const void*,int,const void*));
83947   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*));
83948   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*));
83949   int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
83950   int  (*data_count)(sqlite3_stmt*pStmt);
83951   sqlite3 * (*db_handle)(sqlite3_stmt*);
83952   int (*declare_vtab)(sqlite3*,const char*);
83953   int  (*enable_shared_cache)(int);
83954   int  (*errcode)(sqlite3*db);
83955   const char * (*errmsg)(sqlite3*);
83956   const void * (*errmsg16)(sqlite3*);
83957   int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
83958   int  (*expired)(sqlite3_stmt*);
83959   int  (*finalize)(sqlite3_stmt*pStmt);
83960   void  (*free)(void*);
83961   void  (*free_table)(char**result);
83962   int  (*get_autocommit)(sqlite3*);
83963   void * (*get_auxdata)(sqlite3_context*,int);
83964   int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
83965   int  (*global_recover)(void);
83966   void  (*interruptx)(sqlite3*);
83967   sqlite_int64  (*last_insert_rowid)(sqlite3*);
83968   const char * (*libversion)(void);
83969   int  (*libversion_number)(void);
83970   void *(*malloc)(int);
83971   char * (*mprintf)(const char*,...);
83972   int  (*open)(const char*,sqlite3**);
83973   int  (*open16)(const void*,sqlite3**);
83974   int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
83975   int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
83976   void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
83977   void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
83978   void *(*realloc)(void*,int);
83979   int  (*reset)(sqlite3_stmt*pStmt);
83980   void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
83981   void  (*result_double)(sqlite3_context*,double);
83982   void  (*result_error)(sqlite3_context*,const char*,int);
83983   void  (*result_error16)(sqlite3_context*,const void*,int);
83984   void  (*result_int)(sqlite3_context*,int);
83985   void  (*result_int64)(sqlite3_context*,sqlite_int64);
83986   void  (*result_null)(sqlite3_context*);
83987   void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
83988   void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
83989   void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
83990   void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
83991   void  (*result_value)(sqlite3_context*,sqlite3_value*);
83992   void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
83993   int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,const char*,const char*),void*);
83994   void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
83995   char * (*snprintf)(int,char*,const char*,...);
83996   int  (*step)(sqlite3_stmt*);
83997   int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,char const**,char const**,int*,int*,int*);
83998   void  (*thread_cleanup)(void);
83999   int  (*total_changes)(sqlite3*);
84000   void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
84001   int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
84002   void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,sqlite_int64),void*);
84003   void * (*user_data)(sqlite3_context*);
84004   const void * (*value_blob)(sqlite3_value*);
84005   int  (*value_bytes)(sqlite3_value*);
84006   int  (*value_bytes16)(sqlite3_value*);
84007   double  (*value_double)(sqlite3_value*);
84008   int  (*value_int)(sqlite3_value*);
84009   sqlite_int64  (*value_int64)(sqlite3_value*);
84010   int  (*value_numeric_type)(sqlite3_value*);
84011   const unsigned char * (*value_text)(sqlite3_value*);
84012   const void * (*value_text16)(sqlite3_value*);
84013   const void * (*value_text16be)(sqlite3_value*);
84014   const void * (*value_text16le)(sqlite3_value*);
84015   int  (*value_type)(sqlite3_value*);
84016   char *(*vmprintf)(const char*,va_list);
84017   /* Added ??? */
84018   int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
84019   /* Added by 3.3.13 */
84020   int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
84021   int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
84022   int (*clear_bindings)(sqlite3_stmt*);
84023   /* Added by 3.4.1 */
84024   int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,void (*xDestroy)(void *));
84025   /* Added by 3.5.0 */
84026   int (*bind_zeroblob)(sqlite3_stmt*,int,int);
84027   int (*blob_bytes)(sqlite3_blob*);
84028   int (*blob_close)(sqlite3_blob*);
84029   int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,int,sqlite3_blob**);
84030   int (*blob_read)(sqlite3_blob*,void*,int,int);
84031   int (*blob_write)(sqlite3_blob*,const void*,int,int);
84032   int (*create_collation_v2)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*),void(*)(void*));
84033   int (*file_control)(sqlite3*,const char*,int,void*);
84034   sqlite3_int64 (*memory_highwater)(int);
84035   sqlite3_int64 (*memory_used)(void);
84036   sqlite3_mutex *(*mutex_alloc)(int);
84037   void (*mutex_enter)(sqlite3_mutex*);
84038   void (*mutex_free)(sqlite3_mutex*);
84039   void (*mutex_leave)(sqlite3_mutex*);
84040   int (*mutex_try)(sqlite3_mutex*);
84041   int (*open_v2)(const char*,sqlite3**,int,const char*);
84042   int (*release_memory)(int);
84043   void (*result_error_nomem)(sqlite3_context*);
84044   void (*result_error_toobig)(sqlite3_context*);
84045   int (*sleep)(int);
84046   void (*soft_heap_limit)(int);
84047   sqlite3_vfs *(*vfs_find)(const char*);
84048   int (*vfs_register)(sqlite3_vfs*,int);
84049   int (*vfs_unregister)(sqlite3_vfs*);
84050   int (*xthreadsafe)(void);
84051   void (*result_zeroblob)(sqlite3_context*,int);
84052   void (*result_error_code)(sqlite3_context*,int);
84053   int (*test_control)(int, ...);
84054   void (*randomness)(int,void*);
84055   sqlite3 *(*context_db_handle)(sqlite3_context*);
84056   int (*extended_result_codes)(sqlite3*,int);
84057   int (*limit)(sqlite3*,int,int);
84058   sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
84059   const char *(*sql)(sqlite3_stmt*);
84060   int (*status)(int,int*,int*,int);
84061 };
84062
84063 /*
84064 ** The following macros redefine the API routines so that they are
84065 ** redirected throught the global sqlite3_api structure.
84066 **
84067 ** This header file is also used by the loadext.c source file
84068 ** (part of the main SQLite library - not an extension) so that
84069 ** it can get access to the sqlite3_api_routines structure
84070 ** definition.  But the main library does not want to redefine
84071 ** the API.  So the redefinition macros are only valid if the
84072 ** SQLITE_CORE macros is undefined.
84073 */
84074 #ifndef SQLITE_CORE
84075 #define sqlite3_aggregate_context      sqlite3_api->aggregate_context
84076 #ifndef SQLITE_OMIT_DEPRECATED
84077 #define sqlite3_aggregate_count        sqlite3_api->aggregate_count
84078 #endif
84079 #define sqlite3_bind_blob              sqlite3_api->bind_blob
84080 #define sqlite3_bind_double            sqlite3_api->bind_double
84081 #define sqlite3_bind_int               sqlite3_api->bind_int
84082 #define sqlite3_bind_int64             sqlite3_api->bind_int64
84083 #define sqlite3_bind_null              sqlite3_api->bind_null
84084 #define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count
84085 #define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index
84086 #define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name
84087 #define sqlite3_bind_text              sqlite3_api->bind_text
84088 #define sqlite3_bind_text16            sqlite3_api->bind_text16
84089 #define sqlite3_bind_value             sqlite3_api->bind_value
84090 #define sqlite3_busy_handler           sqlite3_api->busy_handler
84091 #define sqlite3_busy_timeout           sqlite3_api->busy_timeout
84092 #define sqlite3_changes                sqlite3_api->changes
84093 #define sqlite3_close                  sqlite3_api->close
84094 #define sqlite3_collation_needed       sqlite3_api->collation_needed
84095 #define sqlite3_collation_needed16     sqlite3_api->collation_needed16
84096 #define sqlite3_column_blob            sqlite3_api->column_blob
84097 #define sqlite3_column_bytes           sqlite3_api->column_bytes
84098 #define sqlite3_column_bytes16         sqlite3_api->column_bytes16
84099 #define sqlite3_column_count           sqlite3_api->column_count
84100 #define sqlite3_column_database_name   sqlite3_api->column_database_name
84101 #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
84102 #define sqlite3_column_decltype        sqlite3_api->column_decltype
84103 #define sqlite3_column_decltype16      sqlite3_api->column_decltype16
84104 #define sqlite3_column_double          sqlite3_api->column_double
84105 #define sqlite3_column_int             sqlite3_api->column_int
84106 #define sqlite3_column_int64           sqlite3_api->column_int64
84107 #define sqlite3_column_name            sqlite3_api->column_name
84108 #define sqlite3_column_name16          sqlite3_api->column_name16
84109 #define sqlite3_column_origin_name     sqlite3_api->column_origin_name
84110 #define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16
84111 #define sqlite3_column_table_name      sqlite3_api->column_table_name
84112 #define sqlite3_column_table_name16    sqlite3_api->column_table_name16
84113 #define sqlite3_column_text            sqlite3_api->column_text
84114 #define sqlite3_column_text16          sqlite3_api->column_text16
84115 #define sqlite3_column_type            sqlite3_api->column_type
84116 #define sqlite3_column_value           sqlite3_api->column_value
84117 #define sqlite3_commit_hook            sqlite3_api->commit_hook
84118 #define sqlite3_complete               sqlite3_api->complete
84119 #define sqlite3_complete16             sqlite3_api->complete16
84120 #define sqlite3_create_collation       sqlite3_api->create_collation
84121 #define sqlite3_create_collation16     sqlite3_api->create_collation16
84122 #define sqlite3_create_function        sqlite3_api->create_function
84123 #define sqlite3_create_function16      sqlite3_api->create_function16
84124 #define sqlite3_create_module          sqlite3_api->create_module
84125 #define sqlite3_create_module_v2       sqlite3_api->create_module_v2
84126 #define sqlite3_data_count             sqlite3_api->data_count
84127 #define sqlite3_db_handle              sqlite3_api->db_handle
84128 #define sqlite3_declare_vtab           sqlite3_api->declare_vtab
84129 #define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
84130 #define sqlite3_errcode                sqlite3_api->errcode
84131 #define sqlite3_errmsg                 sqlite3_api->errmsg
84132 #define sqlite3_errmsg16               sqlite3_api->errmsg16
84133 #define sqlite3_exec                   sqlite3_api->exec
84134 #ifndef SQLITE_OMIT_DEPRECATED
84135 #define sqlite3_expired                sqlite3_api->expired
84136 #endif
84137 #define sqlite3_finalize               sqlite3_api->finalize
84138 #define sqlite3_free                   sqlite3_api->free
84139 #define sqlite3_free_table             sqlite3_api->free_table
84140 #define sqlite3_get_autocommit         sqlite3_api->get_autocommit
84141 #define sqlite3_get_auxdata            sqlite3_api->get_auxdata
84142 #define sqlite3_get_table              sqlite3_api->get_table
84143 #ifndef SQLITE_OMIT_DEPRECATED
84144 #define sqlite3_global_recover         sqlite3_api->global_recover
84145 #endif
84146 #define sqlite3_interrupt              sqlite3_api->interruptx
84147 #define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid
84148 #define sqlite3_libversion             sqlite3_api->libversion
84149 #define sqlite3_libversion_number      sqlite3_api->libversion_number
84150 #define sqlite3_malloc                 sqlite3_api->malloc
84151 #define sqlite3_mprintf                sqlite3_api->mprintf
84152 #define sqlite3_open                   sqlite3_api->open
84153 #define sqlite3_open16                 sqlite3_api->open16
84154 #define sqlite3_prepare                sqlite3_api->prepare
84155 #define sqlite3_prepare16              sqlite3_api->prepare16
84156 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
84157 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
84158 #define sqlite3_profile                sqlite3_api->profile
84159 #define sqlite3_progress_handler       sqlite3_api->progress_handler
84160 #define sqlite3_realloc                sqlite3_api->realloc
84161 #define sqlite3_reset                  sqlite3_api->reset
84162 #define sqlite3_result_blob            sqlite3_api->result_blob
84163 #define sqlite3_result_double          sqlite3_api->result_double
84164 #define sqlite3_result_error           sqlite3_api->result_error
84165 #define sqlite3_result_error16         sqlite3_api->result_error16
84166 #define sqlite3_result_int             sqlite3_api->result_int
84167 #define sqlite3_result_int64           sqlite3_api->result_int64
84168 #define sqlite3_result_null            sqlite3_api->result_null
84169 #define sqlite3_result_text            sqlite3_api->result_text
84170 #define sqlite3_result_text16          sqlite3_api->result_text16
84171 #define sqlite3_result_text16be        sqlite3_api->result_text16be
84172 #define sqlite3_result_text16le        sqlite3_api->result_text16le
84173 #define sqlite3_result_value           sqlite3_api->result_value
84174 #define sqlite3_rollback_hook          sqlite3_api->rollback_hook
84175 #define sqlite3_set_authorizer         sqlite3_api->set_authorizer
84176 #define sqlite3_set_auxdata            sqlite3_api->set_auxdata
84177 #define sqlite3_snprintf               sqlite3_api->snprintf
84178 #define sqlite3_step                   sqlite3_api->step
84179 #define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata
84180 #define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup
84181 #define sqlite3_total_changes          sqlite3_api->total_changes
84182 #define sqlite3_trace                  sqlite3_api->trace
84183 #ifndef SQLITE_OMIT_DEPRECATED
84184 #define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings
84185 #endif
84186 #define sqlite3_update_hook            sqlite3_api->update_hook
84187 #define sqlite3_user_data              sqlite3_api->user_data
84188 #define sqlite3_value_blob             sqlite3_api->value_blob
84189 #define sqlite3_value_bytes            sqlite3_api->value_bytes
84190 #define sqlite3_value_bytes16          sqlite3_api->value_bytes16
84191 #define sqlite3_value_double           sqlite3_api->value_double
84192 #define sqlite3_value_int              sqlite3_api->value_int
84193 #define sqlite3_value_int64            sqlite3_api->value_int64
84194 #define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type
84195 #define sqlite3_value_text             sqlite3_api->value_text
84196 #define sqlite3_value_text16           sqlite3_api->value_text16
84197 #define sqlite3_value_text16be         sqlite3_api->value_text16be
84198 #define sqlite3_value_text16le         sqlite3_api->value_text16le
84199 #define sqlite3_value_type             sqlite3_api->value_type
84200 #define sqlite3_vmprintf               sqlite3_api->vmprintf
84201 #define sqlite3_overload_function      sqlite3_api->overload_function
84202 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
84203 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
84204 #define sqlite3_clear_bindings         sqlite3_api->clear_bindings
84205 #define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob
84206 #define sqlite3_blob_bytes             sqlite3_api->blob_bytes
84207 #define sqlite3_blob_close             sqlite3_api->blob_close
84208 #define sqlite3_blob_open              sqlite3_api->blob_open
84209 #define sqlite3_blob_read              sqlite3_api->blob_read
84210 #define sqlite3_blob_write             sqlite3_api->blob_write
84211 #define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2
84212 #define sqlite3_file_control           sqlite3_api->file_control
84213 #define sqlite3_memory_highwater       sqlite3_api->memory_highwater
84214 #define sqlite3_memory_used            sqlite3_api->memory_used
84215 #define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc
84216 #define sqlite3_mutex_enter            sqlite3_api->mutex_enter
84217 #define sqlite3_mutex_free             sqlite3_api->mutex_free
84218 #define sqlite3_mutex_leave            sqlite3_api->mutex_leave
84219 #define sqlite3_mutex_try              sqlite3_api->mutex_try
84220 #define sqlite3_open_v2                sqlite3_api->open_v2
84221 #define sqlite3_release_memory         sqlite3_api->release_memory
84222 #define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem
84223 #define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig
84224 #define sqlite3_sleep                  sqlite3_api->sleep
84225 #define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit
84226 #define sqlite3_vfs_find               sqlite3_api->vfs_find
84227 #define sqlite3_vfs_register           sqlite3_api->vfs_register
84228 #define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister
84229 #define sqlite3_threadsafe             sqlite3_api->xthreadsafe
84230 #define sqlite3_result_zeroblob        sqlite3_api->result_zeroblob
84231 #define sqlite3_result_error_code      sqlite3_api->result_error_code
84232 #define sqlite3_test_control           sqlite3_api->test_control
84233 #define sqlite3_randomness             sqlite3_api->randomness
84234 #define sqlite3_context_db_handle      sqlite3_api->context_db_handle
84235 #define sqlite3_extended_result_codes  sqlite3_api->extended_result_codes
84236 #define sqlite3_limit                  sqlite3_api->limit
84237 #define sqlite3_next_stmt              sqlite3_api->next_stmt
84238 #define sqlite3_sql                    sqlite3_api->sql
84239 #define sqlite3_status                 sqlite3_api->status
84240 #endif /* SQLITE_CORE */
84241
84242 #define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api = 0;
84243 #define SQLITE_EXTENSION_INIT2(v)  sqlite3_api = v;
84244
84245 #endif /* _SQLITE3EXT_H_ */
84246
84247 /************** End of sqlite3ext.h ******************************************/
84248 /************** Continuing where we left off in loadext.c ********************/
84249
84250 #ifndef SQLITE_OMIT_LOAD_EXTENSION
84251
84252 /*
84253 ** Some API routines are omitted when various features are
84254 ** excluded from a build of SQLite.  Substitute a NULL pointer
84255 ** for any missing APIs.
84256 */
84257 #ifndef SQLITE_ENABLE_COLUMN_METADATA
84258 # define sqlite3_column_database_name   0
84259 # define sqlite3_column_database_name16 0
84260 # define sqlite3_column_table_name      0
84261 # define sqlite3_column_table_name16    0
84262 # define sqlite3_column_origin_name     0
84263 # define sqlite3_column_origin_name16   0
84264 # define sqlite3_table_column_metadata  0
84265 #endif
84266
84267 #ifdef SQLITE_OMIT_AUTHORIZATION
84268 # define sqlite3_set_authorizer         0
84269 #endif
84270
84271 #ifdef SQLITE_OMIT_UTF16
84272 # define sqlite3_bind_text16            0
84273 # define sqlite3_collation_needed16     0
84274 # define sqlite3_column_decltype16      0
84275 # define sqlite3_column_name16          0
84276 # define sqlite3_column_text16          0
84277 # define sqlite3_complete16             0
84278 # define sqlite3_create_collation16     0
84279 # define sqlite3_create_function16      0
84280 # define sqlite3_errmsg16               0
84281 # define sqlite3_open16                 0
84282 # define sqlite3_prepare16              0
84283 # define sqlite3_prepare16_v2           0
84284 # define sqlite3_result_error16         0
84285 # define sqlite3_result_text16          0
84286 # define sqlite3_result_text16be        0
84287 # define sqlite3_result_text16le        0
84288 # define sqlite3_value_text16           0
84289 # define sqlite3_value_text16be         0
84290 # define sqlite3_value_text16le         0
84291 # define sqlite3_column_database_name16 0
84292 # define sqlite3_column_table_name16    0
84293 # define sqlite3_column_origin_name16   0
84294 #endif
84295
84296 #ifdef SQLITE_OMIT_COMPLETE
84297 # define sqlite3_complete 0
84298 # define sqlite3_complete16 0
84299 #endif
84300
84301 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
84302 # define sqlite3_progress_handler 0
84303 #endif
84304
84305 #ifdef SQLITE_OMIT_VIRTUALTABLE
84306 # define sqlite3_create_module 0
84307 # define sqlite3_create_module_v2 0
84308 # define sqlite3_declare_vtab 0
84309 #endif
84310
84311 #ifdef SQLITE_OMIT_SHARED_CACHE
84312 # define sqlite3_enable_shared_cache 0
84313 #endif
84314
84315 #ifdef SQLITE_OMIT_TRACE
84316 # define sqlite3_profile       0
84317 # define sqlite3_trace         0
84318 #endif
84319
84320 #ifdef SQLITE_OMIT_GET_TABLE
84321 # define sqlite3_free_table    0
84322 # define sqlite3_get_table     0
84323 #endif
84324
84325 #ifdef SQLITE_OMIT_INCRBLOB
84326 #define sqlite3_bind_zeroblob  0
84327 #define sqlite3_blob_bytes     0
84328 #define sqlite3_blob_close     0
84329 #define sqlite3_blob_open      0
84330 #define sqlite3_blob_read      0
84331 #define sqlite3_blob_write     0
84332 #endif
84333
84334 /*
84335 ** The following structure contains pointers to all SQLite API routines.
84336 ** A pointer to this structure is passed into extensions when they are
84337 ** loaded so that the extension can make calls back into the SQLite
84338 ** library.
84339 **
84340 ** When adding new APIs, add them to the bottom of this structure
84341 ** in order to preserve backwards compatibility.
84342 **
84343 ** Extensions that use newer APIs should first call the
84344 ** sqlite3_libversion_number() to make sure that the API they
84345 ** intend to use is supported by the library.  Extensions should
84346 ** also check to make sure that the pointer to the function is
84347 ** not NULL before calling it.
84348 */
84349 static const sqlite3_api_routines sqlite3Apis = {
84350   sqlite3_aggregate_context,
84351 #ifndef SQLITE_OMIT_DEPRECATED
84352   sqlite3_aggregate_count,
84353 #else
84354   0,
84355 #endif
84356   sqlite3_bind_blob,
84357   sqlite3_bind_double,
84358   sqlite3_bind_int,
84359   sqlite3_bind_int64,
84360   sqlite3_bind_null,
84361   sqlite3_bind_parameter_count,
84362   sqlite3_bind_parameter_index,
84363   sqlite3_bind_parameter_name,
84364   sqlite3_bind_text,
84365   sqlite3_bind_text16,
84366   sqlite3_bind_value,
84367   sqlite3_busy_handler,
84368   sqlite3_busy_timeout,
84369   sqlite3_changes,
84370   sqlite3_close,
84371   sqlite3_collation_needed,
84372   sqlite3_collation_needed16,
84373   sqlite3_column_blob,
84374   sqlite3_column_bytes,
84375   sqlite3_column_bytes16,
84376   sqlite3_column_count,
84377   sqlite3_column_database_name,
84378   sqlite3_column_database_name16,
84379   sqlite3_column_decltype,
84380   sqlite3_column_decltype16,
84381   sqlite3_column_double,
84382   sqlite3_column_int,
84383   sqlite3_column_int64,
84384   sqlite3_column_name,
84385   sqlite3_column_name16,
84386   sqlite3_column_origin_name,
84387   sqlite3_column_origin_name16,
84388   sqlite3_column_table_name,
84389   sqlite3_column_table_name16,
84390   sqlite3_column_text,
84391   sqlite3_column_text16,
84392   sqlite3_column_type,
84393   sqlite3_column_value,
84394   sqlite3_commit_hook,
84395   sqlite3_complete,
84396   sqlite3_complete16,
84397   sqlite3_create_collation,
84398   sqlite3_create_collation16,
84399   sqlite3_create_function,
84400   sqlite3_create_function16,
84401   sqlite3_create_module,
84402   sqlite3_data_count,
84403   sqlite3_db_handle,
84404   sqlite3_declare_vtab,
84405   sqlite3_enable_shared_cache,
84406   sqlite3_errcode,
84407   sqlite3_errmsg,
84408   sqlite3_errmsg16,
84409   sqlite3_exec,
84410 #ifndef SQLITE_OMIT_DEPRECATED
84411   sqlite3_expired,
84412 #else
84413   0,
84414 #endif
84415   sqlite3_finalize,
84416   sqlite3_free,
84417   sqlite3_free_table,
84418   sqlite3_get_autocommit,
84419   sqlite3_get_auxdata,
84420   sqlite3_get_table,
84421   0,     /* Was sqlite3_global_recover(), but that function is deprecated */
84422   sqlite3_interrupt,
84423   sqlite3_last_insert_rowid,
84424   sqlite3_libversion,
84425   sqlite3_libversion_number,
84426   sqlite3_malloc,
84427   sqlite3_mprintf,
84428   sqlite3_open,
84429   sqlite3_open16,
84430   sqlite3_prepare,
84431   sqlite3_prepare16,
84432   sqlite3_profile,
84433   sqlite3_progress_handler,
84434   sqlite3_realloc,
84435   sqlite3_reset,
84436   sqlite3_result_blob,
84437   sqlite3_result_double,
84438   sqlite3_result_error,
84439   sqlite3_result_error16,
84440   sqlite3_result_int,
84441   sqlite3_result_int64,
84442   sqlite3_result_null,
84443   sqlite3_result_text,
84444   sqlite3_result_text16,
84445   sqlite3_result_text16be,
84446   sqlite3_result_text16le,
84447   sqlite3_result_value,
84448   sqlite3_rollback_hook,
84449   sqlite3_set_authorizer,
84450   sqlite3_set_auxdata,
84451   sqlite3_snprintf,
84452   sqlite3_step,
84453   sqlite3_table_column_metadata,
84454 #ifndef SQLITE_OMIT_DEPRECATED
84455   sqlite3_thread_cleanup,
84456 #else
84457   0,
84458 #endif
84459   sqlite3_total_changes,
84460   sqlite3_trace,
84461 #ifndef SQLITE_OMIT_DEPRECATED
84462   sqlite3_transfer_bindings,
84463 #else
84464   0,
84465 #endif
84466   sqlite3_update_hook,
84467   sqlite3_user_data,
84468   sqlite3_value_blob,
84469   sqlite3_value_bytes,
84470   sqlite3_value_bytes16,
84471   sqlite3_value_double,
84472   sqlite3_value_int,
84473   sqlite3_value_int64,
84474   sqlite3_value_numeric_type,
84475   sqlite3_value_text,
84476   sqlite3_value_text16,
84477   sqlite3_value_text16be,
84478   sqlite3_value_text16le,
84479   sqlite3_value_type,
84480   sqlite3_vmprintf,
84481   /*
84482   ** The original API set ends here.  All extensions can call any
84483   ** of the APIs above provided that the pointer is not NULL.  But
84484   ** before calling APIs that follow, extension should check the
84485   ** sqlite3_libversion_number() to make sure they are dealing with
84486   ** a library that is new enough to support that API.
84487   *************************************************************************
84488   */
84489   sqlite3_overload_function,
84490
84491   /*
84492   ** Added after 3.3.13
84493   */
84494   sqlite3_prepare_v2,
84495   sqlite3_prepare16_v2,
84496   sqlite3_clear_bindings,
84497
84498   /*
84499   ** Added for 3.4.1
84500   */
84501   sqlite3_create_module_v2,
84502
84503   /*
84504   ** Added for 3.5.0
84505   */
84506   sqlite3_bind_zeroblob,
84507   sqlite3_blob_bytes,
84508   sqlite3_blob_close,
84509   sqlite3_blob_open,
84510   sqlite3_blob_read,
84511   sqlite3_blob_write,
84512   sqlite3_create_collation_v2,
84513   sqlite3_file_control,
84514   sqlite3_memory_highwater,
84515   sqlite3_memory_used,
84516 #ifdef SQLITE_MUTEX_OMIT
84517   0, 
84518   0, 
84519   0,
84520   0,
84521   0,
84522 #else
84523   sqlite3_mutex_alloc,
84524   sqlite3_mutex_enter,
84525   sqlite3_mutex_free,
84526   sqlite3_mutex_leave,
84527   sqlite3_mutex_try,
84528 #endif
84529   sqlite3_open_v2,
84530   sqlite3_release_memory,
84531   sqlite3_result_error_nomem,
84532   sqlite3_result_error_toobig,
84533   sqlite3_sleep,
84534   sqlite3_soft_heap_limit,
84535   sqlite3_vfs_find,
84536   sqlite3_vfs_register,
84537   sqlite3_vfs_unregister,
84538
84539   /*
84540   ** Added for 3.5.8
84541   */
84542   sqlite3_threadsafe,
84543   sqlite3_result_zeroblob,
84544   sqlite3_result_error_code,
84545   sqlite3_test_control,
84546   sqlite3_randomness,
84547   sqlite3_context_db_handle,
84548
84549   /*
84550   ** Added for 3.6.0
84551   */
84552   sqlite3_extended_result_codes,
84553   sqlite3_limit,
84554   sqlite3_next_stmt,
84555   sqlite3_sql,
84556   sqlite3_status,
84557 };
84558
84559 /*
84560 ** Attempt to load an SQLite extension library contained in the file
84561 ** zFile.  The entry point is zProc.  zProc may be 0 in which case a
84562 ** default entry point name (sqlite3_extension_init) is used.  Use
84563 ** of the default name is recommended.
84564 **
84565 ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
84566 **
84567 ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with 
84568 ** error message text.  The calling function should free this memory
84569 ** by calling sqlite3DbFree(db, ).
84570 */
84571 static int sqlite3LoadExtension(
84572   sqlite3 *db,          /* Load the extension into this database connection */
84573   const char *zFile,    /* Name of the shared library containing extension */
84574   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
84575   char **pzErrMsg       /* Put error message here if not 0 */
84576 ){
84577   sqlite3_vfs *pVfs = db->pVfs;
84578   void *handle;
84579   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
84580   char *zErrmsg = 0;
84581   void **aHandle;
84582   const int nMsg = 300;
84583
84584   if( pzErrMsg ) *pzErrMsg = 0;
84585
84586   /* Ticket #1863.  To avoid a creating security problems for older
84587   ** applications that relink against newer versions of SQLite, the
84588   ** ability to run load_extension is turned off by default.  One
84589   ** must call sqlite3_enable_load_extension() to turn on extension
84590   ** loading.  Otherwise you get the following error.
84591   */
84592   if( (db->flags & SQLITE_LoadExtension)==0 ){
84593     if( pzErrMsg ){
84594       *pzErrMsg = sqlite3_mprintf("not authorized");
84595     }
84596     return SQLITE_ERROR;
84597   }
84598
84599   if( zProc==0 ){
84600     zProc = "sqlite3_extension_init";
84601   }
84602
84603   handle = sqlite3OsDlOpen(pVfs, zFile);
84604   if( handle==0 ){
84605     if( pzErrMsg ){
84606       *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
84607       if( zErrmsg ){
84608         sqlite3_snprintf(nMsg, zErrmsg, 
84609             "unable to open shared library [%s]", zFile);
84610         sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
84611       }
84612     }
84613     return SQLITE_ERROR;
84614   }
84615   xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
84616                    sqlite3OsDlSym(pVfs, handle, zProc);
84617   if( xInit==0 ){
84618     if( pzErrMsg ){
84619       *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
84620       if( zErrmsg ){
84621         sqlite3_snprintf(nMsg, zErrmsg,
84622             "no entry point [%s] in shared library [%s]", zProc,zFile);
84623         sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
84624       }
84625       sqlite3OsDlClose(pVfs, handle);
84626     }
84627     return SQLITE_ERROR;
84628   }else if( xInit(db, &zErrmsg, &sqlite3Apis) ){
84629     if( pzErrMsg ){
84630       *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
84631     }
84632     sqlite3_free(zErrmsg);
84633     sqlite3OsDlClose(pVfs, handle);
84634     return SQLITE_ERROR;
84635   }
84636
84637   /* Append the new shared library handle to the db->aExtension array. */
84638   aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
84639   if( aHandle==0 ){
84640     return SQLITE_NOMEM;
84641   }
84642   if( db->nExtension>0 ){
84643     memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
84644   }
84645   sqlite3DbFree(db, db->aExtension);
84646   db->aExtension = aHandle;
84647
84648   db->aExtension[db->nExtension++] = handle;
84649   return SQLITE_OK;
84650 }
84651 SQLITE_API int sqlite3_load_extension(
84652   sqlite3 *db,          /* Load the extension into this database connection */
84653   const char *zFile,    /* Name of the shared library containing extension */
84654   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
84655   char **pzErrMsg       /* Put error message here if not 0 */
84656 ){
84657   int rc;
84658   sqlite3_mutex_enter(db->mutex);
84659   rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
84660   rc = sqlite3ApiExit(db, rc);
84661   sqlite3_mutex_leave(db->mutex);
84662   return rc;
84663 }
84664
84665 /*
84666 ** Call this routine when the database connection is closing in order
84667 ** to clean up loaded extensions
84668 */
84669 SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
84670   int i;
84671   assert( sqlite3_mutex_held(db->mutex) );
84672   for(i=0; i<db->nExtension; i++){
84673     sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
84674   }
84675   sqlite3DbFree(db, db->aExtension);
84676 }
84677
84678 /*
84679 ** Enable or disable extension loading.  Extension loading is disabled by
84680 ** default so as not to open security holes in older applications.
84681 */
84682 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
84683   sqlite3_mutex_enter(db->mutex);
84684   if( onoff ){
84685     db->flags |= SQLITE_LoadExtension;
84686   }else{
84687     db->flags &= ~SQLITE_LoadExtension;
84688   }
84689   sqlite3_mutex_leave(db->mutex);
84690   return SQLITE_OK;
84691 }
84692
84693 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
84694
84695 /*
84696 ** The auto-extension code added regardless of whether or not extension
84697 ** loading is supported.  We need a dummy sqlite3Apis pointer for that
84698 ** code if regular extension loading is not available.  This is that
84699 ** dummy pointer.
84700 */
84701 #ifdef SQLITE_OMIT_LOAD_EXTENSION
84702 static const sqlite3_api_routines sqlite3Apis = { 0 };
84703 #endif
84704
84705
84706 /*
84707 ** The following object holds the list of automatically loaded
84708 ** extensions.
84709 **
84710 ** This list is shared across threads.  The SQLITE_MUTEX_STATIC_MASTER
84711 ** mutex must be held while accessing this list.
84712 */
84713 typedef struct sqlite3AutoExtList sqlite3AutoExtList;
84714 static SQLITE_WSD struct sqlite3AutoExtList {
84715   int nExt;              /* Number of entries in aExt[] */          
84716   void (**aExt)(void);   /* Pointers to the extension init functions */
84717 } sqlite3Autoext = { 0, 0 };
84718
84719 /* The "wsdAutoext" macro will resolve to the autoextension
84720 ** state vector.  If writable static data is unsupported on the target,
84721 ** we have to locate the state vector at run-time.  In the more common
84722 ** case where writable static data is supported, wsdStat can refer directly
84723 ** to the "sqlite3Autoext" state vector declared above.
84724 */
84725 #ifdef SQLITE_OMIT_WSD
84726 # define wsdAutoextInit \
84727   sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
84728 # define wsdAutoext x[0]
84729 #else
84730 # define wsdAutoextInit
84731 # define wsdAutoext sqlite3Autoext
84732 #endif
84733
84734
84735 /*
84736 ** Register a statically linked extension that is automatically
84737 ** loaded by every new database connection.
84738 */
84739 SQLITE_API int sqlite3_auto_extension(void (*xInit)(void)){
84740   int rc = SQLITE_OK;
84741 #ifndef SQLITE_OMIT_AUTOINIT
84742   rc = sqlite3_initialize();
84743   if( rc ){
84744     return rc;
84745   }else
84746 #endif
84747   {
84748     int i;
84749 #if SQLITE_THREADSAFE
84750     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
84751 #endif
84752     wsdAutoextInit;
84753     sqlite3_mutex_enter(mutex);
84754     for(i=0; i<wsdAutoext.nExt; i++){
84755       if( wsdAutoext.aExt[i]==xInit ) break;
84756     }
84757     if( i==wsdAutoext.nExt ){
84758       int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
84759       void (**aNew)(void);
84760       aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
84761       if( aNew==0 ){
84762         rc = SQLITE_NOMEM;
84763       }else{
84764         wsdAutoext.aExt = aNew;
84765         wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
84766         wsdAutoext.nExt++;
84767       }
84768     }
84769     sqlite3_mutex_leave(mutex);
84770     assert( (rc&0xff)==rc );
84771     return rc;
84772   }
84773 }
84774
84775 /*
84776 ** Reset the automatic extension loading mechanism.
84777 */
84778 SQLITE_API void sqlite3_reset_auto_extension(void){
84779 #ifndef SQLITE_OMIT_AUTOINIT
84780   if( sqlite3_initialize()==SQLITE_OK )
84781 #endif
84782   {
84783 #if SQLITE_THREADSAFE
84784     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
84785 #endif
84786     wsdAutoextInit;
84787     sqlite3_mutex_enter(mutex);
84788     sqlite3_free(wsdAutoext.aExt);
84789     wsdAutoext.aExt = 0;
84790     wsdAutoext.nExt = 0;
84791     sqlite3_mutex_leave(mutex);
84792   }
84793 }
84794
84795 /*
84796 ** Load all automatic extensions.
84797 **
84798 ** If anything goes wrong, set an error in the database connection.
84799 */
84800 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
84801   int i;
84802   int go = 1;
84803   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
84804
84805   wsdAutoextInit;
84806   if( wsdAutoext.nExt==0 ){
84807     /* Common case: early out without every having to acquire a mutex */
84808     return;
84809   }
84810   for(i=0; go; i++){
84811     char *zErrmsg;
84812 #if SQLITE_THREADSAFE
84813     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
84814 #endif
84815     sqlite3_mutex_enter(mutex);
84816     if( i>=wsdAutoext.nExt ){
84817       xInit = 0;
84818       go = 0;
84819     }else{
84820       xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
84821               wsdAutoext.aExt[i];
84822     }
84823     sqlite3_mutex_leave(mutex);
84824     zErrmsg = 0;
84825     if( xInit && xInit(db, &zErrmsg, &sqlite3Apis) ){
84826       sqlite3Error(db, SQLITE_ERROR,
84827             "automatic extension loading failed: %s", zErrmsg);
84828       go = 0;
84829     }
84830     sqlite3_free(zErrmsg);
84831   }
84832 }
84833
84834 /************** End of loadext.c *********************************************/
84835 /************** Begin file pragma.c ******************************************/
84836 /*
84837 ** 2003 April 6
84838 **
84839 ** The author disclaims copyright to this source code.  In place of
84840 ** a legal notice, here is a blessing:
84841 **
84842 **    May you do good and not evil.
84843 **    May you find forgiveness for yourself and forgive others.
84844 **    May you share freely, never taking more than you give.
84845 **
84846 *************************************************************************
84847 ** This file contains code used to implement the PRAGMA command.
84848 */
84849
84850 /* Ignore this whole file if pragmas are disabled
84851 */
84852 #if !defined(SQLITE_OMIT_PRAGMA)
84853
84854 /*
84855 ** Interpret the given string as a safety level.  Return 0 for OFF,
84856 ** 1 for ON or NORMAL and 2 for FULL.  Return 1 for an empty or 
84857 ** unrecognized string argument.
84858 **
84859 ** Note that the values returned are one less that the values that
84860 ** should be passed into sqlite3BtreeSetSafetyLevel().  The is done
84861 ** to support legacy SQL code.  The safety level used to be boolean
84862 ** and older scripts may have used numbers 0 for OFF and 1 for ON.
84863 */
84864 static u8 getSafetyLevel(const char *z){
84865                              /* 123456789 123456789 */
84866   static const char zText[] = "onoffalseyestruefull";
84867   static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
84868   static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
84869   static const u8 iValue[] =  {1, 0, 0, 0, 1, 1, 2};
84870   int i, n;
84871   if( sqlite3Isdigit(*z) ){
84872     return (u8)atoi(z);
84873   }
84874   n = sqlite3Strlen30(z);
84875   for(i=0; i<ArraySize(iLength); i++){
84876     if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
84877       return iValue[i];
84878     }
84879   }
84880   return 1;
84881 }
84882
84883 /*
84884 ** Interpret the given string as a boolean value.
84885 */
84886 static u8 getBoolean(const char *z){
84887   return getSafetyLevel(z)&1;
84888 }
84889
84890 /*
84891 ** Interpret the given string as a locking mode value.
84892 */
84893 static int getLockingMode(const char *z){
84894   if( z ){
84895     if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
84896     if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
84897   }
84898   return PAGER_LOCKINGMODE_QUERY;
84899 }
84900
84901 #ifndef SQLITE_OMIT_AUTOVACUUM
84902 /*
84903 ** Interpret the given string as an auto-vacuum mode value.
84904 **
84905 ** The following strings, "none", "full" and "incremental" are 
84906 ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
84907 */
84908 static int getAutoVacuum(const char *z){
84909   int i;
84910   if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
84911   if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
84912   if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
84913   i = atoi(z);
84914   return (u8)((i>=0&&i<=2)?i:0);
84915 }
84916 #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
84917
84918 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
84919 /*
84920 ** Interpret the given string as a temp db location. Return 1 for file
84921 ** backed temporary databases, 2 for the Red-Black tree in memory database
84922 ** and 0 to use the compile-time default.
84923 */
84924 static int getTempStore(const char *z){
84925   if( z[0]>='0' && z[0]<='2' ){
84926     return z[0] - '0';
84927   }else if( sqlite3StrICmp(z, "file")==0 ){
84928     return 1;
84929   }else if( sqlite3StrICmp(z, "memory")==0 ){
84930     return 2;
84931   }else{
84932     return 0;
84933   }
84934 }
84935 #endif /* SQLITE_PAGER_PRAGMAS */
84936
84937 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
84938 /*
84939 ** Invalidate temp storage, either when the temp storage is changed
84940 ** from default, or when 'file' and the temp_store_directory has changed
84941 */
84942 static int invalidateTempStorage(Parse *pParse){
84943   sqlite3 *db = pParse->db;
84944   if( db->aDb[1].pBt!=0 ){
84945     if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
84946       sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
84947         "from within a transaction");
84948       return SQLITE_ERROR;
84949     }
84950     sqlite3BtreeClose(db->aDb[1].pBt);
84951     db->aDb[1].pBt = 0;
84952     sqlite3ResetInternalSchema(db, 0);
84953   }
84954   return SQLITE_OK;
84955 }
84956 #endif /* SQLITE_PAGER_PRAGMAS */
84957
84958 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
84959 /*
84960 ** If the TEMP database is open, close it and mark the database schema
84961 ** as needing reloading.  This must be done when using the SQLITE_TEMP_STORE
84962 ** or DEFAULT_TEMP_STORE pragmas.
84963 */
84964 static int changeTempStorage(Parse *pParse, const char *zStorageType){
84965   int ts = getTempStore(zStorageType);
84966   sqlite3 *db = pParse->db;
84967   if( db->temp_store==ts ) return SQLITE_OK;
84968   if( invalidateTempStorage( pParse ) != SQLITE_OK ){
84969     return SQLITE_ERROR;
84970   }
84971   db->temp_store = (u8)ts;
84972   return SQLITE_OK;
84973 }
84974 #endif /* SQLITE_PAGER_PRAGMAS */
84975
84976 /*
84977 ** Generate code to return a single integer value.
84978 */
84979 static void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){
84980   Vdbe *v = sqlite3GetVdbe(pParse);
84981   int mem = ++pParse->nMem;
84982   i64 *pI64 = sqlite3DbMallocRaw(pParse->db, sizeof(value));
84983   if( pI64 ){
84984     memcpy(pI64, &value, sizeof(value));
84985   }
84986   sqlite3VdbeAddOp4(v, OP_Int64, 0, mem, 0, (char*)pI64, P4_INT64);
84987   sqlite3VdbeSetNumCols(v, 1);
84988   sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
84989   sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
84990 }
84991
84992 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
84993 /*
84994 ** Check to see if zRight and zLeft refer to a pragma that queries
84995 ** or changes one of the flags in db->flags.  Return 1 if so and 0 if not.
84996 ** Also, implement the pragma.
84997 */
84998 static int flagPragma(Parse *pParse, const char *zLeft, const char *zRight){
84999   static const struct sPragmaType {
85000     const char *zName;  /* Name of the pragma */
85001     int mask;           /* Mask for the db->flags value */
85002   } aPragma[] = {
85003     { "full_column_names",        SQLITE_FullColNames  },
85004     { "short_column_names",       SQLITE_ShortColNames },
85005     { "count_changes",            SQLITE_CountRows     },
85006     { "empty_result_callbacks",   SQLITE_NullCallback  },
85007     { "legacy_file_format",       SQLITE_LegacyFileFmt },
85008     { "fullfsync",                SQLITE_FullFSync     },
85009     { "reverse_unordered_selects", SQLITE_ReverseOrder  },
85010 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
85011     { "automatic_index",          SQLITE_AutoIndex     },
85012 #endif
85013 #ifdef SQLITE_DEBUG
85014     { "sql_trace",                SQLITE_SqlTrace      },
85015     { "vdbe_listing",             SQLITE_VdbeListing   },
85016     { "vdbe_trace",               SQLITE_VdbeTrace     },
85017 #endif
85018 #ifndef SQLITE_OMIT_CHECK
85019     { "ignore_check_constraints", SQLITE_IgnoreChecks  },
85020 #endif
85021     /* The following is VERY experimental */
85022     { "writable_schema",          SQLITE_WriteSchema|SQLITE_RecoveryMode },
85023     { "omit_readlock",            SQLITE_NoReadlock    },
85024
85025     /* TODO: Maybe it shouldn't be possible to change the ReadUncommitted
85026     ** flag if there are any active statements. */
85027     { "read_uncommitted",         SQLITE_ReadUncommitted },
85028     { "recursive_triggers",       SQLITE_RecTriggers },
85029
85030     /* This flag may only be set if both foreign-key and trigger support
85031     ** are present in the build.  */
85032 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
85033     { "foreign_keys",             SQLITE_ForeignKeys },
85034 #endif
85035   };
85036   int i;
85037   const struct sPragmaType *p;
85038   for(i=0, p=aPragma; i<ArraySize(aPragma); i++, p++){
85039     if( sqlite3StrICmp(zLeft, p->zName)==0 ){
85040       sqlite3 *db = pParse->db;
85041       Vdbe *v;
85042       v = sqlite3GetVdbe(pParse);
85043       assert( v!=0 );  /* Already allocated by sqlite3Pragma() */
85044       if( ALWAYS(v) ){
85045         if( zRight==0 ){
85046           returnSingleInt(pParse, p->zName, (db->flags & p->mask)!=0 );
85047         }else{
85048           int mask = p->mask;          /* Mask of bits to set or clear. */
85049           if( db->autoCommit==0 ){
85050             /* Foreign key support may not be enabled or disabled while not
85051             ** in auto-commit mode.  */
85052             mask &= ~(SQLITE_ForeignKeys);
85053           }
85054
85055           if( getBoolean(zRight) ){
85056             db->flags |= mask;
85057           }else{
85058             db->flags &= ~mask;
85059           }
85060
85061           /* Many of the flag-pragmas modify the code generated by the SQL 
85062           ** compiler (eg. count_changes). So add an opcode to expire all
85063           ** compiled SQL statements after modifying a pragma value.
85064           */
85065           sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
85066         }
85067       }
85068
85069       return 1;
85070     }
85071   }
85072   return 0;
85073 }
85074 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
85075
85076 /*
85077 ** Return a human-readable name for a constraint resolution action.
85078 */
85079 #ifndef SQLITE_OMIT_FOREIGN_KEY
85080 static const char *actionName(u8 action){
85081   const char *zName;
85082   switch( action ){
85083     case OE_SetNull:  zName = "SET NULL";        break;
85084     case OE_SetDflt:  zName = "SET DEFAULT";     break;
85085     case OE_Cascade:  zName = "CASCADE";         break;
85086     case OE_Restrict: zName = "RESTRICT";        break;
85087     default:          zName = "NO ACTION";  
85088                       assert( action==OE_None ); break;
85089   }
85090   return zName;
85091 }
85092 #endif
85093
85094
85095 /*
85096 ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
85097 ** defined in pager.h. This function returns the associated lowercase
85098 ** journal-mode name.
85099 */
85100 SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
85101   static char * const azModeName[] = {
85102     "delete", "persist", "off", "truncate", "memory"
85103 #ifndef SQLITE_OMIT_WAL
85104      , "wal"
85105 #endif
85106   };
85107   assert( PAGER_JOURNALMODE_DELETE==0 );
85108   assert( PAGER_JOURNALMODE_PERSIST==1 );
85109   assert( PAGER_JOURNALMODE_OFF==2 );
85110   assert( PAGER_JOURNALMODE_TRUNCATE==3 );
85111   assert( PAGER_JOURNALMODE_MEMORY==4 );
85112   assert( PAGER_JOURNALMODE_WAL==5 );
85113   assert( eMode>=0 && eMode<=ArraySize(azModeName) );
85114
85115   if( eMode==ArraySize(azModeName) ) return 0;
85116   return azModeName[eMode];
85117 }
85118
85119 /*
85120 ** Process a pragma statement.  
85121 **
85122 ** Pragmas are of this form:
85123 **
85124 **      PRAGMA [database.]id [= value]
85125 **
85126 ** The identifier might also be a string.  The value is a string, and
85127 ** identifier, or a number.  If minusFlag is true, then the value is
85128 ** a number that was preceded by a minus sign.
85129 **
85130 ** If the left side is "database.id" then pId1 is the database name
85131 ** and pId2 is the id.  If the left side is just "id" then pId1 is the
85132 ** id and pId2 is any empty string.
85133 */
85134 SQLITE_PRIVATE void sqlite3Pragma(
85135   Parse *pParse, 
85136   Token *pId1,        /* First part of [database.]id field */
85137   Token *pId2,        /* Second part of [database.]id field, or NULL */
85138   Token *pValue,      /* Token for <value>, or NULL */
85139   int minusFlag       /* True if a '-' sign preceded <value> */
85140 ){
85141   char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
85142   char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
85143   const char *zDb = 0;   /* The database name */
85144   Token *pId;            /* Pointer to <id> token */
85145   int iDb;               /* Database index for <database> */
85146   sqlite3 *db = pParse->db;
85147   Db *pDb;
85148   Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(db);
85149   if( v==0 ) return;
85150   sqlite3VdbeRunOnlyOnce(v);
85151   pParse->nMem = 2;
85152
85153   /* Interpret the [database.] part of the pragma statement. iDb is the
85154   ** index of the database this pragma is being applied to in db.aDb[]. */
85155   iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
85156   if( iDb<0 ) return;
85157   pDb = &db->aDb[iDb];
85158
85159   /* If the temp database has been explicitly named as part of the 
85160   ** pragma, make sure it is open. 
85161   */
85162   if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
85163     return;
85164   }
85165
85166   zLeft = sqlite3NameFromToken(db, pId);
85167   if( !zLeft ) return;
85168   if( minusFlag ){
85169     zRight = sqlite3MPrintf(db, "-%T", pValue);
85170   }else{
85171     zRight = sqlite3NameFromToken(db, pValue);
85172   }
85173
85174   assert( pId2 );
85175   zDb = pId2->n>0 ? pDb->zName : 0;
85176   if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
85177     goto pragma_out;
85178   }
85179  
85180 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
85181   /*
85182   **  PRAGMA [database.]default_cache_size
85183   **  PRAGMA [database.]default_cache_size=N
85184   **
85185   ** The first form reports the current persistent setting for the
85186   ** page cache size.  The value returned is the maximum number of
85187   ** pages in the page cache.  The second form sets both the current
85188   ** page cache size value and the persistent page cache size value
85189   ** stored in the database file.
85190   **
85191   ** Older versions of SQLite would set the default cache size to a
85192   ** negative number to indicate synchronous=OFF.  These days, synchronous
85193   ** is always on by default regardless of the sign of the default cache
85194   ** size.  But continue to take the absolute value of the default cache
85195   ** size of historical compatibility.
85196   */
85197   if( sqlite3StrICmp(zLeft,"default_cache_size")==0 ){
85198     static const VdbeOpList getCacheSize[] = {
85199       { OP_Transaction, 0, 0,        0},                         /* 0 */
85200       { OP_ReadCookie,  0, 1,        BTREE_DEFAULT_CACHE_SIZE},  /* 1 */
85201       { OP_IfPos,       1, 7,        0},
85202       { OP_Integer,     0, 2,        0},
85203       { OP_Subtract,    1, 2,        1},
85204       { OP_IfPos,       1, 7,        0},
85205       { OP_Integer,     0, 1,        0},                         /* 6 */
85206       { OP_ResultRow,   1, 1,        0},
85207     };
85208     int addr;
85209     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
85210     sqlite3VdbeUsesBtree(v, iDb);
85211     if( !zRight ){
85212       sqlite3VdbeSetNumCols(v, 1);
85213       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
85214       pParse->nMem += 2;
85215       addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
85216       sqlite3VdbeChangeP1(v, addr, iDb);
85217       sqlite3VdbeChangeP1(v, addr+1, iDb);
85218       sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);
85219     }else{
85220       int size = atoi(zRight);
85221       if( size<0 ) size = -size;
85222       sqlite3BeginWriteOperation(pParse, 0, iDb);
85223       sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
85224       sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
85225       pDb->pSchema->cache_size = size;
85226       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
85227     }
85228   }else
85229
85230   /*
85231   **  PRAGMA [database.]page_size
85232   **  PRAGMA [database.]page_size=N
85233   **
85234   ** The first form reports the current setting for the
85235   ** database page size in bytes.  The second form sets the
85236   ** database page size value.  The value can only be set if
85237   ** the database has not yet been created.
85238   */
85239   if( sqlite3StrICmp(zLeft,"page_size")==0 ){
85240     Btree *pBt = pDb->pBt;
85241     assert( pBt!=0 );
85242     if( !zRight ){
85243       int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
85244       returnSingleInt(pParse, "page_size", size);
85245     }else{
85246       /* Malloc may fail when setting the page-size, as there is an internal
85247       ** buffer that the pager module resizes using sqlite3_realloc().
85248       */
85249       db->nextPagesize = atoi(zRight);
85250       if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
85251         db->mallocFailed = 1;
85252       }
85253     }
85254   }else
85255
85256   /*
85257   **  PRAGMA [database.]max_page_count
85258   **  PRAGMA [database.]max_page_count=N
85259   **
85260   ** The first form reports the current setting for the
85261   ** maximum number of pages in the database file.  The 
85262   ** second form attempts to change this setting.  Both
85263   ** forms return the current setting.
85264   */
85265   if( sqlite3StrICmp(zLeft,"max_page_count")==0 ){
85266     Btree *pBt = pDb->pBt;
85267     int newMax = 0;
85268     assert( pBt!=0 );
85269     if( zRight ){
85270       newMax = atoi(zRight);
85271     }
85272     if( ALWAYS(pBt) ){
85273       newMax = sqlite3BtreeMaxPageCount(pBt, newMax);
85274     }
85275     returnSingleInt(pParse, "max_page_count", newMax);
85276   }else
85277
85278   /*
85279   **  PRAGMA [database.]secure_delete
85280   **  PRAGMA [database.]secure_delete=ON/OFF
85281   **
85282   ** The first form reports the current setting for the
85283   ** secure_delete flag.  The second form changes the secure_delete
85284   ** flag setting and reports thenew value.
85285   */
85286   if( sqlite3StrICmp(zLeft,"secure_delete")==0 ){
85287     Btree *pBt = pDb->pBt;
85288     int b = -1;
85289     assert( pBt!=0 );
85290     if( zRight ){
85291       b = getBoolean(zRight);
85292     }
85293     if( pId2->n==0 && b>=0 ){
85294       int ii;
85295       for(ii=0; ii<db->nDb; ii++){
85296         sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
85297       }
85298     }
85299     b = sqlite3BtreeSecureDelete(pBt, b);
85300     returnSingleInt(pParse, "secure_delete", b);
85301   }else
85302
85303   /*
85304   **  PRAGMA [database.]page_count
85305   **
85306   ** Return the number of pages in the specified database.
85307   */
85308   if( sqlite3StrICmp(zLeft,"page_count")==0 ){
85309     int iReg;
85310     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
85311     sqlite3CodeVerifySchema(pParse, iDb);
85312     iReg = ++pParse->nMem;
85313     sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
85314     sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
85315     sqlite3VdbeSetNumCols(v, 1);
85316     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "page_count", SQLITE_STATIC);
85317   }else
85318
85319   /*
85320   **  PRAGMA [database.]locking_mode
85321   **  PRAGMA [database.]locking_mode = (normal|exclusive)
85322   */
85323   if( sqlite3StrICmp(zLeft,"locking_mode")==0 ){
85324     const char *zRet = "normal";
85325     int eMode = getLockingMode(zRight);
85326
85327     if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
85328       /* Simple "PRAGMA locking_mode;" statement. This is a query for
85329       ** the current default locking mode (which may be different to
85330       ** the locking-mode of the main database).
85331       */
85332       eMode = db->dfltLockMode;
85333     }else{
85334       Pager *pPager;
85335       if( pId2->n==0 ){
85336         /* This indicates that no database name was specified as part
85337         ** of the PRAGMA command. In this case the locking-mode must be
85338         ** set on all attached databases, as well as the main db file.
85339         **
85340         ** Also, the sqlite3.dfltLockMode variable is set so that
85341         ** any subsequently attached databases also use the specified
85342         ** locking mode.
85343         */
85344         int ii;
85345         assert(pDb==&db->aDb[0]);
85346         for(ii=2; ii<db->nDb; ii++){
85347           pPager = sqlite3BtreePager(db->aDb[ii].pBt);
85348           sqlite3PagerLockingMode(pPager, eMode);
85349         }
85350         db->dfltLockMode = (u8)eMode;
85351       }
85352       pPager = sqlite3BtreePager(pDb->pBt);
85353       eMode = sqlite3PagerLockingMode(pPager, eMode);
85354     }
85355
85356     assert(eMode==PAGER_LOCKINGMODE_NORMAL||eMode==PAGER_LOCKINGMODE_EXCLUSIVE);
85357     if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
85358       zRet = "exclusive";
85359     }
85360     sqlite3VdbeSetNumCols(v, 1);
85361     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC);
85362     sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
85363     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
85364   }else
85365
85366   /*
85367   **  PRAGMA [database.]journal_mode
85368   **  PRAGMA [database.]journal_mode =
85369   **                      (delete|persist|off|truncate|memory|wal|off)
85370   */
85371   if( sqlite3StrICmp(zLeft,"journal_mode")==0 ){
85372     int eMode;        /* One of the PAGER_JOURNALMODE_XXX symbols */
85373     int ii;           /* Loop counter */
85374
85375     /* Force the schema to be loaded on all databases.  This cases all
85376     ** database files to be opened and the journal_modes set. */
85377     if( sqlite3ReadSchema(pParse) ){
85378       goto pragma_out;
85379     }
85380
85381     sqlite3VdbeSetNumCols(v, 1);
85382     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
85383
85384     if( zRight==0 ){
85385       /* If there is no "=MODE" part of the pragma, do a query for the
85386       ** current mode */
85387       eMode = PAGER_JOURNALMODE_QUERY;
85388     }else{
85389       const char *zMode;
85390       int n = sqlite3Strlen30(zRight);
85391       for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
85392         if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
85393       }
85394       if( !zMode ){
85395         /* If the "=MODE" part does not match any known journal mode,
85396         ** then do a query */
85397         eMode = PAGER_JOURNALMODE_QUERY;
85398       }
85399     }
85400     if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
85401       /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
85402       iDb = 0;
85403       pId2->n = 1;
85404     }
85405     for(ii=db->nDb-1; ii>=0; ii--){
85406       if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
85407         sqlite3VdbeUsesBtree(v, ii);
85408         sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
85409       }
85410     }
85411     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
85412   }else
85413
85414   /*
85415   **  PRAGMA [database.]journal_size_limit
85416   **  PRAGMA [database.]journal_size_limit=N
85417   **
85418   ** Get or set the size limit on rollback journal files.
85419   */
85420   if( sqlite3StrICmp(zLeft,"journal_size_limit")==0 ){
85421     Pager *pPager = sqlite3BtreePager(pDb->pBt);
85422     i64 iLimit = -2;
85423     if( zRight ){
85424       sqlite3Atoi64(zRight, &iLimit, 1000000, SQLITE_UTF8);
85425       if( iLimit<-1 ) iLimit = -1;
85426     }
85427     iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
85428     returnSingleInt(pParse, "journal_size_limit", iLimit);
85429   }else
85430
85431 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
85432
85433   /*
85434   **  PRAGMA [database.]auto_vacuum
85435   **  PRAGMA [database.]auto_vacuum=N
85436   **
85437   ** Get or set the value of the database 'auto-vacuum' parameter.
85438   ** The value is one of:  0 NONE 1 FULL 2 INCREMENTAL
85439   */
85440 #ifndef SQLITE_OMIT_AUTOVACUUM
85441   if( sqlite3StrICmp(zLeft,"auto_vacuum")==0 ){
85442     Btree *pBt = pDb->pBt;
85443     assert( pBt!=0 );
85444     if( sqlite3ReadSchema(pParse) ){
85445       goto pragma_out;
85446     }
85447     if( !zRight ){
85448       int auto_vacuum;
85449       if( ALWAYS(pBt) ){
85450          auto_vacuum = sqlite3BtreeGetAutoVacuum(pBt);
85451       }else{
85452          auto_vacuum = SQLITE_DEFAULT_AUTOVACUUM;
85453       }
85454       returnSingleInt(pParse, "auto_vacuum", auto_vacuum);
85455     }else{
85456       int eAuto = getAutoVacuum(zRight);
85457       assert( eAuto>=0 && eAuto<=2 );
85458       db->nextAutovac = (u8)eAuto;
85459       if( ALWAYS(eAuto>=0) ){
85460         /* Call SetAutoVacuum() to set initialize the internal auto and
85461         ** incr-vacuum flags. This is required in case this connection
85462         ** creates the database file. It is important that it is created
85463         ** as an auto-vacuum capable db.
85464         */
85465         int rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
85466         if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
85467           /* When setting the auto_vacuum mode to either "full" or 
85468           ** "incremental", write the value of meta[6] in the database
85469           ** file. Before writing to meta[6], check that meta[3] indicates
85470           ** that this really is an auto-vacuum capable database.
85471           */
85472           static const VdbeOpList setMeta6[] = {
85473             { OP_Transaction,    0,         1,                 0},    /* 0 */
85474             { OP_ReadCookie,     0,         1,         BTREE_LARGEST_ROOT_PAGE},
85475             { OP_If,             1,         0,                 0},    /* 2 */
85476             { OP_Halt,           SQLITE_OK, OE_Abort,          0},    /* 3 */
85477             { OP_Integer,        0,         1,                 0},    /* 4 */
85478             { OP_SetCookie,      0,         BTREE_INCR_VACUUM, 1},    /* 5 */
85479           };
85480           int iAddr;
85481           iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6);
85482           sqlite3VdbeChangeP1(v, iAddr, iDb);
85483           sqlite3VdbeChangeP1(v, iAddr+1, iDb);
85484           sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
85485           sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
85486           sqlite3VdbeChangeP1(v, iAddr+5, iDb);
85487           sqlite3VdbeUsesBtree(v, iDb);
85488         }
85489       }
85490     }
85491   }else
85492 #endif
85493
85494   /*
85495   **  PRAGMA [database.]incremental_vacuum(N)
85496   **
85497   ** Do N steps of incremental vacuuming on a database.
85498   */
85499 #ifndef SQLITE_OMIT_AUTOVACUUM
85500   if( sqlite3StrICmp(zLeft,"incremental_vacuum")==0 ){
85501     int iLimit, addr;
85502     if( sqlite3ReadSchema(pParse) ){
85503       goto pragma_out;
85504     }
85505     if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
85506       iLimit = 0x7fffffff;
85507     }
85508     sqlite3BeginWriteOperation(pParse, 0, iDb);
85509     sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
85510     addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb);
85511     sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
85512     sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
85513     sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr);
85514     sqlite3VdbeJumpHere(v, addr);
85515   }else
85516 #endif
85517
85518 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
85519   /*
85520   **  PRAGMA [database.]cache_size
85521   **  PRAGMA [database.]cache_size=N
85522   **
85523   ** The first form reports the current local setting for the
85524   ** page cache size.  The local setting can be different from
85525   ** the persistent cache size value that is stored in the database
85526   ** file itself.  The value returned is the maximum number of
85527   ** pages in the page cache.  The second form sets the local
85528   ** page cache size value.  It does not change the persistent
85529   ** cache size stored on the disk so the cache size will revert
85530   ** to its default value when the database is closed and reopened.
85531   ** N should be a positive integer.
85532   */
85533   if( sqlite3StrICmp(zLeft,"cache_size")==0 ){
85534     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
85535     if( !zRight ){
85536       returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
85537     }else{
85538       int size = atoi(zRight);
85539       if( size<0 ) size = -size;
85540       pDb->pSchema->cache_size = size;
85541       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
85542     }
85543   }else
85544
85545   /*
85546   **   PRAGMA temp_store
85547   **   PRAGMA temp_store = "default"|"memory"|"file"
85548   **
85549   ** Return or set the local value of the temp_store flag.  Changing
85550   ** the local value does not make changes to the disk file and the default
85551   ** value will be restored the next time the database is opened.
85552   **
85553   ** Note that it is possible for the library compile-time options to
85554   ** override this setting
85555   */
85556   if( sqlite3StrICmp(zLeft, "temp_store")==0 ){
85557     if( !zRight ){
85558       returnSingleInt(pParse, "temp_store", db->temp_store);
85559     }else{
85560       changeTempStorage(pParse, zRight);
85561     }
85562   }else
85563
85564   /*
85565   **   PRAGMA temp_store_directory
85566   **   PRAGMA temp_store_directory = ""|"directory_name"
85567   **
85568   ** Return or set the local value of the temp_store_directory flag.  Changing
85569   ** the value sets a specific directory to be used for temporary files.
85570   ** Setting to a null string reverts to the default temporary directory search.
85571   ** If temporary directory is changed, then invalidateTempStorage.
85572   **
85573   */
85574   if( sqlite3StrICmp(zLeft, "temp_store_directory")==0 ){
85575     if( !zRight ){
85576       if( sqlite3_temp_directory ){
85577         sqlite3VdbeSetNumCols(v, 1);
85578         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, 
85579             "temp_store_directory", SQLITE_STATIC);
85580         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
85581         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
85582       }
85583     }else{
85584 #ifndef SQLITE_OMIT_WSD
85585       if( zRight[0] ){
85586         int rc;
85587         int res;
85588         rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
85589         if( rc!=SQLITE_OK || res==0 ){
85590           sqlite3ErrorMsg(pParse, "not a writable directory");
85591           goto pragma_out;
85592         }
85593       }
85594       if( SQLITE_TEMP_STORE==0
85595        || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
85596        || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
85597       ){
85598         invalidateTempStorage(pParse);
85599       }
85600       sqlite3_free(sqlite3_temp_directory);
85601       if( zRight[0] ){
85602         sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
85603       }else{
85604         sqlite3_temp_directory = 0;
85605       }
85606 #endif /* SQLITE_OMIT_WSD */
85607     }
85608   }else
85609
85610 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
85611 #  if defined(__APPLE__)
85612 #    define SQLITE_ENABLE_LOCKING_STYLE 1
85613 #  else
85614 #    define SQLITE_ENABLE_LOCKING_STYLE 0
85615 #  endif
85616 #endif
85617 #if SQLITE_ENABLE_LOCKING_STYLE
85618   /*
85619    **   PRAGMA [database.]lock_proxy_file
85620    **   PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
85621    **
85622    ** Return or set the value of the lock_proxy_file flag.  Changing
85623    ** the value sets a specific file to be used for database access locks.
85624    **
85625    */
85626   if( sqlite3StrICmp(zLeft, "lock_proxy_file")==0 ){
85627     if( !zRight ){
85628       Pager *pPager = sqlite3BtreePager(pDb->pBt);
85629       char *proxy_file_path = NULL;
85630       sqlite3_file *pFile = sqlite3PagerFile(pPager);
85631       sqlite3OsFileControl(pFile, SQLITE_GET_LOCKPROXYFILE, 
85632                            &proxy_file_path);
85633       
85634       if( proxy_file_path ){
85635         sqlite3VdbeSetNumCols(v, 1);
85636         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, 
85637                               "lock_proxy_file", SQLITE_STATIC);
85638         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);
85639         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
85640       }
85641     }else{
85642       Pager *pPager = sqlite3BtreePager(pDb->pBt);
85643       sqlite3_file *pFile = sqlite3PagerFile(pPager);
85644       int res;
85645       if( zRight[0] ){
85646         res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, 
85647                                      zRight);
85648       } else {
85649         res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, 
85650                                      NULL);
85651       }
85652       if( res!=SQLITE_OK ){
85653         sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
85654         goto pragma_out;
85655       }
85656     }
85657   }else
85658 #endif /* SQLITE_ENABLE_LOCKING_STYLE */      
85659     
85660   /*
85661   **   PRAGMA [database.]synchronous
85662   **   PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
85663   **
85664   ** Return or set the local value of the synchronous flag.  Changing
85665   ** the local value does not make changes to the disk file and the
85666   ** default value will be restored the next time the database is
85667   ** opened.
85668   */
85669   if( sqlite3StrICmp(zLeft,"synchronous")==0 ){
85670     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
85671     if( !zRight ){
85672       returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
85673     }else{
85674       if( !db->autoCommit ){
85675         sqlite3ErrorMsg(pParse, 
85676             "Safety level may not be changed inside a transaction");
85677       }else{
85678         pDb->safety_level = getSafetyLevel(zRight)+1;
85679       }
85680     }
85681   }else
85682 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
85683
85684 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
85685   if( flagPragma(pParse, zLeft, zRight) ){
85686     /* The flagPragma() subroutine also generates any necessary code
85687     ** there is nothing more to do here */
85688   }else
85689 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
85690
85691 #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
85692   /*
85693   **   PRAGMA table_info(<table>)
85694   **
85695   ** Return a single row for each column of the named table. The columns of
85696   ** the returned data set are:
85697   **
85698   ** cid:        Column id (numbered from left to right, starting at 0)
85699   ** name:       Column name
85700   ** type:       Column declaration type.
85701   ** notnull:    True if 'NOT NULL' is part of column declaration
85702   ** dflt_value: The default value for the column, if any.
85703   */
85704   if( sqlite3StrICmp(zLeft, "table_info")==0 && zRight ){
85705     Table *pTab;
85706     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
85707     pTab = sqlite3FindTable(db, zRight, zDb);
85708     if( pTab ){
85709       int i;
85710       int nHidden = 0;
85711       Column *pCol;
85712       sqlite3VdbeSetNumCols(v, 6);
85713       pParse->nMem = 6;
85714       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC);
85715       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
85716       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC);
85717       sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC);
85718       sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC);
85719       sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC);
85720       sqlite3ViewGetColumnNames(pParse, pTab);
85721       for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
85722         if( IsHiddenColumn(pCol) ){
85723           nHidden++;
85724           continue;
85725         }
85726         sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
85727         sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
85728         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
85729            pCol->zType ? pCol->zType : "", 0);
85730         sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
85731         if( pCol->zDflt ){
85732           sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pCol->zDflt, 0);
85733         }else{
85734           sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
85735         }
85736         sqlite3VdbeAddOp2(v, OP_Integer, pCol->isPrimKey, 6);
85737         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
85738       }
85739     }
85740   }else
85741
85742   if( sqlite3StrICmp(zLeft, "index_info")==0 && zRight ){
85743     Index *pIdx;
85744     Table *pTab;
85745     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
85746     pIdx = sqlite3FindIndex(db, zRight, zDb);
85747     if( pIdx ){
85748       int i;
85749       pTab = pIdx->pTable;
85750       sqlite3VdbeSetNumCols(v, 3);
85751       pParse->nMem = 3;
85752       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC);
85753       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC);
85754       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC);
85755       for(i=0; i<pIdx->nColumn; i++){
85756         int cnum = pIdx->aiColumn[i];
85757         sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
85758         sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
85759         assert( pTab->nCol>cnum );
85760         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
85761         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
85762       }
85763     }
85764   }else
85765
85766   if( sqlite3StrICmp(zLeft, "index_list")==0 && zRight ){
85767     Index *pIdx;
85768     Table *pTab;
85769     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
85770     pTab = sqlite3FindTable(db, zRight, zDb);
85771     if( pTab ){
85772       v = sqlite3GetVdbe(pParse);
85773       pIdx = pTab->pIndex;
85774       if( pIdx ){
85775         int i = 0; 
85776         sqlite3VdbeSetNumCols(v, 3);
85777         pParse->nMem = 3;
85778         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
85779         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
85780         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
85781         while(pIdx){
85782           sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
85783           sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
85784           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3);
85785           sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
85786           ++i;
85787           pIdx = pIdx->pNext;
85788         }
85789       }
85790     }
85791   }else
85792
85793   if( sqlite3StrICmp(zLeft, "database_list")==0 ){
85794     int i;
85795     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
85796     sqlite3VdbeSetNumCols(v, 3);
85797     pParse->nMem = 3;
85798     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
85799     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
85800     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC);
85801     for(i=0; i<db->nDb; i++){
85802       if( db->aDb[i].pBt==0 ) continue;
85803       assert( db->aDb[i].zName!=0 );
85804       sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
85805       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
85806       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
85807            sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
85808       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
85809     }
85810   }else
85811
85812   if( sqlite3StrICmp(zLeft, "collation_list")==0 ){
85813     int i = 0;
85814     HashElem *p;
85815     sqlite3VdbeSetNumCols(v, 2);
85816     pParse->nMem = 2;
85817     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
85818     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
85819     for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
85820       CollSeq *pColl = (CollSeq *)sqliteHashData(p);
85821       sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
85822       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
85823       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
85824     }
85825   }else
85826 #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
85827
85828 #ifndef SQLITE_OMIT_FOREIGN_KEY
85829   if( sqlite3StrICmp(zLeft, "foreign_key_list")==0 && zRight ){
85830     FKey *pFK;
85831     Table *pTab;
85832     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
85833     pTab = sqlite3FindTable(db, zRight, zDb);
85834     if( pTab ){
85835       v = sqlite3GetVdbe(pParse);
85836       pFK = pTab->pFKey;
85837       if( pFK ){
85838         int i = 0; 
85839         sqlite3VdbeSetNumCols(v, 8);
85840         pParse->nMem = 8;
85841         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC);
85842         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC);
85843         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC);
85844         sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC);
85845         sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC);
85846         sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC);
85847         sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC);
85848         sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC);
85849         while(pFK){
85850           int j;
85851           for(j=0; j<pFK->nCol; j++){
85852             char *zCol = pFK->aCol[j].zCol;
85853             char *zOnDelete = (char *)actionName(pFK->aAction[0]);
85854             char *zOnUpdate = (char *)actionName(pFK->aAction[1]);
85855             sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
85856             sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
85857             sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
85858             sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
85859                               pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
85860             sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
85861             sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
85862             sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
85863             sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
85864             sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
85865           }
85866           ++i;
85867           pFK = pFK->pNextFrom;
85868         }
85869       }
85870     }
85871   }else
85872 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
85873
85874 #ifndef NDEBUG
85875   if( sqlite3StrICmp(zLeft, "parser_trace")==0 ){
85876     if( zRight ){
85877       if( getBoolean(zRight) ){
85878         sqlite3ParserTrace(stderr, "parser: ");
85879       }else{
85880         sqlite3ParserTrace(0, 0);
85881       }
85882     }
85883   }else
85884 #endif
85885
85886   /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
85887   ** used will be case sensitive or not depending on the RHS.
85888   */
85889   if( sqlite3StrICmp(zLeft, "case_sensitive_like")==0 ){
85890     if( zRight ){
85891       sqlite3RegisterLikeFunctions(db, getBoolean(zRight));
85892     }
85893   }else
85894
85895 #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
85896 # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
85897 #endif
85898
85899 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
85900   /* Pragma "quick_check" is an experimental reduced version of 
85901   ** integrity_check designed to detect most database corruption
85902   ** without most of the overhead of a full integrity-check.
85903   */
85904   if( sqlite3StrICmp(zLeft, "integrity_check")==0
85905    || sqlite3StrICmp(zLeft, "quick_check")==0 
85906   ){
85907     int i, j, addr, mxErr;
85908
85909     /* Code that appears at the end of the integrity check.  If no error
85910     ** messages have been generated, output OK.  Otherwise output the
85911     ** error message
85912     */
85913     static const VdbeOpList endCode[] = {
85914       { OP_AddImm,      1, 0,        0},    /* 0 */
85915       { OP_IfNeg,       1, 0,        0},    /* 1 */
85916       { OP_String8,     0, 3,        0},    /* 2 */
85917       { OP_ResultRow,   3, 1,        0},
85918     };
85919
85920     int isQuick = (zLeft[0]=='q');
85921
85922     /* Initialize the VDBE program */
85923     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
85924     pParse->nMem = 6;
85925     sqlite3VdbeSetNumCols(v, 1);
85926     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC);
85927
85928     /* Set the maximum error count */
85929     mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
85930     if( zRight ){
85931       mxErr = atoi(zRight);
85932       if( mxErr<=0 ){
85933         mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
85934       }
85935     }
85936     sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1);  /* reg[1] holds errors left */
85937
85938     /* Do an integrity check on each database file */
85939     for(i=0; i<db->nDb; i++){
85940       HashElem *x;
85941       Hash *pTbls;
85942       int cnt = 0;
85943
85944       if( OMIT_TEMPDB && i==1 ) continue;
85945
85946       sqlite3CodeVerifySchema(pParse, i);
85947       addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
85948       sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
85949       sqlite3VdbeJumpHere(v, addr);
85950
85951       /* Do an integrity check of the B-Tree
85952       **
85953       ** Begin by filling registers 2, 3, ... with the root pages numbers
85954       ** for all tables and indices in the database.
85955       */
85956       pTbls = &db->aDb[i].pSchema->tblHash;
85957       for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
85958         Table *pTab = sqliteHashData(x);
85959         Index *pIdx;
85960         sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
85961         cnt++;
85962         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
85963           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
85964           cnt++;
85965         }
85966       }
85967
85968       /* Make sure sufficient number of registers have been allocated */
85969       if( pParse->nMem < cnt+4 ){
85970         pParse->nMem = cnt+4;
85971       }
85972
85973       /* Do the b-tree integrity checks */
85974       sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
85975       sqlite3VdbeChangeP5(v, (u8)i);
85976       addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2);
85977       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
85978          sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
85979          P4_DYNAMIC);
85980       sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
85981       sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
85982       sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
85983       sqlite3VdbeJumpHere(v, addr);
85984
85985       /* Make sure all the indices are constructed correctly.
85986       */
85987       for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
85988         Table *pTab = sqliteHashData(x);
85989         Index *pIdx;
85990         int loopTop;
85991
85992         if( pTab->pIndex==0 ) continue;
85993         addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);  /* Stop if out of errors */
85994         sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
85995         sqlite3VdbeJumpHere(v, addr);
85996         sqlite3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead);
85997         sqlite3VdbeAddOp2(v, OP_Integer, 0, 2);  /* reg(2) will count entries */
85998         loopTop = sqlite3VdbeAddOp2(v, OP_Rewind, 1, 0);
85999         sqlite3VdbeAddOp2(v, OP_AddImm, 2, 1);   /* increment entry count */
86000         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
86001           int jmp2;
86002           int r1;
86003           static const VdbeOpList idxErr[] = {
86004             { OP_AddImm,      1, -1,  0},
86005             { OP_String8,     0,  3,  0},    /* 1 */
86006             { OP_Rowid,       1,  4,  0},
86007             { OP_String8,     0,  5,  0},    /* 3 */
86008             { OP_String8,     0,  6,  0},    /* 4 */
86009             { OP_Concat,      4,  3,  3},
86010             { OP_Concat,      5,  3,  3},
86011             { OP_Concat,      6,  3,  3},
86012             { OP_ResultRow,   3,  1,  0},
86013             { OP_IfPos,       1,  0,  0},    /* 9 */
86014             { OP_Halt,        0,  0,  0},
86015           };
86016           r1 = sqlite3GenerateIndexKey(pParse, pIdx, 1, 3, 0);
86017           jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, j+2, 0, r1, pIdx->nColumn+1);
86018           addr = sqlite3VdbeAddOpList(v, ArraySize(idxErr), idxErr);
86019           sqlite3VdbeChangeP4(v, addr+1, "rowid ", P4_STATIC);
86020           sqlite3VdbeChangeP4(v, addr+3, " missing from index ", P4_STATIC);
86021           sqlite3VdbeChangeP4(v, addr+4, pIdx->zName, P4_STATIC);
86022           sqlite3VdbeJumpHere(v, addr+9);
86023           sqlite3VdbeJumpHere(v, jmp2);
86024         }
86025         sqlite3VdbeAddOp2(v, OP_Next, 1, loopTop+1);
86026         sqlite3VdbeJumpHere(v, loopTop);
86027         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
86028           static const VdbeOpList cntIdx[] = {
86029              { OP_Integer,      0,  3,  0},
86030              { OP_Rewind,       0,  0,  0},  /* 1 */
86031              { OP_AddImm,       3,  1,  0},
86032              { OP_Next,         0,  0,  0},  /* 3 */
86033              { OP_Eq,           2,  0,  3},  /* 4 */
86034              { OP_AddImm,       1, -1,  0},
86035              { OP_String8,      0,  2,  0},  /* 6 */
86036              { OP_String8,      0,  3,  0},  /* 7 */
86037              { OP_Concat,       3,  2,  2},
86038              { OP_ResultRow,    2,  1,  0},
86039           };
86040           addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);
86041           sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
86042           sqlite3VdbeJumpHere(v, addr);
86043           addr = sqlite3VdbeAddOpList(v, ArraySize(cntIdx), cntIdx);
86044           sqlite3VdbeChangeP1(v, addr+1, j+2);
86045           sqlite3VdbeChangeP2(v, addr+1, addr+4);
86046           sqlite3VdbeChangeP1(v, addr+3, j+2);
86047           sqlite3VdbeChangeP2(v, addr+3, addr+2);
86048           sqlite3VdbeJumpHere(v, addr+4);
86049           sqlite3VdbeChangeP4(v, addr+6, 
86050                      "wrong # of entries in index ", P4_STATIC);
86051           sqlite3VdbeChangeP4(v, addr+7, pIdx->zName, P4_STATIC);
86052         }
86053       } 
86054     }
86055     addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode);
86056     sqlite3VdbeChangeP2(v, addr, -mxErr);
86057     sqlite3VdbeJumpHere(v, addr+1);
86058     sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
86059   }else
86060 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
86061
86062 #ifndef SQLITE_OMIT_UTF16
86063   /*
86064   **   PRAGMA encoding
86065   **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
86066   **
86067   ** In its first form, this pragma returns the encoding of the main
86068   ** database. If the database is not initialized, it is initialized now.
86069   **
86070   ** The second form of this pragma is a no-op if the main database file
86071   ** has not already been initialized. In this case it sets the default
86072   ** encoding that will be used for the main database file if a new file
86073   ** is created. If an existing main database file is opened, then the
86074   ** default text encoding for the existing database is used.
86075   ** 
86076   ** In all cases new databases created using the ATTACH command are
86077   ** created to use the same default text encoding as the main database. If
86078   ** the main database has not been initialized and/or created when ATTACH
86079   ** is executed, this is done before the ATTACH operation.
86080   **
86081   ** In the second form this pragma sets the text encoding to be used in
86082   ** new database files created using this database handle. It is only
86083   ** useful if invoked immediately after the main database i
86084   */
86085   if( sqlite3StrICmp(zLeft, "encoding")==0 ){
86086     static const struct EncName {
86087       char *zName;
86088       u8 enc;
86089     } encnames[] = {
86090       { "UTF8",     SQLITE_UTF8        },
86091       { "UTF-8",    SQLITE_UTF8        },  /* Must be element [1] */
86092       { "UTF-16le", SQLITE_UTF16LE     },  /* Must be element [2] */
86093       { "UTF-16be", SQLITE_UTF16BE     },  /* Must be element [3] */
86094       { "UTF16le",  SQLITE_UTF16LE     },
86095       { "UTF16be",  SQLITE_UTF16BE     },
86096       { "UTF-16",   0                  }, /* SQLITE_UTF16NATIVE */
86097       { "UTF16",    0                  }, /* SQLITE_UTF16NATIVE */
86098       { 0, 0 }
86099     };
86100     const struct EncName *pEnc;
86101     if( !zRight ){    /* "PRAGMA encoding" */
86102       if( sqlite3ReadSchema(pParse) ) goto pragma_out;
86103       sqlite3VdbeSetNumCols(v, 1);
86104       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC);
86105       sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
86106       assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
86107       assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
86108       assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
86109       sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);
86110       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
86111     }else{                        /* "PRAGMA encoding = XXX" */
86112       /* Only change the value of sqlite.enc if the database handle is not
86113       ** initialized. If the main database exists, the new sqlite.enc value
86114       ** will be overwritten when the schema is next loaded. If it does not
86115       ** already exists, it will be created to use the new encoding value.
86116       */
86117       if( 
86118         !(DbHasProperty(db, 0, DB_SchemaLoaded)) || 
86119         DbHasProperty(db, 0, DB_Empty) 
86120       ){
86121         for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
86122           if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
86123             ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
86124             break;
86125           }
86126         }
86127         if( !pEnc->zName ){
86128           sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
86129         }
86130       }
86131     }
86132   }else
86133 #endif /* SQLITE_OMIT_UTF16 */
86134
86135 #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
86136   /*
86137   **   PRAGMA [database.]schema_version
86138   **   PRAGMA [database.]schema_version = <integer>
86139   **
86140   **   PRAGMA [database.]user_version
86141   **   PRAGMA [database.]user_version = <integer>
86142   **
86143   ** The pragma's schema_version and user_version are used to set or get
86144   ** the value of the schema-version and user-version, respectively. Both
86145   ** the schema-version and the user-version are 32-bit signed integers
86146   ** stored in the database header.
86147   **
86148   ** The schema-cookie is usually only manipulated internally by SQLite. It
86149   ** is incremented by SQLite whenever the database schema is modified (by
86150   ** creating or dropping a table or index). The schema version is used by
86151   ** SQLite each time a query is executed to ensure that the internal cache
86152   ** of the schema used when compiling the SQL query matches the schema of
86153   ** the database against which the compiled query is actually executed.
86154   ** Subverting this mechanism by using "PRAGMA schema_version" to modify
86155   ** the schema-version is potentially dangerous and may lead to program
86156   ** crashes or database corruption. Use with caution!
86157   **
86158   ** The user-version is not used internally by SQLite. It may be used by
86159   ** applications for any purpose.
86160   */
86161   if( sqlite3StrICmp(zLeft, "schema_version")==0 
86162    || sqlite3StrICmp(zLeft, "user_version")==0 
86163    || sqlite3StrICmp(zLeft, "freelist_count")==0 
86164   ){
86165     int iCookie;   /* Cookie index. 1 for schema-cookie, 6 for user-cookie. */
86166     sqlite3VdbeUsesBtree(v, iDb);
86167     switch( zLeft[0] ){
86168       case 'f': case 'F':
86169         iCookie = BTREE_FREE_PAGE_COUNT;
86170         break;
86171       case 's': case 'S':
86172         iCookie = BTREE_SCHEMA_VERSION;
86173         break;
86174       default:
86175         iCookie = BTREE_USER_VERSION;
86176         break;
86177     }
86178
86179     if( zRight && iCookie!=BTREE_FREE_PAGE_COUNT ){
86180       /* Write the specified cookie value */
86181       static const VdbeOpList setCookie[] = {
86182         { OP_Transaction,    0,  1,  0},    /* 0 */
86183         { OP_Integer,        0,  1,  0},    /* 1 */
86184         { OP_SetCookie,      0,  0,  1},    /* 2 */
86185       };
86186       int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie);
86187       sqlite3VdbeChangeP1(v, addr, iDb);
86188       sqlite3VdbeChangeP1(v, addr+1, atoi(zRight));
86189       sqlite3VdbeChangeP1(v, addr+2, iDb);
86190       sqlite3VdbeChangeP2(v, addr+2, iCookie);
86191     }else{
86192       /* Read the specified cookie value */
86193       static const VdbeOpList readCookie[] = {
86194         { OP_Transaction,     0,  0,  0},    /* 0 */
86195         { OP_ReadCookie,      0,  1,  0},    /* 1 */
86196         { OP_ResultRow,       1,  1,  0}
86197       };
86198       int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie);
86199       sqlite3VdbeChangeP1(v, addr, iDb);
86200       sqlite3VdbeChangeP1(v, addr+1, iDb);
86201       sqlite3VdbeChangeP3(v, addr+1, iCookie);
86202       sqlite3VdbeSetNumCols(v, 1);
86203       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
86204     }
86205   }else
86206 #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
86207
86208 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
86209   /*
86210   **   PRAGMA compile_options
86211   **
86212   ** Return the names of all compile-time options used in this build,
86213   ** one option per row.
86214   */
86215   if( sqlite3StrICmp(zLeft, "compile_options")==0 ){
86216     int i = 0;
86217     const char *zOpt;
86218     sqlite3VdbeSetNumCols(v, 1);
86219     pParse->nMem = 1;
86220     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "compile_option", SQLITE_STATIC);
86221     while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
86222       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zOpt, 0);
86223       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
86224     }
86225   }else
86226 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
86227
86228 #ifndef SQLITE_OMIT_WAL
86229   /*
86230   **   PRAGMA [database.]wal_checkpoint
86231   **
86232   ** Checkpoint the database.
86233   */
86234   if( sqlite3StrICmp(zLeft, "wal_checkpoint")==0 ){
86235     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
86236     sqlite3VdbeAddOp3(v, OP_Checkpoint, pId2->z?iDb:SQLITE_MAX_ATTACHED, 0, 0);
86237   }else
86238
86239   /*
86240   **   PRAGMA wal_autocheckpoint
86241   **   PRAGMA wal_autocheckpoint = N
86242   **
86243   ** Configure a database connection to automatically checkpoint a database
86244   ** after accumulating N frames in the log. Or query for the current value
86245   ** of N.
86246   */
86247   if( sqlite3StrICmp(zLeft, "wal_autocheckpoint")==0 ){
86248     if( zRight ){
86249       int nAuto = atoi(zRight);
86250       sqlite3_wal_autocheckpoint(db, nAuto);
86251     }
86252     returnSingleInt(pParse, "wal_autocheckpoint", 
86253        db->xWalCallback==sqlite3WalDefaultHook ? 
86254            SQLITE_PTR_TO_INT(db->pWalArg) : 0);
86255   }else
86256 #endif
86257
86258 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
86259   /*
86260   ** Report the current state of file logs for all databases
86261   */
86262   if( sqlite3StrICmp(zLeft, "lock_status")==0 ){
86263     static const char *const azLockName[] = {
86264       "unlocked", "shared", "reserved", "pending", "exclusive"
86265     };
86266     int i;
86267     sqlite3VdbeSetNumCols(v, 2);
86268     pParse->nMem = 2;
86269     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC);
86270     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC);
86271     for(i=0; i<db->nDb; i++){
86272       Btree *pBt;
86273       Pager *pPager;
86274       const char *zState = "unknown";
86275       int j;
86276       if( db->aDb[i].zName==0 ) continue;
86277       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
86278       pBt = db->aDb[i].pBt;
86279       if( pBt==0 || (pPager = sqlite3BtreePager(pBt))==0 ){
86280         zState = "closed";
86281       }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0, 
86282                                      SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
86283          zState = azLockName[j];
86284       }
86285       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
86286       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
86287     }
86288
86289   }else
86290 #endif
86291
86292 #ifdef SQLITE_HAS_CODEC
86293   if( sqlite3StrICmp(zLeft, "key")==0 && zRight ){
86294     sqlite3_key(db, zRight, sqlite3Strlen30(zRight));
86295   }else
86296   if( sqlite3StrICmp(zLeft, "rekey")==0 && zRight ){
86297     sqlite3_rekey(db, zRight, sqlite3Strlen30(zRight));
86298   }else
86299   if( zRight && (sqlite3StrICmp(zLeft, "hexkey")==0 ||
86300                  sqlite3StrICmp(zLeft, "hexrekey")==0) ){
86301     int i, h1, h2;
86302     char zKey[40];
86303     for(i=0; (h1 = zRight[i])!=0 && (h2 = zRight[i+1])!=0; i+=2){
86304       h1 += 9*(1&(h1>>6));
86305       h2 += 9*(1&(h2>>6));
86306       zKey[i/2] = (h2 & 0x0f) | ((h1 & 0xf)<<4);
86307     }
86308     if( (zLeft[3] & 0xf)==0xb ){
86309       sqlite3_key(db, zKey, i/2);
86310     }else{
86311       sqlite3_rekey(db, zKey, i/2);
86312     }
86313   }else
86314 #endif
86315 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
86316   if( sqlite3StrICmp(zLeft, "activate_extensions")==0 ){
86317 #ifdef SQLITE_HAS_CODEC
86318     if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
86319       sqlite3_activate_see(&zRight[4]);
86320     }
86321 #endif
86322 #ifdef SQLITE_ENABLE_CEROD
86323     if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
86324       sqlite3_activate_cerod(&zRight[6]);
86325     }
86326 #endif
86327   }else
86328 #endif
86329
86330  
86331   {/* Empty ELSE clause */}
86332
86333   /*
86334   ** Reset the safety level, in case the fullfsync flag or synchronous
86335   ** setting changed.
86336   */
86337 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
86338   if( db->autoCommit ){
86339     sqlite3BtreeSetSafetyLevel(pDb->pBt, pDb->safety_level,
86340                (db->flags&SQLITE_FullFSync)!=0);
86341   }
86342 #endif
86343 pragma_out:
86344   sqlite3DbFree(db, zLeft);
86345   sqlite3DbFree(db, zRight);
86346 }
86347
86348 #endif /* SQLITE_OMIT_PRAGMA */
86349
86350 /************** End of pragma.c **********************************************/
86351 /************** Begin file prepare.c *****************************************/
86352 /*
86353 ** 2005 May 25
86354 **
86355 ** The author disclaims copyright to this source code.  In place of
86356 ** a legal notice, here is a blessing:
86357 **
86358 **    May you do good and not evil.
86359 **    May you find forgiveness for yourself and forgive others.
86360 **    May you share freely, never taking more than you give.
86361 **
86362 *************************************************************************
86363 ** This file contains the implementation of the sqlite3_prepare()
86364 ** interface, and routines that contribute to loading the database schema
86365 ** from disk.
86366 */
86367
86368 /*
86369 ** Fill the InitData structure with an error message that indicates
86370 ** that the database is corrupt.
86371 */
86372 static void corruptSchema(
86373   InitData *pData,     /* Initialization context */
86374   const char *zObj,    /* Object being parsed at the point of error */
86375   const char *zExtra   /* Error information */
86376 ){
86377   sqlite3 *db = pData->db;
86378   if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
86379     if( zObj==0 ) zObj = "?";
86380     sqlite3SetString(pData->pzErrMsg, db,
86381       "malformed database schema (%s)", zObj);
86382     if( zExtra ){
86383       *pData->pzErrMsg = sqlite3MAppendf(db, *pData->pzErrMsg, 
86384                                  "%s - %s", *pData->pzErrMsg, zExtra);
86385     }
86386   }
86387   pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT;
86388 }
86389
86390 /*
86391 ** This is the callback routine for the code that initializes the
86392 ** database.  See sqlite3Init() below for additional information.
86393 ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
86394 **
86395 ** Each callback contains the following information:
86396 **
86397 **     argv[0] = name of thing being created
86398 **     argv[1] = root page number for table or index. 0 for trigger or view.
86399 **     argv[2] = SQL text for the CREATE statement.
86400 **
86401 */
86402 SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
86403   InitData *pData = (InitData*)pInit;
86404   sqlite3 *db = pData->db;
86405   int iDb = pData->iDb;
86406
86407   assert( argc==3 );
86408   UNUSED_PARAMETER2(NotUsed, argc);
86409   assert( sqlite3_mutex_held(db->mutex) );
86410   DbClearProperty(db, iDb, DB_Empty);
86411   if( db->mallocFailed ){
86412     corruptSchema(pData, argv[0], 0);
86413     return 1;
86414   }
86415
86416   assert( iDb>=0 && iDb<db->nDb );
86417   if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
86418   if( argv[1]==0 ){
86419     corruptSchema(pData, argv[0], 0);
86420   }else if( argv[2] && argv[2][0] ){
86421     /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
86422     ** But because db->init.busy is set to 1, no VDBE code is generated
86423     ** or executed.  All the parser does is build the internal data
86424     ** structures that describe the table, index, or view.
86425     */
86426     int rc;
86427     sqlite3_stmt *pStmt;
86428     TESTONLY(int rcp);            /* Return code from sqlite3_prepare() */
86429
86430     assert( db->init.busy );
86431     db->init.iDb = iDb;
86432     db->init.newTnum = atoi(argv[1]);
86433     db->init.orphanTrigger = 0;
86434     TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
86435     rc = db->errCode;
86436     assert( (rc&0xFF)==(rcp&0xFF) );
86437     db->init.iDb = 0;
86438     if( SQLITE_OK!=rc ){
86439       if( db->init.orphanTrigger ){
86440         assert( iDb==1 );
86441       }else{
86442         pData->rc = rc;
86443         if( rc==SQLITE_NOMEM ){
86444           db->mallocFailed = 1;
86445         }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
86446           corruptSchema(pData, argv[0], sqlite3_errmsg(db));
86447         }
86448       }
86449     }
86450     sqlite3_finalize(pStmt);
86451   }else if( argv[0]==0 ){
86452     corruptSchema(pData, 0, 0);
86453   }else{
86454     /* If the SQL column is blank it means this is an index that
86455     ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
86456     ** constraint for a CREATE TABLE.  The index should have already
86457     ** been created when we processed the CREATE TABLE.  All we have
86458     ** to do here is record the root page number for that index.
86459     */
86460     Index *pIndex;
86461     pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
86462     if( pIndex==0 ){
86463       /* This can occur if there exists an index on a TEMP table which
86464       ** has the same name as another index on a permanent index.  Since
86465       ** the permanent table is hidden by the TEMP table, we can also
86466       ** safely ignore the index on the permanent table.
86467       */
86468       /* Do Nothing */;
86469     }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
86470       corruptSchema(pData, argv[0], "invalid rootpage");
86471     }
86472   }
86473   return 0;
86474 }
86475
86476 /*
86477 ** Attempt to read the database schema and initialize internal
86478 ** data structures for a single database file.  The index of the
86479 ** database file is given by iDb.  iDb==0 is used for the main
86480 ** database.  iDb==1 should never be used.  iDb>=2 is used for
86481 ** auxiliary databases.  Return one of the SQLITE_ error codes to
86482 ** indicate success or failure.
86483 */
86484 static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
86485   int rc;
86486   int i;
86487   int size;
86488   Table *pTab;
86489   Db *pDb;
86490   char const *azArg[4];
86491   int meta[5];
86492   InitData initData;
86493   char const *zMasterSchema;
86494   char const *zMasterName = SCHEMA_TABLE(iDb);
86495   int openedTransaction = 0;
86496
86497   /*
86498   ** The master database table has a structure like this
86499   */
86500   static const char master_schema[] = 
86501      "CREATE TABLE sqlite_master(\n"
86502      "  type text,\n"
86503      "  name text,\n"
86504      "  tbl_name text,\n"
86505      "  rootpage integer,\n"
86506      "  sql text\n"
86507      ")"
86508   ;
86509 #ifndef SQLITE_OMIT_TEMPDB
86510   static const char temp_master_schema[] = 
86511      "CREATE TEMP TABLE sqlite_temp_master(\n"
86512      "  type text,\n"
86513      "  name text,\n"
86514      "  tbl_name text,\n"
86515      "  rootpage integer,\n"
86516      "  sql text\n"
86517      ")"
86518   ;
86519 #else
86520   #define temp_master_schema 0
86521 #endif
86522
86523   assert( iDb>=0 && iDb<db->nDb );
86524   assert( db->aDb[iDb].pSchema );
86525   assert( sqlite3_mutex_held(db->mutex) );
86526   assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
86527
86528   /* zMasterSchema and zInitScript are set to point at the master schema
86529   ** and initialisation script appropriate for the database being
86530   ** initialised. zMasterName is the name of the master table.
86531   */
86532   if( !OMIT_TEMPDB && iDb==1 ){
86533     zMasterSchema = temp_master_schema;
86534   }else{
86535     zMasterSchema = master_schema;
86536   }
86537   zMasterName = SCHEMA_TABLE(iDb);
86538
86539   /* Construct the schema tables.  */
86540   azArg[0] = zMasterName;
86541   azArg[1] = "1";
86542   azArg[2] = zMasterSchema;
86543   azArg[3] = 0;
86544   initData.db = db;
86545   initData.iDb = iDb;
86546   initData.rc = SQLITE_OK;
86547   initData.pzErrMsg = pzErrMsg;
86548   sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
86549   if( initData.rc ){
86550     rc = initData.rc;
86551     goto error_out;
86552   }
86553   pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
86554   if( ALWAYS(pTab) ){
86555     pTab->tabFlags |= TF_Readonly;
86556   }
86557
86558   /* Create a cursor to hold the database open
86559   */
86560   pDb = &db->aDb[iDb];
86561   if( pDb->pBt==0 ){
86562     if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
86563       DbSetProperty(db, 1, DB_SchemaLoaded);
86564     }
86565     return SQLITE_OK;
86566   }
86567
86568   /* If there is not already a read-only (or read-write) transaction opened
86569   ** on the b-tree database, open one now. If a transaction is opened, it 
86570   ** will be closed before this function returns.  */
86571   sqlite3BtreeEnter(pDb->pBt);
86572   if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
86573     rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
86574     if( rc!=SQLITE_OK ){
86575       sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
86576       goto initone_error_out;
86577     }
86578     openedTransaction = 1;
86579   }
86580
86581   /* Get the database meta information.
86582   **
86583   ** Meta values are as follows:
86584   **    meta[0]   Schema cookie.  Changes with each schema change.
86585   **    meta[1]   File format of schema layer.
86586   **    meta[2]   Size of the page cache.
86587   **    meta[3]   Largest rootpage (auto/incr_vacuum mode)
86588   **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
86589   **    meta[5]   User version
86590   **    meta[6]   Incremental vacuum mode
86591   **    meta[7]   unused
86592   **    meta[8]   unused
86593   **    meta[9]   unused
86594   **
86595   ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
86596   ** the possible values of meta[4].
86597   */
86598   for(i=0; i<ArraySize(meta); i++){
86599     sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
86600   }
86601   pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
86602
86603   /* If opening a non-empty database, check the text encoding. For the
86604   ** main database, set sqlite3.enc to the encoding of the main database.
86605   ** For an attached db, it is an error if the encoding is not the same
86606   ** as sqlite3.enc.
86607   */
86608   if( meta[BTREE_TEXT_ENCODING-1] ){  /* text encoding */
86609     if( iDb==0 ){
86610       u8 encoding;
86611       /* If opening the main database, set ENC(db). */
86612       encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
86613       if( encoding==0 ) encoding = SQLITE_UTF8;
86614       ENC(db) = encoding;
86615       db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
86616     }else{
86617       /* If opening an attached database, the encoding much match ENC(db) */
86618       if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
86619         sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
86620             " text encoding as main database");
86621         rc = SQLITE_ERROR;
86622         goto initone_error_out;
86623       }
86624     }
86625   }else{
86626     DbSetProperty(db, iDb, DB_Empty);
86627   }
86628   pDb->pSchema->enc = ENC(db);
86629
86630   if( pDb->pSchema->cache_size==0 ){
86631     size = meta[BTREE_DEFAULT_CACHE_SIZE-1];
86632     if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
86633     if( size<0 ) size = -size;
86634     pDb->pSchema->cache_size = size;
86635     sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
86636   }
86637
86638   /*
86639   ** file_format==1    Version 3.0.0.
86640   ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
86641   ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
86642   ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
86643   */
86644   pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
86645   if( pDb->pSchema->file_format==0 ){
86646     pDb->pSchema->file_format = 1;
86647   }
86648   if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
86649     sqlite3SetString(pzErrMsg, db, "unsupported file format");
86650     rc = SQLITE_ERROR;
86651     goto initone_error_out;
86652   }
86653
86654   /* Ticket #2804:  When we open a database in the newer file format,
86655   ** clear the legacy_file_format pragma flag so that a VACUUM will
86656   ** not downgrade the database and thus invalidate any descending
86657   ** indices that the user might have created.
86658   */
86659   if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
86660     db->flags &= ~SQLITE_LegacyFileFmt;
86661   }
86662
86663   /* Read the schema information out of the schema tables
86664   */
86665   assert( db->init.busy );
86666   {
86667     char *zSql;
86668     zSql = sqlite3MPrintf(db, 
86669         "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid",
86670         db->aDb[iDb].zName, zMasterName);
86671 #ifndef SQLITE_OMIT_AUTHORIZATION
86672     {
86673       int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
86674       xAuth = db->xAuth;
86675       db->xAuth = 0;
86676 #endif
86677       rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
86678 #ifndef SQLITE_OMIT_AUTHORIZATION
86679       db->xAuth = xAuth;
86680     }
86681 #endif
86682     if( rc==SQLITE_OK ) rc = initData.rc;
86683     sqlite3DbFree(db, zSql);
86684 #ifndef SQLITE_OMIT_ANALYZE
86685     if( rc==SQLITE_OK ){
86686       sqlite3AnalysisLoad(db, iDb);
86687     }
86688 #endif
86689   }
86690   if( db->mallocFailed ){
86691     rc = SQLITE_NOMEM;
86692     sqlite3ResetInternalSchema(db, 0);
86693   }
86694   if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
86695     /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
86696     ** the schema loaded, even if errors occurred. In this situation the 
86697     ** current sqlite3_prepare() operation will fail, but the following one
86698     ** will attempt to compile the supplied statement against whatever subset
86699     ** of the schema was loaded before the error occurred. The primary
86700     ** purpose of this is to allow access to the sqlite_master table
86701     ** even when its contents have been corrupted.
86702     */
86703     DbSetProperty(db, iDb, DB_SchemaLoaded);
86704     rc = SQLITE_OK;
86705   }
86706
86707   /* Jump here for an error that occurs after successfully allocating
86708   ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
86709   ** before that point, jump to error_out.
86710   */
86711 initone_error_out:
86712   if( openedTransaction ){
86713     sqlite3BtreeCommit(pDb->pBt);
86714   }
86715   sqlite3BtreeLeave(pDb->pBt);
86716
86717 error_out:
86718   if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
86719     db->mallocFailed = 1;
86720   }
86721   return rc;
86722 }
86723
86724 /*
86725 ** Initialize all database files - the main database file, the file
86726 ** used to store temporary tables, and any additional database files
86727 ** created using ATTACH statements.  Return a success code.  If an
86728 ** error occurs, write an error message into *pzErrMsg.
86729 **
86730 ** After a database is initialized, the DB_SchemaLoaded bit is set
86731 ** bit is set in the flags field of the Db structure. If the database
86732 ** file was of zero-length, then the DB_Empty flag is also set.
86733 */
86734 SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
86735   int i, rc;
86736   int commit_internal = !(db->flags&SQLITE_InternChanges);
86737   
86738   assert( sqlite3_mutex_held(db->mutex) );
86739   rc = SQLITE_OK;
86740   db->init.busy = 1;
86741   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
86742     if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
86743     rc = sqlite3InitOne(db, i, pzErrMsg);
86744     if( rc ){
86745       sqlite3ResetInternalSchema(db, i);
86746     }
86747   }
86748
86749   /* Once all the other databases have been initialised, load the schema
86750   ** for the TEMP database. This is loaded last, as the TEMP database
86751   ** schema may contain references to objects in other databases.
86752   */
86753 #ifndef SQLITE_OMIT_TEMPDB
86754   if( rc==SQLITE_OK && ALWAYS(db->nDb>1)
86755                     && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
86756     rc = sqlite3InitOne(db, 1, pzErrMsg);
86757     if( rc ){
86758       sqlite3ResetInternalSchema(db, 1);
86759     }
86760   }
86761 #endif
86762
86763   db->init.busy = 0;
86764   if( rc==SQLITE_OK && commit_internal ){
86765     sqlite3CommitInternalChanges(db);
86766   }
86767
86768   return rc; 
86769 }
86770
86771 /*
86772 ** This routine is a no-op if the database schema is already initialised.
86773 ** Otherwise, the schema is loaded. An error code is returned.
86774 */
86775 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
86776   int rc = SQLITE_OK;
86777   sqlite3 *db = pParse->db;
86778   assert( sqlite3_mutex_held(db->mutex) );
86779   if( !db->init.busy ){
86780     rc = sqlite3Init(db, &pParse->zErrMsg);
86781   }
86782   if( rc!=SQLITE_OK ){
86783     pParse->rc = rc;
86784     pParse->nErr++;
86785   }
86786   return rc;
86787 }
86788
86789
86790 /*
86791 ** Check schema cookies in all databases.  If any cookie is out
86792 ** of date set pParse->rc to SQLITE_SCHEMA.  If all schema cookies
86793 ** make no changes to pParse->rc.
86794 */
86795 static void schemaIsValid(Parse *pParse){
86796   sqlite3 *db = pParse->db;
86797   int iDb;
86798   int rc;
86799   int cookie;
86800
86801   assert( pParse->checkSchema );
86802   assert( sqlite3_mutex_held(db->mutex) );
86803   for(iDb=0; iDb<db->nDb; iDb++){
86804     int openedTransaction = 0;         /* True if a transaction is opened */
86805     Btree *pBt = db->aDb[iDb].pBt;     /* Btree database to read cookie from */
86806     if( pBt==0 ) continue;
86807
86808     /* If there is not already a read-only (or read-write) transaction opened
86809     ** on the b-tree database, open one now. If a transaction is opened, it 
86810     ** will be closed immediately after reading the meta-value. */
86811     if( !sqlite3BtreeIsInReadTrans(pBt) ){
86812       rc = sqlite3BtreeBeginTrans(pBt, 0);
86813       if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
86814         db->mallocFailed = 1;
86815       }
86816       if( rc!=SQLITE_OK ) return;
86817       openedTransaction = 1;
86818     }
86819
86820     /* Read the schema cookie from the database. If it does not match the 
86821     ** value stored as part of the in-memory schema representation,
86822     ** set Parse.rc to SQLITE_SCHEMA. */
86823     sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
86824     if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
86825       pParse->rc = SQLITE_SCHEMA;
86826     }
86827
86828     /* Close the transaction, if one was opened. */
86829     if( openedTransaction ){
86830       sqlite3BtreeCommit(pBt);
86831     }
86832   }
86833 }
86834
86835 /*
86836 ** Convert a schema pointer into the iDb index that indicates
86837 ** which database file in db->aDb[] the schema refers to.
86838 **
86839 ** If the same database is attached more than once, the first
86840 ** attached database is returned.
86841 */
86842 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
86843   int i = -1000000;
86844
86845   /* If pSchema is NULL, then return -1000000. This happens when code in 
86846   ** expr.c is trying to resolve a reference to a transient table (i.e. one
86847   ** created by a sub-select). In this case the return value of this 
86848   ** function should never be used.
86849   **
86850   ** We return -1000000 instead of the more usual -1 simply because using
86851   ** -1000000 as the incorrect index into db->aDb[] is much 
86852   ** more likely to cause a segfault than -1 (of course there are assert()
86853   ** statements too, but it never hurts to play the odds).
86854   */
86855   assert( sqlite3_mutex_held(db->mutex) );
86856   if( pSchema ){
86857     for(i=0; ALWAYS(i<db->nDb); i++){
86858       if( db->aDb[i].pSchema==pSchema ){
86859         break;
86860       }
86861     }
86862     assert( i>=0 && i<db->nDb );
86863   }
86864   return i;
86865 }
86866
86867 /*
86868 ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
86869 */
86870 static int sqlite3Prepare(
86871   sqlite3 *db,              /* Database handle. */
86872   const char *zSql,         /* UTF-8 encoded SQL statement. */
86873   int nBytes,               /* Length of zSql in bytes. */
86874   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
86875   Vdbe *pReprepare,         /* VM being reprepared */
86876   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
86877   const char **pzTail       /* OUT: End of parsed string */
86878 ){
86879   Parse *pParse;            /* Parsing context */
86880   char *zErrMsg = 0;        /* Error message */
86881   int rc = SQLITE_OK;       /* Result code */
86882   int i;                    /* Loop counter */
86883
86884   /* Allocate the parsing context */
86885   pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
86886   if( pParse==0 ){
86887     rc = SQLITE_NOMEM;
86888     goto end_prepare;
86889   }
86890   pParse->pReprepare = pReprepare;
86891   assert( ppStmt && *ppStmt==0 );
86892   assert( !db->mallocFailed );
86893   assert( sqlite3_mutex_held(db->mutex) );
86894
86895   /* Check to verify that it is possible to get a read lock on all
86896   ** database schemas.  The inability to get a read lock indicates that
86897   ** some other database connection is holding a write-lock, which in
86898   ** turn means that the other connection has made uncommitted changes
86899   ** to the schema.
86900   **
86901   ** Were we to proceed and prepare the statement against the uncommitted
86902   ** schema changes and if those schema changes are subsequently rolled
86903   ** back and different changes are made in their place, then when this
86904   ** prepared statement goes to run the schema cookie would fail to detect
86905   ** the schema change.  Disaster would follow.
86906   **
86907   ** This thread is currently holding mutexes on all Btrees (because
86908   ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
86909   ** is not possible for another thread to start a new schema change
86910   ** while this routine is running.  Hence, we do not need to hold 
86911   ** locks on the schema, we just need to make sure nobody else is 
86912   ** holding them.
86913   **
86914   ** Note that setting READ_UNCOMMITTED overrides most lock detection,
86915   ** but it does *not* override schema lock detection, so this all still
86916   ** works even if READ_UNCOMMITTED is set.
86917   */
86918   for(i=0; i<db->nDb; i++) {
86919     Btree *pBt = db->aDb[i].pBt;
86920     if( pBt ){
86921       assert( sqlite3BtreeHoldsMutex(pBt) );
86922       rc = sqlite3BtreeSchemaLocked(pBt);
86923       if( rc ){
86924         const char *zDb = db->aDb[i].zName;
86925         sqlite3Error(db, rc, "database schema is locked: %s", zDb);
86926         testcase( db->flags & SQLITE_ReadUncommitted );
86927         goto end_prepare;
86928       }
86929     }
86930   }
86931
86932   sqlite3VtabUnlockList(db);
86933
86934   pParse->db = db;
86935   pParse->nQueryLoop = (double)1;
86936   if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
86937     char *zSqlCopy;
86938     int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
86939     testcase( nBytes==mxLen );
86940     testcase( nBytes==mxLen+1 );
86941     if( nBytes>mxLen ){
86942       sqlite3Error(db, SQLITE_TOOBIG, "statement too long");
86943       rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
86944       goto end_prepare;
86945     }
86946     zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
86947     if( zSqlCopy ){
86948       sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
86949       sqlite3DbFree(db, zSqlCopy);
86950       pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
86951     }else{
86952       pParse->zTail = &zSql[nBytes];
86953     }
86954   }else{
86955     sqlite3RunParser(pParse, zSql, &zErrMsg);
86956   }
86957   assert( 1==(int)pParse->nQueryLoop );
86958
86959   if( db->mallocFailed ){
86960     pParse->rc = SQLITE_NOMEM;
86961   }
86962   if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
86963   if( pParse->checkSchema ){
86964     schemaIsValid(pParse);
86965   }
86966   if( pParse->rc==SQLITE_SCHEMA ){
86967     sqlite3ResetInternalSchema(db, 0);
86968   }
86969   if( db->mallocFailed ){
86970     pParse->rc = SQLITE_NOMEM;
86971   }
86972   if( pzTail ){
86973     *pzTail = pParse->zTail;
86974   }
86975   rc = pParse->rc;
86976
86977 #ifndef SQLITE_OMIT_EXPLAIN
86978   if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
86979     static const char * const azColName[] = {
86980        "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
86981        "order", "from", "detail"
86982     };
86983     int iFirst, mx;
86984     if( pParse->explain==2 ){
86985       sqlite3VdbeSetNumCols(pParse->pVdbe, 3);
86986       iFirst = 8;
86987       mx = 11;
86988     }else{
86989       sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
86990       iFirst = 0;
86991       mx = 8;
86992     }
86993     for(i=iFirst; i<mx; i++){
86994       sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
86995                             azColName[i], SQLITE_STATIC);
86996     }
86997   }
86998 #endif
86999
87000   assert( db->init.busy==0 || saveSqlFlag==0 );
87001   if( db->init.busy==0 ){
87002     Vdbe *pVdbe = pParse->pVdbe;
87003     sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
87004   }
87005   if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
87006     sqlite3VdbeFinalize(pParse->pVdbe);
87007     assert(!(*ppStmt));
87008   }else{
87009     *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
87010   }
87011
87012   if( zErrMsg ){
87013     sqlite3Error(db, rc, "%s", zErrMsg);
87014     sqlite3DbFree(db, zErrMsg);
87015   }else{
87016     sqlite3Error(db, rc, 0);
87017   }
87018
87019   /* Delete any TriggerPrg structures allocated while parsing this statement. */
87020   while( pParse->pTriggerPrg ){
87021     TriggerPrg *pT = pParse->pTriggerPrg;
87022     pParse->pTriggerPrg = pT->pNext;
87023     sqlite3DbFree(db, pT);
87024   }
87025
87026 end_prepare:
87027
87028   sqlite3StackFree(db, pParse);
87029   rc = sqlite3ApiExit(db, rc);
87030   assert( (rc&db->errMask)==rc );
87031   return rc;
87032 }
87033 static int sqlite3LockAndPrepare(
87034   sqlite3 *db,              /* Database handle. */
87035   const char *zSql,         /* UTF-8 encoded SQL statement. */
87036   int nBytes,               /* Length of zSql in bytes. */
87037   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
87038   Vdbe *pOld,               /* VM being reprepared */
87039   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
87040   const char **pzTail       /* OUT: End of parsed string */
87041 ){
87042   int rc;
87043   assert( ppStmt!=0 );
87044   *ppStmt = 0;
87045   if( !sqlite3SafetyCheckOk(db) ){
87046     return SQLITE_MISUSE_BKPT;
87047   }
87048   sqlite3_mutex_enter(db->mutex);
87049   sqlite3BtreeEnterAll(db);
87050   rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
87051   if( rc==SQLITE_SCHEMA ){
87052     sqlite3_finalize(*ppStmt);
87053     rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
87054   }
87055   sqlite3BtreeLeaveAll(db);
87056   sqlite3_mutex_leave(db->mutex);
87057   return rc;
87058 }
87059
87060 /*
87061 ** Rerun the compilation of a statement after a schema change.
87062 **
87063 ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
87064 ** if the statement cannot be recompiled because another connection has
87065 ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
87066 ** occurs, return SQLITE_SCHEMA.
87067 */
87068 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
87069   int rc;
87070   sqlite3_stmt *pNew;
87071   const char *zSql;
87072   sqlite3 *db;
87073
87074   assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
87075   zSql = sqlite3_sql((sqlite3_stmt *)p);
87076   assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
87077   db = sqlite3VdbeDb(p);
87078   assert( sqlite3_mutex_held(db->mutex) );
87079   rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
87080   if( rc ){
87081     if( rc==SQLITE_NOMEM ){
87082       db->mallocFailed = 1;
87083     }
87084     assert( pNew==0 );
87085     return rc;
87086   }else{
87087     assert( pNew!=0 );
87088   }
87089   sqlite3VdbeSwap((Vdbe*)pNew, p);
87090   sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
87091   sqlite3VdbeResetStepResult((Vdbe*)pNew);
87092   sqlite3VdbeFinalize((Vdbe*)pNew);
87093   return SQLITE_OK;
87094 }
87095
87096
87097 /*
87098 ** Two versions of the official API.  Legacy and new use.  In the legacy
87099 ** version, the original SQL text is not saved in the prepared statement
87100 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
87101 ** sqlite3_step().  In the new version, the original SQL text is retained
87102 ** and the statement is automatically recompiled if an schema change
87103 ** occurs.
87104 */
87105 SQLITE_API int sqlite3_prepare(
87106   sqlite3 *db,              /* Database handle. */
87107   const char *zSql,         /* UTF-8 encoded SQL statement. */
87108   int nBytes,               /* Length of zSql in bytes. */
87109   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
87110   const char **pzTail       /* OUT: End of parsed string */
87111 ){
87112   int rc;
87113   rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
87114   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
87115   return rc;
87116 }
87117 SQLITE_API int sqlite3_prepare_v2(
87118   sqlite3 *db,              /* Database handle. */
87119   const char *zSql,         /* UTF-8 encoded SQL statement. */
87120   int nBytes,               /* Length of zSql in bytes. */
87121   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
87122   const char **pzTail       /* OUT: End of parsed string */
87123 ){
87124   int rc;
87125   rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
87126   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
87127   return rc;
87128 }
87129
87130
87131 #ifndef SQLITE_OMIT_UTF16
87132 /*
87133 ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
87134 */
87135 static int sqlite3Prepare16(
87136   sqlite3 *db,              /* Database handle. */ 
87137   const void *zSql,         /* UTF-8 encoded SQL statement. */
87138   int nBytes,               /* Length of zSql in bytes. */
87139   int saveSqlFlag,          /* True to save SQL text into the sqlite3_stmt */
87140   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
87141   const void **pzTail       /* OUT: End of parsed string */
87142 ){
87143   /* This function currently works by first transforming the UTF-16
87144   ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
87145   ** tricky bit is figuring out the pointer to return in *pzTail.
87146   */
87147   char *zSql8;
87148   const char *zTail8 = 0;
87149   int rc = SQLITE_OK;
87150
87151   assert( ppStmt );
87152   *ppStmt = 0;
87153   if( !sqlite3SafetyCheckOk(db) ){
87154     return SQLITE_MISUSE_BKPT;
87155   }
87156   sqlite3_mutex_enter(db->mutex);
87157   zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
87158   if( zSql8 ){
87159     rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
87160   }
87161
87162   if( zTail8 && pzTail ){
87163     /* If sqlite3_prepare returns a tail pointer, we calculate the
87164     ** equivalent pointer into the UTF-16 string by counting the unicode
87165     ** characters between zSql8 and zTail8, and then returning a pointer
87166     ** the same number of characters into the UTF-16 string.
87167     */
87168     int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
87169     *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
87170   }
87171   sqlite3DbFree(db, zSql8); 
87172   rc = sqlite3ApiExit(db, rc);
87173   sqlite3_mutex_leave(db->mutex);
87174   return rc;
87175 }
87176
87177 /*
87178 ** Two versions of the official API.  Legacy and new use.  In the legacy
87179 ** version, the original SQL text is not saved in the prepared statement
87180 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
87181 ** sqlite3_step().  In the new version, the original SQL text is retained
87182 ** and the statement is automatically recompiled if an schema change
87183 ** occurs.
87184 */
87185 SQLITE_API int sqlite3_prepare16(
87186   sqlite3 *db,              /* Database handle. */ 
87187   const void *zSql,         /* UTF-8 encoded SQL statement. */
87188   int nBytes,               /* Length of zSql in bytes. */
87189   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
87190   const void **pzTail       /* OUT: End of parsed string */
87191 ){
87192   int rc;
87193   rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
87194   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
87195   return rc;
87196 }
87197 SQLITE_API int sqlite3_prepare16_v2(
87198   sqlite3 *db,              /* Database handle. */ 
87199   const void *zSql,         /* UTF-8 encoded SQL statement. */
87200   int nBytes,               /* Length of zSql in bytes. */
87201   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
87202   const void **pzTail       /* OUT: End of parsed string */
87203 ){
87204   int rc;
87205   rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
87206   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
87207   return rc;
87208 }
87209
87210 #endif /* SQLITE_OMIT_UTF16 */
87211
87212 /************** End of prepare.c *********************************************/
87213 /************** Begin file select.c ******************************************/
87214 /*
87215 ** 2001 September 15
87216 **
87217 ** The author disclaims copyright to this source code.  In place of
87218 ** a legal notice, here is a blessing:
87219 **
87220 **    May you do good and not evil.
87221 **    May you find forgiveness for yourself and forgive others.
87222 **    May you share freely, never taking more than you give.
87223 **
87224 *************************************************************************
87225 ** This file contains C code routines that are called by the parser
87226 ** to handle SELECT statements in SQLite.
87227 */
87228
87229
87230 /*
87231 ** Delete all the content of a Select structure but do not deallocate
87232 ** the select structure itself.
87233 */
87234 static void clearSelect(sqlite3 *db, Select *p){
87235   sqlite3ExprListDelete(db, p->pEList);
87236   sqlite3SrcListDelete(db, p->pSrc);
87237   sqlite3ExprDelete(db, p->pWhere);
87238   sqlite3ExprListDelete(db, p->pGroupBy);
87239   sqlite3ExprDelete(db, p->pHaving);
87240   sqlite3ExprListDelete(db, p->pOrderBy);
87241   sqlite3SelectDelete(db, p->pPrior);
87242   sqlite3ExprDelete(db, p->pLimit);
87243   sqlite3ExprDelete(db, p->pOffset);
87244 }
87245
87246 /*
87247 ** Initialize a SelectDest structure.
87248 */
87249 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
87250   pDest->eDest = (u8)eDest;
87251   pDest->iParm = iParm;
87252   pDest->affinity = 0;
87253   pDest->iMem = 0;
87254   pDest->nMem = 0;
87255 }
87256
87257
87258 /*
87259 ** Allocate a new Select structure and return a pointer to that
87260 ** structure.
87261 */
87262 SQLITE_PRIVATE Select *sqlite3SelectNew(
87263   Parse *pParse,        /* Parsing context */
87264   ExprList *pEList,     /* which columns to include in the result */
87265   SrcList *pSrc,        /* the FROM clause -- which tables to scan */
87266   Expr *pWhere,         /* the WHERE clause */
87267   ExprList *pGroupBy,   /* the GROUP BY clause */
87268   Expr *pHaving,        /* the HAVING clause */
87269   ExprList *pOrderBy,   /* the ORDER BY clause */
87270   int isDistinct,       /* true if the DISTINCT keyword is present */
87271   Expr *pLimit,         /* LIMIT value.  NULL means not used */
87272   Expr *pOffset         /* OFFSET value.  NULL means no offset */
87273 ){
87274   Select *pNew;
87275   Select standin;
87276   sqlite3 *db = pParse->db;
87277   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
87278   assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
87279   if( pNew==0 ){
87280     pNew = &standin;
87281     memset(pNew, 0, sizeof(*pNew));
87282   }
87283   if( pEList==0 ){
87284     pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
87285   }
87286   pNew->pEList = pEList;
87287   pNew->pSrc = pSrc;
87288   pNew->pWhere = pWhere;
87289   pNew->pGroupBy = pGroupBy;
87290   pNew->pHaving = pHaving;
87291   pNew->pOrderBy = pOrderBy;
87292   pNew->selFlags = isDistinct ? SF_Distinct : 0;
87293   pNew->op = TK_SELECT;
87294   pNew->pLimit = pLimit;
87295   pNew->pOffset = pOffset;
87296   assert( pOffset==0 || pLimit!=0 );
87297   pNew->addrOpenEphm[0] = -1;
87298   pNew->addrOpenEphm[1] = -1;
87299   pNew->addrOpenEphm[2] = -1;
87300   if( db->mallocFailed ) {
87301     clearSelect(db, pNew);
87302     if( pNew!=&standin ) sqlite3DbFree(db, pNew);
87303     pNew = 0;
87304   }
87305   return pNew;
87306 }
87307
87308 /*
87309 ** Delete the given Select structure and all of its substructures.
87310 */
87311 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
87312   if( p ){
87313     clearSelect(db, p);
87314     sqlite3DbFree(db, p);
87315   }
87316 }
87317
87318 /*
87319 ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
87320 ** type of join.  Return an integer constant that expresses that type
87321 ** in terms of the following bit values:
87322 **
87323 **     JT_INNER
87324 **     JT_CROSS
87325 **     JT_OUTER
87326 **     JT_NATURAL
87327 **     JT_LEFT
87328 **     JT_RIGHT
87329 **
87330 ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
87331 **
87332 ** If an illegal or unsupported join type is seen, then still return
87333 ** a join type, but put an error in the pParse structure.
87334 */
87335 SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
87336   int jointype = 0;
87337   Token *apAll[3];
87338   Token *p;
87339                              /*   0123456789 123456789 123456789 123 */
87340   static const char zKeyText[] = "naturaleftouterightfullinnercross";
87341   static const struct {
87342     u8 i;        /* Beginning of keyword text in zKeyText[] */
87343     u8 nChar;    /* Length of the keyword in characters */
87344     u8 code;     /* Join type mask */
87345   } aKeyword[] = {
87346     /* natural */ { 0,  7, JT_NATURAL                },
87347     /* left    */ { 6,  4, JT_LEFT|JT_OUTER          },
87348     /* outer   */ { 10, 5, JT_OUTER                  },
87349     /* right   */ { 14, 5, JT_RIGHT|JT_OUTER         },
87350     /* full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
87351     /* inner   */ { 23, 5, JT_INNER                  },
87352     /* cross   */ { 28, 5, JT_INNER|JT_CROSS         },
87353   };
87354   int i, j;
87355   apAll[0] = pA;
87356   apAll[1] = pB;
87357   apAll[2] = pC;
87358   for(i=0; i<3 && apAll[i]; i++){
87359     p = apAll[i];
87360     for(j=0; j<ArraySize(aKeyword); j++){
87361       if( p->n==aKeyword[j].nChar 
87362           && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
87363         jointype |= aKeyword[j].code;
87364         break;
87365       }
87366     }
87367     testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
87368     if( j>=ArraySize(aKeyword) ){
87369       jointype |= JT_ERROR;
87370       break;
87371     }
87372   }
87373   if(
87374      (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
87375      (jointype & JT_ERROR)!=0
87376   ){
87377     const char *zSp = " ";
87378     assert( pB!=0 );
87379     if( pC==0 ){ zSp++; }
87380     sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
87381        "%T %T%s%T", pA, pB, zSp, pC);
87382     jointype = JT_INNER;
87383   }else if( (jointype & JT_OUTER)!=0 
87384          && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
87385     sqlite3ErrorMsg(pParse, 
87386       "RIGHT and FULL OUTER JOINs are not currently supported");
87387     jointype = JT_INNER;
87388   }
87389   return jointype;
87390 }
87391
87392 /*
87393 ** Return the index of a column in a table.  Return -1 if the column
87394 ** is not contained in the table.
87395 */
87396 static int columnIndex(Table *pTab, const char *zCol){
87397   int i;
87398   for(i=0; i<pTab->nCol; i++){
87399     if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
87400   }
87401   return -1;
87402 }
87403
87404 /*
87405 ** Search the first N tables in pSrc, from left to right, looking for a
87406 ** table that has a column named zCol.  
87407 **
87408 ** When found, set *piTab and *piCol to the table index and column index
87409 ** of the matching column and return TRUE.
87410 **
87411 ** If not found, return FALSE.
87412 */
87413 static int tableAndColumnIndex(
87414   SrcList *pSrc,       /* Array of tables to search */
87415   int N,               /* Number of tables in pSrc->a[] to search */
87416   const char *zCol,    /* Name of the column we are looking for */
87417   int *piTab,          /* Write index of pSrc->a[] here */
87418   int *piCol           /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
87419 ){
87420   int i;               /* For looping over tables in pSrc */
87421   int iCol;            /* Index of column matching zCol */
87422
87423   assert( (piTab==0)==(piCol==0) );  /* Both or neither are NULL */
87424   for(i=0; i<N; i++){
87425     iCol = columnIndex(pSrc->a[i].pTab, zCol);
87426     if( iCol>=0 ){
87427       if( piTab ){
87428         *piTab = i;
87429         *piCol = iCol;
87430       }
87431       return 1;
87432     }
87433   }
87434   return 0;
87435 }
87436
87437 /*
87438 ** This function is used to add terms implied by JOIN syntax to the
87439 ** WHERE clause expression of a SELECT statement. The new term, which
87440 ** is ANDed with the existing WHERE clause, is of the form:
87441 **
87442 **    (tab1.col1 = tab2.col2)
87443 **
87444 ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the 
87445 ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
87446 ** column iColRight of tab2.
87447 */
87448 static void addWhereTerm(
87449   Parse *pParse,                  /* Parsing context */
87450   SrcList *pSrc,                  /* List of tables in FROM clause */
87451   int iLeft,                      /* Index of first table to join in pSrc */
87452   int iColLeft,                   /* Index of column in first table */
87453   int iRight,                     /* Index of second table in pSrc */
87454   int iColRight,                  /* Index of column in second table */
87455   int isOuterJoin,                /* True if this is an OUTER join */
87456   Expr **ppWhere                  /* IN/OUT: The WHERE clause to add to */
87457 ){
87458   sqlite3 *db = pParse->db;
87459   Expr *pE1;
87460   Expr *pE2;
87461   Expr *pEq;
87462
87463   assert( iLeft<iRight );
87464   assert( pSrc->nSrc>iRight );
87465   assert( pSrc->a[iLeft].pTab );
87466   assert( pSrc->a[iRight].pTab );
87467
87468   pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
87469   pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
87470
87471   pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
87472   if( pEq && isOuterJoin ){
87473     ExprSetProperty(pEq, EP_FromJoin);
87474     assert( !ExprHasAnyProperty(pEq, EP_TokenOnly|EP_Reduced) );
87475     ExprSetIrreducible(pEq);
87476     pEq->iRightJoinTable = (i16)pE2->iTable;
87477   }
87478   *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
87479 }
87480
87481 /*
87482 ** Set the EP_FromJoin property on all terms of the given expression.
87483 ** And set the Expr.iRightJoinTable to iTable for every term in the
87484 ** expression.
87485 **
87486 ** The EP_FromJoin property is used on terms of an expression to tell
87487 ** the LEFT OUTER JOIN processing logic that this term is part of the
87488 ** join restriction specified in the ON or USING clause and not a part
87489 ** of the more general WHERE clause.  These terms are moved over to the
87490 ** WHERE clause during join processing but we need to remember that they
87491 ** originated in the ON or USING clause.
87492 **
87493 ** The Expr.iRightJoinTable tells the WHERE clause processing that the
87494 ** expression depends on table iRightJoinTable even if that table is not
87495 ** explicitly mentioned in the expression.  That information is needed
87496 ** for cases like this:
87497 **
87498 **    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
87499 **
87500 ** The where clause needs to defer the handling of the t1.x=5
87501 ** term until after the t2 loop of the join.  In that way, a
87502 ** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
87503 ** defer the handling of t1.x=5, it will be processed immediately
87504 ** after the t1 loop and rows with t1.x!=5 will never appear in
87505 ** the output, which is incorrect.
87506 */
87507 static void setJoinExpr(Expr *p, int iTable){
87508   while( p ){
87509     ExprSetProperty(p, EP_FromJoin);
87510     assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
87511     ExprSetIrreducible(p);
87512     p->iRightJoinTable = (i16)iTable;
87513     setJoinExpr(p->pLeft, iTable);
87514     p = p->pRight;
87515   } 
87516 }
87517
87518 /*
87519 ** This routine processes the join information for a SELECT statement.
87520 ** ON and USING clauses are converted into extra terms of the WHERE clause.
87521 ** NATURAL joins also create extra WHERE clause terms.
87522 **
87523 ** The terms of a FROM clause are contained in the Select.pSrc structure.
87524 ** The left most table is the first entry in Select.pSrc.  The right-most
87525 ** table is the last entry.  The join operator is held in the entry to
87526 ** the left.  Thus entry 0 contains the join operator for the join between
87527 ** entries 0 and 1.  Any ON or USING clauses associated with the join are
87528 ** also attached to the left entry.
87529 **
87530 ** This routine returns the number of errors encountered.
87531 */
87532 static int sqliteProcessJoin(Parse *pParse, Select *p){
87533   SrcList *pSrc;                  /* All tables in the FROM clause */
87534   int i, j;                       /* Loop counters */
87535   struct SrcList_item *pLeft;     /* Left table being joined */
87536   struct SrcList_item *pRight;    /* Right table being joined */
87537
87538   pSrc = p->pSrc;
87539   pLeft = &pSrc->a[0];
87540   pRight = &pLeft[1];
87541   for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
87542     Table *pLeftTab = pLeft->pTab;
87543     Table *pRightTab = pRight->pTab;
87544     int isOuter;
87545
87546     if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
87547     isOuter = (pRight->jointype & JT_OUTER)!=0;
87548
87549     /* When the NATURAL keyword is present, add WHERE clause terms for
87550     ** every column that the two tables have in common.
87551     */
87552     if( pRight->jointype & JT_NATURAL ){
87553       if( pRight->pOn || pRight->pUsing ){
87554         sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
87555            "an ON or USING clause", 0);
87556         return 1;
87557       }
87558       for(j=0; j<pRightTab->nCol; j++){
87559         char *zName;   /* Name of column in the right table */
87560         int iLeft;     /* Matching left table */
87561         int iLeftCol;  /* Matching column in the left table */
87562
87563         zName = pRightTab->aCol[j].zName;
87564         if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
87565           addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
87566                        isOuter, &p->pWhere);
87567         }
87568       }
87569     }
87570
87571     /* Disallow both ON and USING clauses in the same join
87572     */
87573     if( pRight->pOn && pRight->pUsing ){
87574       sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
87575         "clauses in the same join");
87576       return 1;
87577     }
87578
87579     /* Add the ON clause to the end of the WHERE clause, connected by
87580     ** an AND operator.
87581     */
87582     if( pRight->pOn ){
87583       if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
87584       p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
87585       pRight->pOn = 0;
87586     }
87587
87588     /* Create extra terms on the WHERE clause for each column named
87589     ** in the USING clause.  Example: If the two tables to be joined are 
87590     ** A and B and the USING clause names X, Y, and Z, then add this
87591     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
87592     ** Report an error if any column mentioned in the USING clause is
87593     ** not contained in both tables to be joined.
87594     */
87595     if( pRight->pUsing ){
87596       IdList *pList = pRight->pUsing;
87597       for(j=0; j<pList->nId; j++){
87598         char *zName;     /* Name of the term in the USING clause */
87599         int iLeft;       /* Table on the left with matching column name */
87600         int iLeftCol;    /* Column number of matching column on the left */
87601         int iRightCol;   /* Column number of matching column on the right */
87602
87603         zName = pList->a[j].zName;
87604         iRightCol = columnIndex(pRightTab, zName);
87605         if( iRightCol<0
87606          || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
87607         ){
87608           sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
87609             "not present in both tables", zName);
87610           return 1;
87611         }
87612         addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
87613                      isOuter, &p->pWhere);
87614       }
87615     }
87616   }
87617   return 0;
87618 }
87619
87620 /*
87621 ** Insert code into "v" that will push the record on the top of the
87622 ** stack into the sorter.
87623 */
87624 static void pushOntoSorter(
87625   Parse *pParse,         /* Parser context */
87626   ExprList *pOrderBy,    /* The ORDER BY clause */
87627   Select *pSelect,       /* The whole SELECT statement */
87628   int regData            /* Register holding data to be sorted */
87629 ){
87630   Vdbe *v = pParse->pVdbe;
87631   int nExpr = pOrderBy->nExpr;
87632   int regBase = sqlite3GetTempRange(pParse, nExpr+2);
87633   int regRecord = sqlite3GetTempReg(pParse);
87634   sqlite3ExprCacheClear(pParse);
87635   sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
87636   sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
87637   sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
87638   sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
87639   sqlite3VdbeAddOp2(v, OP_IdxInsert, pOrderBy->iECursor, regRecord);
87640   sqlite3ReleaseTempReg(pParse, regRecord);
87641   sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
87642   if( pSelect->iLimit ){
87643     int addr1, addr2;
87644     int iLimit;
87645     if( pSelect->iOffset ){
87646       iLimit = pSelect->iOffset+1;
87647     }else{
87648       iLimit = pSelect->iLimit;
87649     }
87650     addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
87651     sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
87652     addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
87653     sqlite3VdbeJumpHere(v, addr1);
87654     sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
87655     sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
87656     sqlite3VdbeJumpHere(v, addr2);
87657   }
87658 }
87659
87660 /*
87661 ** Add code to implement the OFFSET
87662 */
87663 static void codeOffset(
87664   Vdbe *v,          /* Generate code into this VM */
87665   Select *p,        /* The SELECT statement being coded */
87666   int iContinue     /* Jump here to skip the current record */
87667 ){
87668   if( p->iOffset && iContinue!=0 ){
87669     int addr;
87670     sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
87671     addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
87672     sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
87673     VdbeComment((v, "skip OFFSET records"));
87674     sqlite3VdbeJumpHere(v, addr);
87675   }
87676 }
87677
87678 /*
87679 ** Add code that will check to make sure the N registers starting at iMem
87680 ** form a distinct entry.  iTab is a sorting index that holds previously
87681 ** seen combinations of the N values.  A new entry is made in iTab
87682 ** if the current N values are new.
87683 **
87684 ** A jump to addrRepeat is made and the N+1 values are popped from the
87685 ** stack if the top N elements are not distinct.
87686 */
87687 static void codeDistinct(
87688   Parse *pParse,     /* Parsing and code generating context */
87689   int iTab,          /* A sorting index used to test for distinctness */
87690   int addrRepeat,    /* Jump to here if not distinct */
87691   int N,             /* Number of elements */
87692   int iMem           /* First element */
87693 ){
87694   Vdbe *v;
87695   int r1;
87696
87697   v = pParse->pVdbe;
87698   r1 = sqlite3GetTempReg(pParse);
87699   sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N);
87700   sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
87701   sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
87702   sqlite3ReleaseTempReg(pParse, r1);
87703 }
87704
87705 #ifndef SQLITE_OMIT_SUBQUERY
87706 /*
87707 ** Generate an error message when a SELECT is used within a subexpression
87708 ** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
87709 ** column.  We do this in a subroutine because the error used to occur
87710 ** in multiple places.  (The error only occurs in one place now, but we
87711 ** retain the subroutine to minimize code disruption.)
87712 */
87713 static int checkForMultiColumnSelectError(
87714   Parse *pParse,       /* Parse context. */
87715   SelectDest *pDest,   /* Destination of SELECT results */
87716   int nExpr            /* Number of result columns returned by SELECT */
87717 ){
87718   int eDest = pDest->eDest;
87719   if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
87720     sqlite3ErrorMsg(pParse, "only a single result allowed for "
87721        "a SELECT that is part of an expression");
87722     return 1;
87723   }else{
87724     return 0;
87725   }
87726 }
87727 #endif
87728
87729 /*
87730 ** This routine generates the code for the inside of the inner loop
87731 ** of a SELECT.
87732 **
87733 ** If srcTab and nColumn are both zero, then the pEList expressions
87734 ** are evaluated in order to get the data for this row.  If nColumn>0
87735 ** then data is pulled from srcTab and pEList is used only to get the
87736 ** datatypes for each column.
87737 */
87738 static void selectInnerLoop(
87739   Parse *pParse,          /* The parser context */
87740   Select *p,              /* The complete select statement being coded */
87741   ExprList *pEList,       /* List of values being extracted */
87742   int srcTab,             /* Pull data from this table */
87743   int nColumn,            /* Number of columns in the source table */
87744   ExprList *pOrderBy,     /* If not NULL, sort results using this key */
87745   int distinct,           /* If >=0, make sure results are distinct */
87746   SelectDest *pDest,      /* How to dispose of the results */
87747   int iContinue,          /* Jump here to continue with next row */
87748   int iBreak              /* Jump here to break out of the inner loop */
87749 ){
87750   Vdbe *v = pParse->pVdbe;
87751   int i;
87752   int hasDistinct;        /* True if the DISTINCT keyword is present */
87753   int regResult;              /* Start of memory holding result set */
87754   int eDest = pDest->eDest;   /* How to dispose of results */
87755   int iParm = pDest->iParm;   /* First argument to disposal method */
87756   int nResultCol;             /* Number of result columns */
87757
87758   assert( v );
87759   if( NEVER(v==0) ) return;
87760   assert( pEList!=0 );
87761   hasDistinct = distinct>=0;
87762   if( pOrderBy==0 && !hasDistinct ){
87763     codeOffset(v, p, iContinue);
87764   }
87765
87766   /* Pull the requested columns.
87767   */
87768   if( nColumn>0 ){
87769     nResultCol = nColumn;
87770   }else{
87771     nResultCol = pEList->nExpr;
87772   }
87773   if( pDest->iMem==0 ){
87774     pDest->iMem = pParse->nMem+1;
87775     pDest->nMem = nResultCol;
87776     pParse->nMem += nResultCol;
87777   }else{ 
87778     assert( pDest->nMem==nResultCol );
87779   }
87780   regResult = pDest->iMem;
87781   if( nColumn>0 ){
87782     for(i=0; i<nColumn; i++){
87783       sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
87784     }
87785   }else if( eDest!=SRT_Exists ){
87786     /* If the destination is an EXISTS(...) expression, the actual
87787     ** values returned by the SELECT are not required.
87788     */
87789     sqlite3ExprCacheClear(pParse);
87790     sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);
87791   }
87792   nColumn = nResultCol;
87793
87794   /* If the DISTINCT keyword was present on the SELECT statement
87795   ** and this row has been seen before, then do not make this row
87796   ** part of the result.
87797   */
87798   if( hasDistinct ){
87799     assert( pEList!=0 );
87800     assert( pEList->nExpr==nColumn );
87801     codeDistinct(pParse, distinct, iContinue, nColumn, regResult);
87802     if( pOrderBy==0 ){
87803       codeOffset(v, p, iContinue);
87804     }
87805   }
87806
87807   switch( eDest ){
87808     /* In this mode, write each query result to the key of the temporary
87809     ** table iParm.
87810     */
87811 #ifndef SQLITE_OMIT_COMPOUND_SELECT
87812     case SRT_Union: {
87813       int r1;
87814       r1 = sqlite3GetTempReg(pParse);
87815       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
87816       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
87817       sqlite3ReleaseTempReg(pParse, r1);
87818       break;
87819     }
87820
87821     /* Construct a record from the query result, but instead of
87822     ** saving that record, use it as a key to delete elements from
87823     ** the temporary table iParm.
87824     */
87825     case SRT_Except: {
87826       sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
87827       break;
87828     }
87829 #endif
87830
87831     /* Store the result as data using a unique key.
87832     */
87833     case SRT_Table:
87834     case SRT_EphemTab: {
87835       int r1 = sqlite3GetTempReg(pParse);
87836       testcase( eDest==SRT_Table );
87837       testcase( eDest==SRT_EphemTab );
87838       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
87839       if( pOrderBy ){
87840         pushOntoSorter(pParse, pOrderBy, p, r1);
87841       }else{
87842         int r2 = sqlite3GetTempReg(pParse);
87843         sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
87844         sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
87845         sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
87846         sqlite3ReleaseTempReg(pParse, r2);
87847       }
87848       sqlite3ReleaseTempReg(pParse, r1);
87849       break;
87850     }
87851
87852 #ifndef SQLITE_OMIT_SUBQUERY
87853     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
87854     ** then there should be a single item on the stack.  Write this
87855     ** item into the set table with bogus data.
87856     */
87857     case SRT_Set: {
87858       assert( nColumn==1 );
87859       p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affinity);
87860       if( pOrderBy ){
87861         /* At first glance you would think we could optimize out the
87862         ** ORDER BY in this case since the order of entries in the set
87863         ** does not matter.  But there might be a LIMIT clause, in which
87864         ** case the order does matter */
87865         pushOntoSorter(pParse, pOrderBy, p, regResult);
87866       }else{
87867         int r1 = sqlite3GetTempReg(pParse);
87868         sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, 1, r1, &p->affinity, 1);
87869         sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
87870         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
87871         sqlite3ReleaseTempReg(pParse, r1);
87872       }
87873       break;
87874     }
87875
87876     /* If any row exist in the result set, record that fact and abort.
87877     */
87878     case SRT_Exists: {
87879       sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
87880       /* The LIMIT clause will terminate the loop for us */
87881       break;
87882     }
87883
87884     /* If this is a scalar select that is part of an expression, then
87885     ** store the results in the appropriate memory cell and break out
87886     ** of the scan loop.
87887     */
87888     case SRT_Mem: {
87889       assert( nColumn==1 );
87890       if( pOrderBy ){
87891         pushOntoSorter(pParse, pOrderBy, p, regResult);
87892       }else{
87893         sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
87894         /* The LIMIT clause will jump out of the loop for us */
87895       }
87896       break;
87897     }
87898 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
87899
87900     /* Send the data to the callback function or to a subroutine.  In the
87901     ** case of a subroutine, the subroutine itself is responsible for
87902     ** popping the data from the stack.
87903     */
87904     case SRT_Coroutine:
87905     case SRT_Output: {
87906       testcase( eDest==SRT_Coroutine );
87907       testcase( eDest==SRT_Output );
87908       if( pOrderBy ){
87909         int r1 = sqlite3GetTempReg(pParse);
87910         sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
87911         pushOntoSorter(pParse, pOrderBy, p, r1);
87912         sqlite3ReleaseTempReg(pParse, r1);
87913       }else if( eDest==SRT_Coroutine ){
87914         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
87915       }else{
87916         sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
87917         sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn);
87918       }
87919       break;
87920     }
87921
87922 #if !defined(SQLITE_OMIT_TRIGGER)
87923     /* Discard the results.  This is used for SELECT statements inside
87924     ** the body of a TRIGGER.  The purpose of such selects is to call
87925     ** user-defined functions that have side effects.  We do not care
87926     ** about the actual results of the select.
87927     */
87928     default: {
87929       assert( eDest==SRT_Discard );
87930       break;
87931     }
87932 #endif
87933   }
87934
87935   /* Jump to the end of the loop if the LIMIT is reached.  Except, if
87936   ** there is a sorter, in which case the sorter has already limited
87937   ** the output for us.
87938   */
87939   if( pOrderBy==0 && p->iLimit ){
87940     sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
87941   }
87942 }
87943
87944 /*
87945 ** Given an expression list, generate a KeyInfo structure that records
87946 ** the collating sequence for each expression in that expression list.
87947 **
87948 ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
87949 ** KeyInfo structure is appropriate for initializing a virtual index to
87950 ** implement that clause.  If the ExprList is the result set of a SELECT
87951 ** then the KeyInfo structure is appropriate for initializing a virtual
87952 ** index to implement a DISTINCT test.
87953 **
87954 ** Space to hold the KeyInfo structure is obtain from malloc.  The calling
87955 ** function is responsible for seeing that this structure is eventually
87956 ** freed.  Add the KeyInfo structure to the P4 field of an opcode using
87957 ** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
87958 */
87959 static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
87960   sqlite3 *db = pParse->db;
87961   int nExpr;
87962   KeyInfo *pInfo;
87963   struct ExprList_item *pItem;
87964   int i;
87965
87966   nExpr = pList->nExpr;
87967   pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
87968   if( pInfo ){
87969     pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
87970     pInfo->nField = (u16)nExpr;
87971     pInfo->enc = ENC(db);
87972     pInfo->db = db;
87973     for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
87974       CollSeq *pColl;
87975       pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
87976       if( !pColl ){
87977         pColl = db->pDfltColl;
87978       }
87979       pInfo->aColl[i] = pColl;
87980       pInfo->aSortOrder[i] = pItem->sortOrder;
87981     }
87982   }
87983   return pInfo;
87984 }
87985
87986
87987 /*
87988 ** If the inner loop was generated using a non-null pOrderBy argument,
87989 ** then the results were placed in a sorter.  After the loop is terminated
87990 ** we need to run the sorter and output the results.  The following
87991 ** routine generates the code needed to do that.
87992 */
87993 static void generateSortTail(
87994   Parse *pParse,    /* Parsing context */
87995   Select *p,        /* The SELECT statement */
87996   Vdbe *v,          /* Generate code into this VDBE */
87997   int nColumn,      /* Number of columns of data */
87998   SelectDest *pDest /* Write the sorted results here */
87999 ){
88000   int addrBreak = sqlite3VdbeMakeLabel(v);     /* Jump here to exit loop */
88001   int addrContinue = sqlite3VdbeMakeLabel(v);  /* Jump here for next cycle */
88002   int addr;
88003   int iTab;
88004   int pseudoTab = 0;
88005   ExprList *pOrderBy = p->pOrderBy;
88006
88007   int eDest = pDest->eDest;
88008   int iParm = pDest->iParm;
88009
88010   int regRow;
88011   int regRowid;
88012
88013   iTab = pOrderBy->iECursor;
88014   regRow = sqlite3GetTempReg(pParse);
88015   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
88016     pseudoTab = pParse->nTab++;
88017     sqlite3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn);
88018     regRowid = 0;
88019   }else{
88020     regRowid = sqlite3GetTempReg(pParse);
88021   }
88022   addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak);
88023   codeOffset(v, p, addrContinue);
88024   sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr + 1, regRow);
88025   switch( eDest ){
88026     case SRT_Table:
88027     case SRT_EphemTab: {
88028       testcase( eDest==SRT_Table );
88029       testcase( eDest==SRT_EphemTab );
88030       sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
88031       sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
88032       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
88033       break;
88034     }
88035 #ifndef SQLITE_OMIT_SUBQUERY
88036     case SRT_Set: {
88037       assert( nColumn==1 );
88038       sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid, &p->affinity, 1);
88039       sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
88040       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
88041       break;
88042     }
88043     case SRT_Mem: {
88044       assert( nColumn==1 );
88045       sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
88046       /* The LIMIT clause will terminate the loop for us */
88047       break;
88048     }
88049 #endif
88050     default: {
88051       int i;
88052       assert( eDest==SRT_Output || eDest==SRT_Coroutine ); 
88053       testcase( eDest==SRT_Output );
88054       testcase( eDest==SRT_Coroutine );
88055       for(i=0; i<nColumn; i++){
88056         assert( regRow!=pDest->iMem+i );
88057         sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iMem+i);
88058         if( i==0 ){
88059           sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
88060         }
88061       }
88062       if( eDest==SRT_Output ){
88063         sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iMem, nColumn);
88064         sqlite3ExprCacheAffinityChange(pParse, pDest->iMem, nColumn);
88065       }else{
88066         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
88067       }
88068       break;
88069     }
88070   }
88071   sqlite3ReleaseTempReg(pParse, regRow);
88072   sqlite3ReleaseTempReg(pParse, regRowid);
88073
88074   /* The bottom of the loop
88075   */
88076   sqlite3VdbeResolveLabel(v, addrContinue);
88077   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
88078   sqlite3VdbeResolveLabel(v, addrBreak);
88079   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
88080     sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
88081   }
88082 }
88083
88084 /*
88085 ** Return a pointer to a string containing the 'declaration type' of the
88086 ** expression pExpr. The string may be treated as static by the caller.
88087 **
88088 ** The declaration type is the exact datatype definition extracted from the
88089 ** original CREATE TABLE statement if the expression is a column. The
88090 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
88091 ** is considered a column can be complex in the presence of subqueries. The
88092 ** result-set expression in all of the following SELECT statements is 
88093 ** considered a column by this function.
88094 **
88095 **   SELECT col FROM tbl;
88096 **   SELECT (SELECT col FROM tbl;
88097 **   SELECT (SELECT col FROM tbl);
88098 **   SELECT abc FROM (SELECT col AS abc FROM tbl);
88099 ** 
88100 ** The declaration type for any expression other than a column is NULL.
88101 */
88102 static const char *columnType(
88103   NameContext *pNC, 
88104   Expr *pExpr,
88105   const char **pzOriginDb,
88106   const char **pzOriginTab,
88107   const char **pzOriginCol
88108 ){
88109   char const *zType = 0;
88110   char const *zOriginDb = 0;
88111   char const *zOriginTab = 0;
88112   char const *zOriginCol = 0;
88113   int j;
88114   if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
88115
88116   switch( pExpr->op ){
88117     case TK_AGG_COLUMN:
88118     case TK_COLUMN: {
88119       /* The expression is a column. Locate the table the column is being
88120       ** extracted from in NameContext.pSrcList. This table may be real
88121       ** database table or a subquery.
88122       */
88123       Table *pTab = 0;            /* Table structure column is extracted from */
88124       Select *pS = 0;             /* Select the column is extracted from */
88125       int iCol = pExpr->iColumn;  /* Index of column in pTab */
88126       testcase( pExpr->op==TK_AGG_COLUMN );
88127       testcase( pExpr->op==TK_COLUMN );
88128       while( pNC && !pTab ){
88129         SrcList *pTabList = pNC->pSrcList;
88130         for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
88131         if( j<pTabList->nSrc ){
88132           pTab = pTabList->a[j].pTab;
88133           pS = pTabList->a[j].pSelect;
88134         }else{
88135           pNC = pNC->pNext;
88136         }
88137       }
88138
88139       if( pTab==0 ){
88140         /* At one time, code such as "SELECT new.x" within a trigger would
88141         ** cause this condition to run.  Since then, we have restructured how
88142         ** trigger code is generated and so this condition is no longer 
88143         ** possible. However, it can still be true for statements like
88144         ** the following:
88145         **
88146         **   CREATE TABLE t1(col INTEGER);
88147         **   SELECT (SELECT t1.col) FROM FROM t1;
88148         **
88149         ** when columnType() is called on the expression "t1.col" in the 
88150         ** sub-select. In this case, set the column type to NULL, even
88151         ** though it should really be "INTEGER".
88152         **
88153         ** This is not a problem, as the column type of "t1.col" is never
88154         ** used. When columnType() is called on the expression 
88155         ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
88156         ** branch below.  */
88157         break;
88158       }
88159
88160       assert( pTab && pExpr->pTab==pTab );
88161       if( pS ){
88162         /* The "table" is actually a sub-select or a view in the FROM clause
88163         ** of the SELECT statement. Return the declaration type and origin
88164         ** data for the result-set column of the sub-select.
88165         */
88166         if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
88167           /* If iCol is less than zero, then the expression requests the
88168           ** rowid of the sub-select or view. This expression is legal (see 
88169           ** test case misc2.2.2) - it always evaluates to NULL.
88170           */
88171           NameContext sNC;
88172           Expr *p = pS->pEList->a[iCol].pExpr;
88173           sNC.pSrcList = pS->pSrc;
88174           sNC.pNext = pNC;
88175           sNC.pParse = pNC->pParse;
88176           zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 
88177         }
88178       }else if( ALWAYS(pTab->pSchema) ){
88179         /* A real table */
88180         assert( !pS );
88181         if( iCol<0 ) iCol = pTab->iPKey;
88182         assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
88183         if( iCol<0 ){
88184           zType = "INTEGER";
88185           zOriginCol = "rowid";
88186         }else{
88187           zType = pTab->aCol[iCol].zType;
88188           zOriginCol = pTab->aCol[iCol].zName;
88189         }
88190         zOriginTab = pTab->zName;
88191         if( pNC->pParse ){
88192           int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
88193           zOriginDb = pNC->pParse->db->aDb[iDb].zName;
88194         }
88195       }
88196       break;
88197     }
88198 #ifndef SQLITE_OMIT_SUBQUERY
88199     case TK_SELECT: {
88200       /* The expression is a sub-select. Return the declaration type and
88201       ** origin info for the single column in the result set of the SELECT
88202       ** statement.
88203       */
88204       NameContext sNC;
88205       Select *pS = pExpr->x.pSelect;
88206       Expr *p = pS->pEList->a[0].pExpr;
88207       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
88208       sNC.pSrcList = pS->pSrc;
88209       sNC.pNext = pNC;
88210       sNC.pParse = pNC->pParse;
88211       zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 
88212       break;
88213     }
88214 #endif
88215   }
88216   
88217   if( pzOriginDb ){
88218     assert( pzOriginTab && pzOriginCol );
88219     *pzOriginDb = zOriginDb;
88220     *pzOriginTab = zOriginTab;
88221     *pzOriginCol = zOriginCol;
88222   }
88223   return zType;
88224 }
88225
88226 /*
88227 ** Generate code that will tell the VDBE the declaration types of columns
88228 ** in the result set.
88229 */
88230 static void generateColumnTypes(
88231   Parse *pParse,      /* Parser context */
88232   SrcList *pTabList,  /* List of tables */
88233   ExprList *pEList    /* Expressions defining the result set */
88234 ){
88235 #ifndef SQLITE_OMIT_DECLTYPE
88236   Vdbe *v = pParse->pVdbe;
88237   int i;
88238   NameContext sNC;
88239   sNC.pSrcList = pTabList;
88240   sNC.pParse = pParse;
88241   for(i=0; i<pEList->nExpr; i++){
88242     Expr *p = pEList->a[i].pExpr;
88243     const char *zType;
88244 #ifdef SQLITE_ENABLE_COLUMN_METADATA
88245     const char *zOrigDb = 0;
88246     const char *zOrigTab = 0;
88247     const char *zOrigCol = 0;
88248     zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
88249
88250     /* The vdbe must make its own copy of the column-type and other 
88251     ** column specific strings, in case the schema is reset before this
88252     ** virtual machine is deleted.
88253     */
88254     sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
88255     sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
88256     sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
88257 #else
88258     zType = columnType(&sNC, p, 0, 0, 0);
88259 #endif
88260     sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
88261   }
88262 #endif /* SQLITE_OMIT_DECLTYPE */
88263 }
88264
88265 /*
88266 ** Generate code that will tell the VDBE the names of columns
88267 ** in the result set.  This information is used to provide the
88268 ** azCol[] values in the callback.
88269 */
88270 static void generateColumnNames(
88271   Parse *pParse,      /* Parser context */
88272   SrcList *pTabList,  /* List of tables */
88273   ExprList *pEList    /* Expressions defining the result set */
88274 ){
88275   Vdbe *v = pParse->pVdbe;
88276   int i, j;
88277   sqlite3 *db = pParse->db;
88278   int fullNames, shortNames;
88279
88280 #ifndef SQLITE_OMIT_EXPLAIN
88281   /* If this is an EXPLAIN, skip this step */
88282   if( pParse->explain ){
88283     return;
88284   }
88285 #endif
88286
88287   if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
88288   pParse->colNamesSet = 1;
88289   fullNames = (db->flags & SQLITE_FullColNames)!=0;
88290   shortNames = (db->flags & SQLITE_ShortColNames)!=0;
88291   sqlite3VdbeSetNumCols(v, pEList->nExpr);
88292   for(i=0; i<pEList->nExpr; i++){
88293     Expr *p;
88294     p = pEList->a[i].pExpr;
88295     if( NEVER(p==0) ) continue;
88296     if( pEList->a[i].zName ){
88297       char *zName = pEList->a[i].zName;
88298       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
88299     }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
88300       Table *pTab;
88301       char *zCol;
88302       int iCol = p->iColumn;
88303       for(j=0; ALWAYS(j<pTabList->nSrc); j++){
88304         if( pTabList->a[j].iCursor==p->iTable ) break;
88305       }
88306       assert( j<pTabList->nSrc );
88307       pTab = pTabList->a[j].pTab;
88308       if( iCol<0 ) iCol = pTab->iPKey;
88309       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
88310       if( iCol<0 ){
88311         zCol = "rowid";
88312       }else{
88313         zCol = pTab->aCol[iCol].zName;
88314       }
88315       if( !shortNames && !fullNames ){
88316         sqlite3VdbeSetColName(v, i, COLNAME_NAME, 
88317             sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
88318       }else if( fullNames ){
88319         char *zName = 0;
88320         zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
88321         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
88322       }else{
88323         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
88324       }
88325     }else{
88326       sqlite3VdbeSetColName(v, i, COLNAME_NAME, 
88327           sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
88328     }
88329   }
88330   generateColumnTypes(pParse, pTabList, pEList);
88331 }
88332
88333 #ifndef SQLITE_OMIT_COMPOUND_SELECT
88334 /*
88335 ** Name of the connection operator, used for error messages.
88336 */
88337 static const char *selectOpName(int id){
88338   char *z;
88339   switch( id ){
88340     case TK_ALL:       z = "UNION ALL";   break;
88341     case TK_INTERSECT: z = "INTERSECT";   break;
88342     case TK_EXCEPT:    z = "EXCEPT";      break;
88343     default:           z = "UNION";       break;
88344   }
88345   return z;
88346 }
88347 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
88348
88349 /*
88350 ** Given a an expression list (which is really the list of expressions
88351 ** that form the result set of a SELECT statement) compute appropriate
88352 ** column names for a table that would hold the expression list.
88353 **
88354 ** All column names will be unique.
88355 **
88356 ** Only the column names are computed.  Column.zType, Column.zColl,
88357 ** and other fields of Column are zeroed.
88358 **
88359 ** Return SQLITE_OK on success.  If a memory allocation error occurs,
88360 ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
88361 */
88362 static int selectColumnsFromExprList(
88363   Parse *pParse,          /* Parsing context */
88364   ExprList *pEList,       /* Expr list from which to derive column names */
88365   int *pnCol,             /* Write the number of columns here */
88366   Column **paCol          /* Write the new column list here */
88367 ){
88368   sqlite3 *db = pParse->db;   /* Database connection */
88369   int i, j;                   /* Loop counters */
88370   int cnt;                    /* Index added to make the name unique */
88371   Column *aCol, *pCol;        /* For looping over result columns */
88372   int nCol;                   /* Number of columns in the result set */
88373   Expr *p;                    /* Expression for a single result column */
88374   char *zName;                /* Column name */
88375   int nName;                  /* Size of name in zName[] */
88376
88377   *pnCol = nCol = pEList->nExpr;
88378   aCol = *paCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
88379   if( aCol==0 ) return SQLITE_NOMEM;
88380   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
88381     /* Get an appropriate name for the column
88382     */
88383     p = pEList->a[i].pExpr;
88384     assert( p->pRight==0 || ExprHasProperty(p->pRight, EP_IntValue)
88385                || p->pRight->u.zToken==0 || p->pRight->u.zToken[0]!=0 );
88386     if( (zName = pEList->a[i].zName)!=0 ){
88387       /* If the column contains an "AS <name>" phrase, use <name> as the name */
88388       zName = sqlite3DbStrDup(db, zName);
88389     }else{
88390       Expr *pColExpr = p;  /* The expression that is the result column name */
88391       Table *pTab;         /* Table associated with this expression */
88392       while( pColExpr->op==TK_DOT ) pColExpr = pColExpr->pRight;
88393       if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
88394         /* For columns use the column name name */
88395         int iCol = pColExpr->iColumn;
88396         pTab = pColExpr->pTab;
88397         if( iCol<0 ) iCol = pTab->iPKey;
88398         zName = sqlite3MPrintf(db, "%s",
88399                  iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
88400       }else if( pColExpr->op==TK_ID ){
88401         assert( !ExprHasProperty(pColExpr, EP_IntValue) );
88402         zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
88403       }else{
88404         /* Use the original text of the column expression as its name */
88405         zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
88406       }
88407     }
88408     if( db->mallocFailed ){
88409       sqlite3DbFree(db, zName);
88410       break;
88411     }
88412
88413     /* Make sure the column name is unique.  If the name is not unique,
88414     ** append a integer to the name so that it becomes unique.
88415     */
88416     nName = sqlite3Strlen30(zName);
88417     for(j=cnt=0; j<i; j++){
88418       if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
88419         char *zNewName;
88420         zName[nName] = 0;
88421         zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
88422         sqlite3DbFree(db, zName);
88423         zName = zNewName;
88424         j = -1;
88425         if( zName==0 ) break;
88426       }
88427     }
88428     pCol->zName = zName;
88429   }
88430   if( db->mallocFailed ){
88431     for(j=0; j<i; j++){
88432       sqlite3DbFree(db, aCol[j].zName);
88433     }
88434     sqlite3DbFree(db, aCol);
88435     *paCol = 0;
88436     *pnCol = 0;
88437     return SQLITE_NOMEM;
88438   }
88439   return SQLITE_OK;
88440 }
88441
88442 /*
88443 ** Add type and collation information to a column list based on
88444 ** a SELECT statement.
88445 ** 
88446 ** The column list presumably came from selectColumnNamesFromExprList().
88447 ** The column list has only names, not types or collations.  This
88448 ** routine goes through and adds the types and collations.
88449 **
88450 ** This routine requires that all identifiers in the SELECT
88451 ** statement be resolved.
88452 */
88453 static void selectAddColumnTypeAndCollation(
88454   Parse *pParse,        /* Parsing contexts */
88455   int nCol,             /* Number of columns */
88456   Column *aCol,         /* List of columns */
88457   Select *pSelect       /* SELECT used to determine types and collations */
88458 ){
88459   sqlite3 *db = pParse->db;
88460   NameContext sNC;
88461   Column *pCol;
88462   CollSeq *pColl;
88463   int i;
88464   Expr *p;
88465   struct ExprList_item *a;
88466
88467   assert( pSelect!=0 );
88468   assert( (pSelect->selFlags & SF_Resolved)!=0 );
88469   assert( nCol==pSelect->pEList->nExpr || db->mallocFailed );
88470   if( db->mallocFailed ) return;
88471   memset(&sNC, 0, sizeof(sNC));
88472   sNC.pSrcList = pSelect->pSrc;
88473   a = pSelect->pEList->a;
88474   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
88475     p = a[i].pExpr;
88476     pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
88477     pCol->affinity = sqlite3ExprAffinity(p);
88478     if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
88479     pColl = sqlite3ExprCollSeq(pParse, p);
88480     if( pColl ){
88481       pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
88482     }
88483   }
88484 }
88485
88486 /*
88487 ** Given a SELECT statement, generate a Table structure that describes
88488 ** the result set of that SELECT.
88489 */
88490 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
88491   Table *pTab;
88492   sqlite3 *db = pParse->db;
88493   int savedFlags;
88494
88495   savedFlags = db->flags;
88496   db->flags &= ~SQLITE_FullColNames;
88497   db->flags |= SQLITE_ShortColNames;
88498   sqlite3SelectPrep(pParse, pSelect, 0);
88499   if( pParse->nErr ) return 0;
88500   while( pSelect->pPrior ) pSelect = pSelect->pPrior;
88501   db->flags = savedFlags;
88502   pTab = sqlite3DbMallocZero(db, sizeof(Table) );
88503   if( pTab==0 ){
88504     return 0;
88505   }
88506   /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
88507   ** is disabled */
88508   assert( db->lookaside.bEnabled==0 );
88509   pTab->nRef = 1;
88510   pTab->zName = 0;
88511   selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
88512   selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSelect);
88513   pTab->iPKey = -1;
88514   if( db->mallocFailed ){
88515     sqlite3DeleteTable(db, pTab);
88516     return 0;
88517   }
88518   return pTab;
88519 }
88520
88521 /*
88522 ** Get a VDBE for the given parser context.  Create a new one if necessary.
88523 ** If an error occurs, return NULL and leave a message in pParse.
88524 */
88525 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
88526   Vdbe *v = pParse->pVdbe;
88527   if( v==0 ){
88528     v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
88529 #ifndef SQLITE_OMIT_TRACE
88530     if( v ){
88531       sqlite3VdbeAddOp0(v, OP_Trace);
88532     }
88533 #endif
88534   }
88535   return v;
88536 }
88537
88538
88539 /*
88540 ** Compute the iLimit and iOffset fields of the SELECT based on the
88541 ** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
88542 ** that appear in the original SQL statement after the LIMIT and OFFSET
88543 ** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset 
88544 ** are the integer memory register numbers for counters used to compute 
88545 ** the limit and offset.  If there is no limit and/or offset, then 
88546 ** iLimit and iOffset are negative.
88547 **
88548 ** This routine changes the values of iLimit and iOffset only if
88549 ** a limit or offset is defined by pLimit and pOffset.  iLimit and
88550 ** iOffset should have been preset to appropriate default values
88551 ** (usually but not always -1) prior to calling this routine.
88552 ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
88553 ** redefined.  The UNION ALL operator uses this property to force
88554 ** the reuse of the same limit and offset registers across multiple
88555 ** SELECT statements.
88556 */
88557 static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
88558   Vdbe *v = 0;
88559   int iLimit = 0;
88560   int iOffset;
88561   int addr1, n;
88562   if( p->iLimit ) return;
88563
88564   /* 
88565   ** "LIMIT -1" always shows all rows.  There is some
88566   ** contraversy about what the correct behavior should be.
88567   ** The current implementation interprets "LIMIT 0" to mean
88568   ** no rows.
88569   */
88570   sqlite3ExprCacheClear(pParse);
88571   assert( p->pOffset==0 || p->pLimit!=0 );
88572   if( p->pLimit ){
88573     p->iLimit = iLimit = ++pParse->nMem;
88574     v = sqlite3GetVdbe(pParse);
88575     if( NEVER(v==0) ) return;  /* VDBE should have already been allocated */
88576     if( sqlite3ExprIsInteger(p->pLimit, &n) ){
88577       sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
88578       VdbeComment((v, "LIMIT counter"));
88579       if( n==0 ){
88580         sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
88581       }
88582     }else{
88583       sqlite3ExprCode(pParse, p->pLimit, iLimit);
88584       sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
88585       VdbeComment((v, "LIMIT counter"));
88586       sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
88587     }
88588     if( p->pOffset ){
88589       p->iOffset = iOffset = ++pParse->nMem;
88590       pParse->nMem++;   /* Allocate an extra register for limit+offset */
88591       sqlite3ExprCode(pParse, p->pOffset, iOffset);
88592       sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
88593       VdbeComment((v, "OFFSET counter"));
88594       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
88595       sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
88596       sqlite3VdbeJumpHere(v, addr1);
88597       sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
88598       VdbeComment((v, "LIMIT+OFFSET"));
88599       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
88600       sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
88601       sqlite3VdbeJumpHere(v, addr1);
88602     }
88603   }
88604 }
88605
88606 #ifndef SQLITE_OMIT_COMPOUND_SELECT
88607 /*
88608 ** Return the appropriate collating sequence for the iCol-th column of
88609 ** the result set for the compound-select statement "p".  Return NULL if
88610 ** the column has no default collating sequence.
88611 **
88612 ** The collating sequence for the compound select is taken from the
88613 ** left-most term of the select that has a collating sequence.
88614 */
88615 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
88616   CollSeq *pRet;
88617   if( p->pPrior ){
88618     pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
88619   }else{
88620     pRet = 0;
88621   }
88622   assert( iCol>=0 );
88623   if( pRet==0 && iCol<p->pEList->nExpr ){
88624     pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
88625   }
88626   return pRet;
88627 }
88628 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
88629
88630 /* Forward reference */
88631 static int multiSelectOrderBy(
88632   Parse *pParse,        /* Parsing context */
88633   Select *p,            /* The right-most of SELECTs to be coded */
88634   SelectDest *pDest     /* What to do with query results */
88635 );
88636
88637
88638 #ifndef SQLITE_OMIT_COMPOUND_SELECT
88639 /*
88640 ** This routine is called to process a compound query form from
88641 ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
88642 ** INTERSECT
88643 **
88644 ** "p" points to the right-most of the two queries.  the query on the
88645 ** left is p->pPrior.  The left query could also be a compound query
88646 ** in which case this routine will be called recursively. 
88647 **
88648 ** The results of the total query are to be written into a destination
88649 ** of type eDest with parameter iParm.
88650 **
88651 ** Example 1:  Consider a three-way compound SQL statement.
88652 **
88653 **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
88654 **
88655 ** This statement is parsed up as follows:
88656 **
88657 **     SELECT c FROM t3
88658 **      |
88659 **      `----->  SELECT b FROM t2
88660 **                |
88661 **                `------>  SELECT a FROM t1
88662 **
88663 ** The arrows in the diagram above represent the Select.pPrior pointer.
88664 ** So if this routine is called with p equal to the t3 query, then
88665 ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
88666 **
88667 ** Notice that because of the way SQLite parses compound SELECTs, the
88668 ** individual selects always group from left to right.
88669 */
88670 static int multiSelect(
88671   Parse *pParse,        /* Parsing context */
88672   Select *p,            /* The right-most of SELECTs to be coded */
88673   SelectDest *pDest     /* What to do with query results */
88674 ){
88675   int rc = SQLITE_OK;   /* Success code from a subroutine */
88676   Select *pPrior;       /* Another SELECT immediately to our left */
88677   Vdbe *v;              /* Generate code to this VDBE */
88678   SelectDest dest;      /* Alternative data destination */
88679   Select *pDelete = 0;  /* Chain of simple selects to delete */
88680   sqlite3 *db;          /* Database connection */
88681
88682   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
88683   ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
88684   */
88685   assert( p && p->pPrior );  /* Calling function guarantees this much */
88686   db = pParse->db;
88687   pPrior = p->pPrior;
88688   assert( pPrior->pRightmost!=pPrior );
88689   assert( pPrior->pRightmost==p->pRightmost );
88690   dest = *pDest;
88691   if( pPrior->pOrderBy ){
88692     sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
88693       selectOpName(p->op));
88694     rc = 1;
88695     goto multi_select_end;
88696   }
88697   if( pPrior->pLimit ){
88698     sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
88699       selectOpName(p->op));
88700     rc = 1;
88701     goto multi_select_end;
88702   }
88703
88704   v = sqlite3GetVdbe(pParse);
88705   assert( v!=0 );  /* The VDBE already created by calling function */
88706
88707   /* Create the destination temporary table if necessary
88708   */
88709   if( dest.eDest==SRT_EphemTab ){
88710     assert( p->pEList );
88711     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iParm, p->pEList->nExpr);
88712     sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
88713     dest.eDest = SRT_Table;
88714   }
88715
88716   /* Make sure all SELECTs in the statement have the same number of elements
88717   ** in their result sets.
88718   */
88719   assert( p->pEList && pPrior->pEList );
88720   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
88721     sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
88722       " do not have the same number of result columns", selectOpName(p->op));
88723     rc = 1;
88724     goto multi_select_end;
88725   }
88726
88727   /* Compound SELECTs that have an ORDER BY clause are handled separately.
88728   */
88729   if( p->pOrderBy ){
88730     return multiSelectOrderBy(pParse, p, pDest);
88731   }
88732
88733   /* Generate code for the left and right SELECT statements.
88734   */
88735   switch( p->op ){
88736     case TK_ALL: {
88737       int addr = 0;
88738       assert( !pPrior->pLimit );
88739       pPrior->pLimit = p->pLimit;
88740       pPrior->pOffset = p->pOffset;
88741       rc = sqlite3Select(pParse, pPrior, &dest);
88742       p->pLimit = 0;
88743       p->pOffset = 0;
88744       if( rc ){
88745         goto multi_select_end;
88746       }
88747       p->pPrior = 0;
88748       p->iLimit = pPrior->iLimit;
88749       p->iOffset = pPrior->iOffset;
88750       if( p->iLimit ){
88751         addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
88752         VdbeComment((v, "Jump ahead if LIMIT reached"));
88753       }
88754       rc = sqlite3Select(pParse, p, &dest);
88755       testcase( rc!=SQLITE_OK );
88756       pDelete = p->pPrior;
88757       p->pPrior = pPrior;
88758       if( addr ){
88759         sqlite3VdbeJumpHere(v, addr);
88760       }
88761       break;
88762     }
88763     case TK_EXCEPT:
88764     case TK_UNION: {
88765       int unionTab;    /* Cursor number of the temporary table holding result */
88766       u8 op = 0;       /* One of the SRT_ operations to apply to self */
88767       int priorOp;     /* The SRT_ operation to apply to prior selects */
88768       Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
88769       int addr;
88770       SelectDest uniondest;
88771
88772       testcase( p->op==TK_EXCEPT );
88773       testcase( p->op==TK_UNION );
88774       priorOp = SRT_Union;
88775       if( dest.eDest==priorOp && ALWAYS(!p->pLimit &&!p->pOffset) ){
88776         /* We can reuse a temporary table generated by a SELECT to our
88777         ** right.
88778         */
88779         assert( p->pRightmost!=p );  /* Can only happen for leftward elements
88780                                      ** of a 3-way or more compound */
88781         assert( p->pLimit==0 );      /* Not allowed on leftward elements */
88782         assert( p->pOffset==0 );     /* Not allowed on leftward elements */
88783         unionTab = dest.iParm;
88784       }else{
88785         /* We will need to create our own temporary table to hold the
88786         ** intermediate results.
88787         */
88788         unionTab = pParse->nTab++;
88789         assert( p->pOrderBy==0 );
88790         addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
88791         assert( p->addrOpenEphm[0] == -1 );
88792         p->addrOpenEphm[0] = addr;
88793         p->pRightmost->selFlags |= SF_UsesEphemeral;
88794         assert( p->pEList );
88795       }
88796
88797       /* Code the SELECT statements to our left
88798       */
88799       assert( !pPrior->pOrderBy );
88800       sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
88801       rc = sqlite3Select(pParse, pPrior, &uniondest);
88802       if( rc ){
88803         goto multi_select_end;
88804       }
88805
88806       /* Code the current SELECT statement
88807       */
88808       if( p->op==TK_EXCEPT ){
88809         op = SRT_Except;
88810       }else{
88811         assert( p->op==TK_UNION );
88812         op = SRT_Union;
88813       }
88814       p->pPrior = 0;
88815       pLimit = p->pLimit;
88816       p->pLimit = 0;
88817       pOffset = p->pOffset;
88818       p->pOffset = 0;
88819       uniondest.eDest = op;
88820       rc = sqlite3Select(pParse, p, &uniondest);
88821       testcase( rc!=SQLITE_OK );
88822       /* Query flattening in sqlite3Select() might refill p->pOrderBy.
88823       ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
88824       sqlite3ExprListDelete(db, p->pOrderBy);
88825       pDelete = p->pPrior;
88826       p->pPrior = pPrior;
88827       p->pOrderBy = 0;
88828       sqlite3ExprDelete(db, p->pLimit);
88829       p->pLimit = pLimit;
88830       p->pOffset = pOffset;
88831       p->iLimit = 0;
88832       p->iOffset = 0;
88833
88834       /* Convert the data in the temporary table into whatever form
88835       ** it is that we currently need.
88836       */
88837       assert( unionTab==dest.iParm || dest.eDest!=priorOp );
88838       if( dest.eDest!=priorOp ){
88839         int iCont, iBreak, iStart;
88840         assert( p->pEList );
88841         if( dest.eDest==SRT_Output ){
88842           Select *pFirst = p;
88843           while( pFirst->pPrior ) pFirst = pFirst->pPrior;
88844           generateColumnNames(pParse, 0, pFirst->pEList);
88845         }
88846         iBreak = sqlite3VdbeMakeLabel(v);
88847         iCont = sqlite3VdbeMakeLabel(v);
88848         computeLimitRegisters(pParse, p, iBreak);
88849         sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
88850         iStart = sqlite3VdbeCurrentAddr(v);
88851         selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
88852                         0, -1, &dest, iCont, iBreak);
88853         sqlite3VdbeResolveLabel(v, iCont);
88854         sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
88855         sqlite3VdbeResolveLabel(v, iBreak);
88856         sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
88857       }
88858       break;
88859     }
88860     default: assert( p->op==TK_INTERSECT ); {
88861       int tab1, tab2;
88862       int iCont, iBreak, iStart;
88863       Expr *pLimit, *pOffset;
88864       int addr;
88865       SelectDest intersectdest;
88866       int r1;
88867
88868       /* INTERSECT is different from the others since it requires
88869       ** two temporary tables.  Hence it has its own case.  Begin
88870       ** by allocating the tables we will need.
88871       */
88872       tab1 = pParse->nTab++;
88873       tab2 = pParse->nTab++;
88874       assert( p->pOrderBy==0 );
88875
88876       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
88877       assert( p->addrOpenEphm[0] == -1 );
88878       p->addrOpenEphm[0] = addr;
88879       p->pRightmost->selFlags |= SF_UsesEphemeral;
88880       assert( p->pEList );
88881
88882       /* Code the SELECTs to our left into temporary table "tab1".
88883       */
88884       sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
88885       rc = sqlite3Select(pParse, pPrior, &intersectdest);
88886       if( rc ){
88887         goto multi_select_end;
88888       }
88889
88890       /* Code the current SELECT into temporary table "tab2"
88891       */
88892       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
88893       assert( p->addrOpenEphm[1] == -1 );
88894       p->addrOpenEphm[1] = addr;
88895       p->pPrior = 0;
88896       pLimit = p->pLimit;
88897       p->pLimit = 0;
88898       pOffset = p->pOffset;
88899       p->pOffset = 0;
88900       intersectdest.iParm = tab2;
88901       rc = sqlite3Select(pParse, p, &intersectdest);
88902       testcase( rc!=SQLITE_OK );
88903       pDelete = p->pPrior;
88904       p->pPrior = pPrior;
88905       sqlite3ExprDelete(db, p->pLimit);
88906       p->pLimit = pLimit;
88907       p->pOffset = pOffset;
88908
88909       /* Generate code to take the intersection of the two temporary
88910       ** tables.
88911       */
88912       assert( p->pEList );
88913       if( dest.eDest==SRT_Output ){
88914         Select *pFirst = p;
88915         while( pFirst->pPrior ) pFirst = pFirst->pPrior;
88916         generateColumnNames(pParse, 0, pFirst->pEList);
88917       }
88918       iBreak = sqlite3VdbeMakeLabel(v);
88919       iCont = sqlite3VdbeMakeLabel(v);
88920       computeLimitRegisters(pParse, p, iBreak);
88921       sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
88922       r1 = sqlite3GetTempReg(pParse);
88923       iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
88924       sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
88925       sqlite3ReleaseTempReg(pParse, r1);
88926       selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
88927                       0, -1, &dest, iCont, iBreak);
88928       sqlite3VdbeResolveLabel(v, iCont);
88929       sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
88930       sqlite3VdbeResolveLabel(v, iBreak);
88931       sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
88932       sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
88933       break;
88934     }
88935   }
88936
88937   /* Compute collating sequences used by 
88938   ** temporary tables needed to implement the compound select.
88939   ** Attach the KeyInfo structure to all temporary tables.
88940   **
88941   ** This section is run by the right-most SELECT statement only.
88942   ** SELECT statements to the left always skip this part.  The right-most
88943   ** SELECT might also skip this part if it has no ORDER BY clause and
88944   ** no temp tables are required.
88945   */
88946   if( p->selFlags & SF_UsesEphemeral ){
88947     int i;                        /* Loop counter */
88948     KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
88949     Select *pLoop;                /* For looping through SELECT statements */
88950     CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
88951     int nCol;                     /* Number of columns in result set */
88952
88953     assert( p->pRightmost==p );
88954     nCol = p->pEList->nExpr;
88955     pKeyInfo = sqlite3DbMallocZero(db,
88956                        sizeof(*pKeyInfo)+nCol*(sizeof(CollSeq*) + 1));
88957     if( !pKeyInfo ){
88958       rc = SQLITE_NOMEM;
88959       goto multi_select_end;
88960     }
88961
88962     pKeyInfo->enc = ENC(db);
88963     pKeyInfo->nField = (u16)nCol;
88964
88965     for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
88966       *apColl = multiSelectCollSeq(pParse, p, i);
88967       if( 0==*apColl ){
88968         *apColl = db->pDfltColl;
88969       }
88970     }
88971
88972     for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
88973       for(i=0; i<2; i++){
88974         int addr = pLoop->addrOpenEphm[i];
88975         if( addr<0 ){
88976           /* If [0] is unused then [1] is also unused.  So we can
88977           ** always safely abort as soon as the first unused slot is found */
88978           assert( pLoop->addrOpenEphm[1]<0 );
88979           break;
88980         }
88981         sqlite3VdbeChangeP2(v, addr, nCol);
88982         sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
88983         pLoop->addrOpenEphm[i] = -1;
88984       }
88985     }
88986     sqlite3DbFree(db, pKeyInfo);
88987   }
88988
88989 multi_select_end:
88990   pDest->iMem = dest.iMem;
88991   pDest->nMem = dest.nMem;
88992   sqlite3SelectDelete(db, pDelete);
88993   return rc;
88994 }
88995 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
88996
88997 /*
88998 ** Code an output subroutine for a coroutine implementation of a
88999 ** SELECT statment.
89000 **
89001 ** The data to be output is contained in pIn->iMem.  There are
89002 ** pIn->nMem columns to be output.  pDest is where the output should
89003 ** be sent.
89004 **
89005 ** regReturn is the number of the register holding the subroutine
89006 ** return address.
89007 **
89008 ** If regPrev>0 then it is the first register in a vector that
89009 ** records the previous output.  mem[regPrev] is a flag that is false
89010 ** if there has been no previous output.  If regPrev>0 then code is
89011 ** generated to suppress duplicates.  pKeyInfo is used for comparing
89012 ** keys.
89013 **
89014 ** If the LIMIT found in p->iLimit is reached, jump immediately to
89015 ** iBreak.
89016 */
89017 static int generateOutputSubroutine(
89018   Parse *pParse,          /* Parsing context */
89019   Select *p,              /* The SELECT statement */
89020   SelectDest *pIn,        /* Coroutine supplying data */
89021   SelectDest *pDest,      /* Where to send the data */
89022   int regReturn,          /* The return address register */
89023   int regPrev,            /* Previous result register.  No uniqueness if 0 */
89024   KeyInfo *pKeyInfo,      /* For comparing with previous entry */
89025   int p4type,             /* The p4 type for pKeyInfo */
89026   int iBreak              /* Jump here if we hit the LIMIT */
89027 ){
89028   Vdbe *v = pParse->pVdbe;
89029   int iContinue;
89030   int addr;
89031
89032   addr = sqlite3VdbeCurrentAddr(v);
89033   iContinue = sqlite3VdbeMakeLabel(v);
89034
89035   /* Suppress duplicates for UNION, EXCEPT, and INTERSECT 
89036   */
89037   if( regPrev ){
89038     int j1, j2;
89039     j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);
89040     j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iMem, regPrev+1, pIn->nMem,
89041                               (char*)pKeyInfo, p4type);
89042     sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
89043     sqlite3VdbeJumpHere(v, j1);
89044     sqlite3ExprCodeCopy(pParse, pIn->iMem, regPrev+1, pIn->nMem);
89045     sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
89046   }
89047   if( pParse->db->mallocFailed ) return 0;
89048
89049   /* Suppress the the first OFFSET entries if there is an OFFSET clause
89050   */
89051   codeOffset(v, p, iContinue);
89052
89053   switch( pDest->eDest ){
89054     /* Store the result as data using a unique key.
89055     */
89056     case SRT_Table:
89057     case SRT_EphemTab: {
89058       int r1 = sqlite3GetTempReg(pParse);
89059       int r2 = sqlite3GetTempReg(pParse);
89060       testcase( pDest->eDest==SRT_Table );
89061       testcase( pDest->eDest==SRT_EphemTab );
89062       sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iMem, pIn->nMem, r1);
89063       sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iParm, r2);
89064       sqlite3VdbeAddOp3(v, OP_Insert, pDest->iParm, r1, r2);
89065       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
89066       sqlite3ReleaseTempReg(pParse, r2);
89067       sqlite3ReleaseTempReg(pParse, r1);
89068       break;
89069     }
89070
89071 #ifndef SQLITE_OMIT_SUBQUERY
89072     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
89073     ** then there should be a single item on the stack.  Write this
89074     ** item into the set table with bogus data.
89075     */
89076     case SRT_Set: {
89077       int r1;
89078       assert( pIn->nMem==1 );
89079       p->affinity = 
89080          sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affinity);
89081       r1 = sqlite3GetTempReg(pParse);
89082       sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iMem, 1, r1, &p->affinity, 1);
89083       sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, 1);
89084       sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iParm, r1);
89085       sqlite3ReleaseTempReg(pParse, r1);
89086       break;
89087     }
89088
89089 #if 0  /* Never occurs on an ORDER BY query */
89090     /* If any row exist in the result set, record that fact and abort.
89091     */
89092     case SRT_Exists: {
89093       sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iParm);
89094       /* The LIMIT clause will terminate the loop for us */
89095       break;
89096     }
89097 #endif
89098
89099     /* If this is a scalar select that is part of an expression, then
89100     ** store the results in the appropriate memory cell and break out
89101     ** of the scan loop.
89102     */
89103     case SRT_Mem: {
89104       assert( pIn->nMem==1 );
89105       sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iParm, 1);
89106       /* The LIMIT clause will jump out of the loop for us */
89107       break;
89108     }
89109 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
89110
89111     /* The results are stored in a sequence of registers
89112     ** starting at pDest->iMem.  Then the co-routine yields.
89113     */
89114     case SRT_Coroutine: {
89115       if( pDest->iMem==0 ){
89116         pDest->iMem = sqlite3GetTempRange(pParse, pIn->nMem);
89117         pDest->nMem = pIn->nMem;
89118       }
89119       sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iMem, pDest->nMem);
89120       sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
89121       break;
89122     }
89123
89124     /* If none of the above, then the result destination must be
89125     ** SRT_Output.  This routine is never called with any other
89126     ** destination other than the ones handled above or SRT_Output.
89127     **
89128     ** For SRT_Output, results are stored in a sequence of registers.  
89129     ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
89130     ** return the next row of result.
89131     */
89132     default: {
89133       assert( pDest->eDest==SRT_Output );
89134       sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iMem, pIn->nMem);
89135       sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, pIn->nMem);
89136       break;
89137     }
89138   }
89139
89140   /* Jump to the end of the loop if the LIMIT is reached.
89141   */
89142   if( p->iLimit ){
89143     sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
89144   }
89145
89146   /* Generate the subroutine return
89147   */
89148   sqlite3VdbeResolveLabel(v, iContinue);
89149   sqlite3VdbeAddOp1(v, OP_Return, regReturn);
89150
89151   return addr;
89152 }
89153
89154 /*
89155 ** Alternative compound select code generator for cases when there
89156 ** is an ORDER BY clause.
89157 **
89158 ** We assume a query of the following form:
89159 **
89160 **      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
89161 **
89162 ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
89163 ** is to code both <selectA> and <selectB> with the ORDER BY clause as
89164 ** co-routines.  Then run the co-routines in parallel and merge the results
89165 ** into the output.  In addition to the two coroutines (called selectA and
89166 ** selectB) there are 7 subroutines:
89167 **
89168 **    outA:    Move the output of the selectA coroutine into the output
89169 **             of the compound query.
89170 **
89171 **    outB:    Move the output of the selectB coroutine into the output
89172 **             of the compound query.  (Only generated for UNION and
89173 **             UNION ALL.  EXCEPT and INSERTSECT never output a row that
89174 **             appears only in B.)
89175 **
89176 **    AltB:    Called when there is data from both coroutines and A<B.
89177 **
89178 **    AeqB:    Called when there is data from both coroutines and A==B.
89179 **
89180 **    AgtB:    Called when there is data from both coroutines and A>B.
89181 **
89182 **    EofA:    Called when data is exhausted from selectA.
89183 **
89184 **    EofB:    Called when data is exhausted from selectB.
89185 **
89186 ** The implementation of the latter five subroutines depend on which 
89187 ** <operator> is used:
89188 **
89189 **
89190 **             UNION ALL         UNION            EXCEPT          INTERSECT
89191 **          -------------  -----------------  --------------  -----------------
89192 **   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
89193 **
89194 **   AeqB:   outA, nextA         nextA             nextA         outA, nextA
89195 **
89196 **   AgtB:   outB, nextB      outB, nextB          nextB            nextB
89197 **
89198 **   EofA:   outB, nextB      outB, nextB          halt             halt
89199 **
89200 **   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
89201 **
89202 ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
89203 ** causes an immediate jump to EofA and an EOF on B following nextB causes
89204 ** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
89205 ** following nextX causes a jump to the end of the select processing.
89206 **
89207 ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
89208 ** within the output subroutine.  The regPrev register set holds the previously
89209 ** output value.  A comparison is made against this value and the output
89210 ** is skipped if the next results would be the same as the previous.
89211 **
89212 ** The implementation plan is to implement the two coroutines and seven
89213 ** subroutines first, then put the control logic at the bottom.  Like this:
89214 **
89215 **          goto Init
89216 **     coA: coroutine for left query (A)
89217 **     coB: coroutine for right query (B)
89218 **    outA: output one row of A
89219 **    outB: output one row of B (UNION and UNION ALL only)
89220 **    EofA: ...
89221 **    EofB: ...
89222 **    AltB: ...
89223 **    AeqB: ...
89224 **    AgtB: ...
89225 **    Init: initialize coroutine registers
89226 **          yield coA
89227 **          if eof(A) goto EofA
89228 **          yield coB
89229 **          if eof(B) goto EofB
89230 **    Cmpr: Compare A, B
89231 **          Jump AltB, AeqB, AgtB
89232 **     End: ...
89233 **
89234 ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
89235 ** actually called using Gosub and they do not Return.  EofA and EofB loop
89236 ** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
89237 ** and AgtB jump to either L2 or to one of EofA or EofB.
89238 */
89239 #ifndef SQLITE_OMIT_COMPOUND_SELECT
89240 static int multiSelectOrderBy(
89241   Parse *pParse,        /* Parsing context */
89242   Select *p,            /* The right-most of SELECTs to be coded */
89243   SelectDest *pDest     /* What to do with query results */
89244 ){
89245   int i, j;             /* Loop counters */
89246   Select *pPrior;       /* Another SELECT immediately to our left */
89247   Vdbe *v;              /* Generate code to this VDBE */
89248   SelectDest destA;     /* Destination for coroutine A */
89249   SelectDest destB;     /* Destination for coroutine B */
89250   int regAddrA;         /* Address register for select-A coroutine */
89251   int regEofA;          /* Flag to indicate when select-A is complete */
89252   int regAddrB;         /* Address register for select-B coroutine */
89253   int regEofB;          /* Flag to indicate when select-B is complete */
89254   int addrSelectA;      /* Address of the select-A coroutine */
89255   int addrSelectB;      /* Address of the select-B coroutine */
89256   int regOutA;          /* Address register for the output-A subroutine */
89257   int regOutB;          /* Address register for the output-B subroutine */
89258   int addrOutA;         /* Address of the output-A subroutine */
89259   int addrOutB = 0;     /* Address of the output-B subroutine */
89260   int addrEofA;         /* Address of the select-A-exhausted subroutine */
89261   int addrEofB;         /* Address of the select-B-exhausted subroutine */
89262   int addrAltB;         /* Address of the A<B subroutine */
89263   int addrAeqB;         /* Address of the A==B subroutine */
89264   int addrAgtB;         /* Address of the A>B subroutine */
89265   int regLimitA;        /* Limit register for select-A */
89266   int regLimitB;        /* Limit register for select-A */
89267   int regPrev;          /* A range of registers to hold previous output */
89268   int savedLimit;       /* Saved value of p->iLimit */
89269   int savedOffset;      /* Saved value of p->iOffset */
89270   int labelCmpr;        /* Label for the start of the merge algorithm */
89271   int labelEnd;         /* Label for the end of the overall SELECT stmt */
89272   int j1;               /* Jump instructions that get retargetted */
89273   int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
89274   KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
89275   KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
89276   sqlite3 *db;          /* Database connection */
89277   ExprList *pOrderBy;   /* The ORDER BY clause */
89278   int nOrderBy;         /* Number of terms in the ORDER BY clause */
89279   int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
89280
89281   assert( p->pOrderBy!=0 );
89282   assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
89283   db = pParse->db;
89284   v = pParse->pVdbe;
89285   assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */
89286   labelEnd = sqlite3VdbeMakeLabel(v);
89287   labelCmpr = sqlite3VdbeMakeLabel(v);
89288
89289
89290   /* Patch up the ORDER BY clause
89291   */
89292   op = p->op;  
89293   pPrior = p->pPrior;
89294   assert( pPrior->pOrderBy==0 );
89295   pOrderBy = p->pOrderBy;
89296   assert( pOrderBy );
89297   nOrderBy = pOrderBy->nExpr;
89298
89299   /* For operators other than UNION ALL we have to make sure that
89300   ** the ORDER BY clause covers every term of the result set.  Add
89301   ** terms to the ORDER BY clause as necessary.
89302   */
89303   if( op!=TK_ALL ){
89304     for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
89305       struct ExprList_item *pItem;
89306       for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
89307         assert( pItem->iCol>0 );
89308         if( pItem->iCol==i ) break;
89309       }
89310       if( j==nOrderBy ){
89311         Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
89312         if( pNew==0 ) return SQLITE_NOMEM;
89313         pNew->flags |= EP_IntValue;
89314         pNew->u.iValue = i;
89315         pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
89316         pOrderBy->a[nOrderBy++].iCol = (u16)i;
89317       }
89318     }
89319   }
89320
89321   /* Compute the comparison permutation and keyinfo that is used with
89322   ** the permutation used to determine if the next
89323   ** row of results comes from selectA or selectB.  Also add explicit
89324   ** collations to the ORDER BY clause terms so that when the subqueries
89325   ** to the right and the left are evaluated, they use the correct
89326   ** collation.
89327   */
89328   aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
89329   if( aPermute ){
89330     struct ExprList_item *pItem;
89331     for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
89332       assert( pItem->iCol>0  && pItem->iCol<=p->pEList->nExpr );
89333       aPermute[i] = pItem->iCol - 1;
89334     }
89335     pKeyMerge =
89336       sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1));
89337     if( pKeyMerge ){
89338       pKeyMerge->aSortOrder = (u8*)&pKeyMerge->aColl[nOrderBy];
89339       pKeyMerge->nField = (u16)nOrderBy;
89340       pKeyMerge->enc = ENC(db);
89341       for(i=0; i<nOrderBy; i++){
89342         CollSeq *pColl;
89343         Expr *pTerm = pOrderBy->a[i].pExpr;
89344         if( pTerm->flags & EP_ExpCollate ){
89345           pColl = pTerm->pColl;
89346         }else{
89347           pColl = multiSelectCollSeq(pParse, p, aPermute[i]);
89348           pTerm->flags |= EP_ExpCollate;
89349           pTerm->pColl = pColl;
89350         }
89351         pKeyMerge->aColl[i] = pColl;
89352         pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder;
89353       }
89354     }
89355   }else{
89356     pKeyMerge = 0;
89357   }
89358
89359   /* Reattach the ORDER BY clause to the query.
89360   */
89361   p->pOrderBy = pOrderBy;
89362   pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
89363
89364   /* Allocate a range of temporary registers and the KeyInfo needed
89365   ** for the logic that removes duplicate result rows when the
89366   ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
89367   */
89368   if( op==TK_ALL ){
89369     regPrev = 0;
89370   }else{
89371     int nExpr = p->pEList->nExpr;
89372     assert( nOrderBy>=nExpr || db->mallocFailed );
89373     regPrev = sqlite3GetTempRange(pParse, nExpr+1);
89374     sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
89375     pKeyDup = sqlite3DbMallocZero(db,
89376                   sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) );
89377     if( pKeyDup ){
89378       pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr];
89379       pKeyDup->nField = (u16)nExpr;
89380       pKeyDup->enc = ENC(db);
89381       for(i=0; i<nExpr; i++){
89382         pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
89383         pKeyDup->aSortOrder[i] = 0;
89384       }
89385     }
89386   }
89387  
89388   /* Separate the left and the right query from one another
89389   */
89390   p->pPrior = 0;
89391   sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
89392   if( pPrior->pPrior==0 ){
89393     sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
89394   }
89395
89396   /* Compute the limit registers */
89397   computeLimitRegisters(pParse, p, labelEnd);
89398   if( p->iLimit && op==TK_ALL ){
89399     regLimitA = ++pParse->nMem;
89400     regLimitB = ++pParse->nMem;
89401     sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
89402                                   regLimitA);
89403     sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
89404   }else{
89405     regLimitA = regLimitB = 0;
89406   }
89407   sqlite3ExprDelete(db, p->pLimit);
89408   p->pLimit = 0;
89409   sqlite3ExprDelete(db, p->pOffset);
89410   p->pOffset = 0;
89411
89412   regAddrA = ++pParse->nMem;
89413   regEofA = ++pParse->nMem;
89414   regAddrB = ++pParse->nMem;
89415   regEofB = ++pParse->nMem;
89416   regOutA = ++pParse->nMem;
89417   regOutB = ++pParse->nMem;
89418   sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
89419   sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
89420
89421   /* Jump past the various subroutines and coroutines to the main
89422   ** merge loop
89423   */
89424   j1 = sqlite3VdbeAddOp0(v, OP_Goto);
89425   addrSelectA = sqlite3VdbeCurrentAddr(v);
89426
89427
89428   /* Generate a coroutine to evaluate the SELECT statement to the
89429   ** left of the compound operator - the "A" select.
89430   */
89431   VdbeNoopComment((v, "Begin coroutine for left SELECT"));
89432   pPrior->iLimit = regLimitA;
89433   sqlite3Select(pParse, pPrior, &destA);
89434   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA);
89435   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
89436   VdbeNoopComment((v, "End coroutine for left SELECT"));
89437
89438   /* Generate a coroutine to evaluate the SELECT statement on 
89439   ** the right - the "B" select
89440   */
89441   addrSelectB = sqlite3VdbeCurrentAddr(v);
89442   VdbeNoopComment((v, "Begin coroutine for right SELECT"));
89443   savedLimit = p->iLimit;
89444   savedOffset = p->iOffset;
89445   p->iLimit = regLimitB;
89446   p->iOffset = 0;  
89447   sqlite3Select(pParse, p, &destB);
89448   p->iLimit = savedLimit;
89449   p->iOffset = savedOffset;
89450   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB);
89451   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
89452   VdbeNoopComment((v, "End coroutine for right SELECT"));
89453
89454   /* Generate a subroutine that outputs the current row of the A
89455   ** select as the next output row of the compound select.
89456   */
89457   VdbeNoopComment((v, "Output routine for A"));
89458   addrOutA = generateOutputSubroutine(pParse,
89459                  p, &destA, pDest, regOutA,
89460                  regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd);
89461   
89462   /* Generate a subroutine that outputs the current row of the B
89463   ** select as the next output row of the compound select.
89464   */
89465   if( op==TK_ALL || op==TK_UNION ){
89466     VdbeNoopComment((v, "Output routine for B"));
89467     addrOutB = generateOutputSubroutine(pParse,
89468                  p, &destB, pDest, regOutB,
89469                  regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd);
89470   }
89471
89472   /* Generate a subroutine to run when the results from select A
89473   ** are exhausted and only data in select B remains.
89474   */
89475   VdbeNoopComment((v, "eof-A subroutine"));
89476   if( op==TK_EXCEPT || op==TK_INTERSECT ){
89477     addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd);
89478   }else{  
89479     addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd);
89480     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
89481     sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
89482     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
89483   }
89484
89485   /* Generate a subroutine to run when the results from select B
89486   ** are exhausted and only data in select A remains.
89487   */
89488   if( op==TK_INTERSECT ){
89489     addrEofB = addrEofA;
89490   }else{  
89491     VdbeNoopComment((v, "eof-B subroutine"));
89492     addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd);
89493     sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
89494     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
89495     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
89496   }
89497
89498   /* Generate code to handle the case of A<B
89499   */
89500   VdbeNoopComment((v, "A-lt-B subroutine"));
89501   addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
89502   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
89503   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
89504   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
89505
89506   /* Generate code to handle the case of A==B
89507   */
89508   if( op==TK_ALL ){
89509     addrAeqB = addrAltB;
89510   }else if( op==TK_INTERSECT ){
89511     addrAeqB = addrAltB;
89512     addrAltB++;
89513   }else{
89514     VdbeNoopComment((v, "A-eq-B subroutine"));
89515     addrAeqB =
89516     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
89517     sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
89518     sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
89519   }
89520
89521   /* Generate code to handle the case of A>B
89522   */
89523   VdbeNoopComment((v, "A-gt-B subroutine"));
89524   addrAgtB = sqlite3VdbeCurrentAddr(v);
89525   if( op==TK_ALL || op==TK_UNION ){
89526     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
89527   }
89528   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
89529   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
89530   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
89531
89532   /* This code runs once to initialize everything.
89533   */
89534   sqlite3VdbeJumpHere(v, j1);
89535   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA);
89536   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB);
89537   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);
89538   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);
89539   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
89540   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
89541
89542   /* Implement the main merge loop
89543   */
89544   sqlite3VdbeResolveLabel(v, labelCmpr);
89545   sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
89546   sqlite3VdbeAddOp4(v, OP_Compare, destA.iMem, destB.iMem, nOrderBy,
89547                          (char*)pKeyMerge, P4_KEYINFO_HANDOFF);
89548   sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
89549
89550   /* Release temporary registers
89551   */
89552   if( regPrev ){
89553     sqlite3ReleaseTempRange(pParse, regPrev, nOrderBy+1);
89554   }
89555
89556   /* Jump to the this point in order to terminate the query.
89557   */
89558   sqlite3VdbeResolveLabel(v, labelEnd);
89559
89560   /* Set the number of output columns
89561   */
89562   if( pDest->eDest==SRT_Output ){
89563     Select *pFirst = pPrior;
89564     while( pFirst->pPrior ) pFirst = pFirst->pPrior;
89565     generateColumnNames(pParse, 0, pFirst->pEList);
89566   }
89567
89568   /* Reassembly the compound query so that it will be freed correctly
89569   ** by the calling function */
89570   if( p->pPrior ){
89571     sqlite3SelectDelete(db, p->pPrior);
89572   }
89573   p->pPrior = pPrior;
89574
89575   /*** TBD:  Insert subroutine calls to close cursors on incomplete
89576   **** subqueries ****/
89577   return SQLITE_OK;
89578 }
89579 #endif
89580
89581 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
89582 /* Forward Declarations */
89583 static void substExprList(sqlite3*, ExprList*, int, ExprList*);
89584 static void substSelect(sqlite3*, Select *, int, ExprList *);
89585
89586 /*
89587 ** Scan through the expression pExpr.  Replace every reference to
89588 ** a column in table number iTable with a copy of the iColumn-th
89589 ** entry in pEList.  (But leave references to the ROWID column 
89590 ** unchanged.)
89591 **
89592 ** This routine is part of the flattening procedure.  A subquery
89593 ** whose result set is defined by pEList appears as entry in the
89594 ** FROM clause of a SELECT such that the VDBE cursor assigned to that
89595 ** FORM clause entry is iTable.  This routine make the necessary 
89596 ** changes to pExpr so that it refers directly to the source table
89597 ** of the subquery rather the result set of the subquery.
89598 */
89599 static Expr *substExpr(
89600   sqlite3 *db,        /* Report malloc errors to this connection */
89601   Expr *pExpr,        /* Expr in which substitution occurs */
89602   int iTable,         /* Table to be substituted */
89603   ExprList *pEList    /* Substitute expressions */
89604 ){
89605   if( pExpr==0 ) return 0;
89606   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
89607     if( pExpr->iColumn<0 ){
89608       pExpr->op = TK_NULL;
89609     }else{
89610       Expr *pNew;
89611       assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
89612       assert( pExpr->pLeft==0 && pExpr->pRight==0 );
89613       pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
89614       if( pNew && pExpr->pColl ){
89615         pNew->pColl = pExpr->pColl;
89616       }
89617       sqlite3ExprDelete(db, pExpr);
89618       pExpr = pNew;
89619     }
89620   }else{
89621     pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
89622     pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
89623     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
89624       substSelect(db, pExpr->x.pSelect, iTable, pEList);
89625     }else{
89626       substExprList(db, pExpr->x.pList, iTable, pEList);
89627     }
89628   }
89629   return pExpr;
89630 }
89631 static void substExprList(
89632   sqlite3 *db,         /* Report malloc errors here */
89633   ExprList *pList,     /* List to scan and in which to make substitutes */
89634   int iTable,          /* Table to be substituted */
89635   ExprList *pEList     /* Substitute values */
89636 ){
89637   int i;
89638   if( pList==0 ) return;
89639   for(i=0; i<pList->nExpr; i++){
89640     pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
89641   }
89642 }
89643 static void substSelect(
89644   sqlite3 *db,         /* Report malloc errors here */
89645   Select *p,           /* SELECT statement in which to make substitutions */
89646   int iTable,          /* Table to be replaced */
89647   ExprList *pEList     /* Substitute values */
89648 ){
89649   SrcList *pSrc;
89650   struct SrcList_item *pItem;
89651   int i;
89652   if( !p ) return;
89653   substExprList(db, p->pEList, iTable, pEList);
89654   substExprList(db, p->pGroupBy, iTable, pEList);
89655   substExprList(db, p->pOrderBy, iTable, pEList);
89656   p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
89657   p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
89658   substSelect(db, p->pPrior, iTable, pEList);
89659   pSrc = p->pSrc;
89660   assert( pSrc );  /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
89661   if( ALWAYS(pSrc) ){
89662     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
89663       substSelect(db, pItem->pSelect, iTable, pEList);
89664     }
89665   }
89666 }
89667 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
89668
89669 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
89670 /*
89671 ** This routine attempts to flatten subqueries in order to speed
89672 ** execution.  It returns 1 if it makes changes and 0 if no flattening
89673 ** occurs.
89674 **
89675 ** To understand the concept of flattening, consider the following
89676 ** query:
89677 **
89678 **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
89679 **
89680 ** The default way of implementing this query is to execute the
89681 ** subquery first and store the results in a temporary table, then
89682 ** run the outer query on that temporary table.  This requires two
89683 ** passes over the data.  Furthermore, because the temporary table
89684 ** has no indices, the WHERE clause on the outer query cannot be
89685 ** optimized.
89686 **
89687 ** This routine attempts to rewrite queries such as the above into
89688 ** a single flat select, like this:
89689 **
89690 **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
89691 **
89692 ** The code generated for this simpification gives the same result
89693 ** but only has to scan the data once.  And because indices might 
89694 ** exist on the table t1, a complete scan of the data might be
89695 ** avoided.
89696 **
89697 ** Flattening is only attempted if all of the following are true:
89698 **
89699 **   (1)  The subquery and the outer query do not both use aggregates.
89700 **
89701 **   (2)  The subquery is not an aggregate or the outer query is not a join.
89702 **
89703 **   (3)  The subquery is not the right operand of a left outer join
89704 **        (Originally ticket #306.  Strengthened by ticket #3300)
89705 **
89706 **   (4)  The subquery is not DISTINCT.
89707 **
89708 **  (**)  At one point restrictions (4) and (5) defined a subset of DISTINCT
89709 **        sub-queries that were excluded from this optimization. Restriction 
89710 **        (4) has since been expanded to exclude all DISTINCT subqueries.
89711 **
89712 **   (6)  The subquery does not use aggregates or the outer query is not
89713 **        DISTINCT.
89714 **
89715 **   (7)  The subquery has a FROM clause.
89716 **
89717 **   (8)  The subquery does not use LIMIT or the outer query is not a join.
89718 **
89719 **   (9)  The subquery does not use LIMIT or the outer query does not use
89720 **        aggregates.
89721 **
89722 **  (10)  The subquery does not use aggregates or the outer query does not
89723 **        use LIMIT.
89724 **
89725 **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
89726 **
89727 **  (**)  Not implemented.  Subsumed into restriction (3).  Was previously
89728 **        a separate restriction deriving from ticket #350.
89729 **
89730 **  (13)  The subquery and outer query do not both use LIMIT.
89731 **
89732 **  (14)  The subquery does not use OFFSET.
89733 **
89734 **  (15)  The outer query is not part of a compound select or the
89735 **        subquery does not have a LIMIT clause.
89736 **        (See ticket #2339 and ticket [02a8e81d44]).
89737 **
89738 **  (16)  The outer query is not an aggregate or the subquery does
89739 **        not contain ORDER BY.  (Ticket #2942)  This used to not matter
89740 **        until we introduced the group_concat() function.  
89741 **
89742 **  (17)  The sub-query is not a compound select, or it is a UNION ALL 
89743 **        compound clause made up entirely of non-aggregate queries, and 
89744 **        the parent query:
89745 **
89746 **          * is not itself part of a compound select,
89747 **          * is not an aggregate or DISTINCT query, and
89748 **          * has no other tables or sub-selects in the FROM clause.
89749 **
89750 **        The parent and sub-query may contain WHERE clauses. Subject to
89751 **        rules (11), (13) and (14), they may also contain ORDER BY,
89752 **        LIMIT and OFFSET clauses.
89753 **
89754 **  (18)  If the sub-query is a compound select, then all terms of the
89755 **        ORDER by clause of the parent must be simple references to 
89756 **        columns of the sub-query.
89757 **
89758 **  (19)  The subquery does not use LIMIT or the outer query does not
89759 **        have a WHERE clause.
89760 **
89761 **  (20)  If the sub-query is a compound select, then it must not use
89762 **        an ORDER BY clause.  Ticket #3773.  We could relax this constraint
89763 **        somewhat by saying that the terms of the ORDER BY clause must
89764 **        appear as unmodified result columns in the outer query.  But
89765 **        have other optimizations in mind to deal with that case.
89766 **
89767 ** In this routine, the "p" parameter is a pointer to the outer query.
89768 ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
89769 ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
89770 **
89771 ** If flattening is not attempted, this routine is a no-op and returns 0.
89772 ** If flattening is attempted this routine returns 1.
89773 **
89774 ** All of the expression analysis must occur on both the outer query and
89775 ** the subquery before this routine runs.
89776 */
89777 static int flattenSubquery(
89778   Parse *pParse,       /* Parsing context */
89779   Select *p,           /* The parent or outer SELECT statement */
89780   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
89781   int isAgg,           /* True if outer SELECT uses aggregate functions */
89782   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
89783 ){
89784   const char *zSavedAuthContext = pParse->zAuthContext;
89785   Select *pParent;
89786   Select *pSub;       /* The inner query or "subquery" */
89787   Select *pSub1;      /* Pointer to the rightmost select in sub-query */
89788   SrcList *pSrc;      /* The FROM clause of the outer query */
89789   SrcList *pSubSrc;   /* The FROM clause of the subquery */
89790   ExprList *pList;    /* The result set of the outer query */
89791   int iParent;        /* VDBE cursor number of the pSub result set temp table */
89792   int i;              /* Loop counter */
89793   Expr *pWhere;                    /* The WHERE clause */
89794   struct SrcList_item *pSubitem;   /* The subquery */
89795   sqlite3 *db = pParse->db;
89796
89797   /* Check to see if flattening is permitted.  Return 0 if not.
89798   */
89799   assert( p!=0 );
89800   assert( p->pPrior==0 );  /* Unable to flatten compound queries */
89801   if( db->flags & SQLITE_QueryFlattener ) return 0;
89802   pSrc = p->pSrc;
89803   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
89804   pSubitem = &pSrc->a[iFrom];
89805   iParent = pSubitem->iCursor;
89806   pSub = pSubitem->pSelect;
89807   assert( pSub!=0 );
89808   if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
89809   if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
89810   pSubSrc = pSub->pSrc;
89811   assert( pSubSrc );
89812   /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
89813   ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
89814   ** because they could be computed at compile-time.  But when LIMIT and OFFSET
89815   ** became arbitrary expressions, we were forced to add restrictions (13)
89816   ** and (14). */
89817   if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
89818   if( pSub->pOffset ) return 0;                          /* Restriction (14) */
89819   if( p->pRightmost && pSub->pLimit ){
89820     return 0;                                            /* Restriction (15) */
89821   }
89822   if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
89823   if( pSub->selFlags & SF_Distinct ) return 0;           /* Restriction (5)  */
89824   if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
89825      return 0;         /* Restrictions (8)(9) */
89826   }
89827   if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
89828      return 0;         /* Restriction (6)  */
89829   }
89830   if( p->pOrderBy && pSub->pOrderBy ){
89831      return 0;                                           /* Restriction (11) */
89832   }
89833   if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
89834   if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
89835
89836   /* OBSOLETE COMMENT 1:
89837   ** Restriction 3:  If the subquery is a join, make sure the subquery is 
89838   ** not used as the right operand of an outer join.  Examples of why this
89839   ** is not allowed:
89840   **
89841   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
89842   **
89843   ** If we flatten the above, we would get
89844   **
89845   **         (t1 LEFT OUTER JOIN t2) JOIN t3
89846   **
89847   ** which is not at all the same thing.
89848   **
89849   ** OBSOLETE COMMENT 2:
89850   ** Restriction 12:  If the subquery is the right operand of a left outer
89851   ** join, make sure the subquery has no WHERE clause.
89852   ** An examples of why this is not allowed:
89853   **
89854   **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
89855   **
89856   ** If we flatten the above, we would get
89857   **
89858   **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
89859   **
89860   ** But the t2.x>0 test will always fail on a NULL row of t2, which
89861   ** effectively converts the OUTER JOIN into an INNER JOIN.
89862   **
89863   ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
89864   ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
89865   ** is fraught with danger.  Best to avoid the whole thing.  If the
89866   ** subquery is the right term of a LEFT JOIN, then do not flatten.
89867   */
89868   if( (pSubitem->jointype & JT_OUTER)!=0 ){
89869     return 0;
89870   }
89871
89872   /* Restriction 17: If the sub-query is a compound SELECT, then it must
89873   ** use only the UNION ALL operator. And none of the simple select queries
89874   ** that make up the compound SELECT are allowed to be aggregate or distinct
89875   ** queries.
89876   */
89877   if( pSub->pPrior ){
89878     if( pSub->pOrderBy ){
89879       return 0;  /* Restriction 20 */
89880     }
89881     if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
89882       return 0;
89883     }
89884     for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
89885       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
89886       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
89887       if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
89888        || (pSub1->pPrior && pSub1->op!=TK_ALL) 
89889        || NEVER(pSub1->pSrc==0) || pSub1->pSrc->nSrc!=1
89890       ){
89891         return 0;
89892       }
89893     }
89894
89895     /* Restriction 18. */
89896     if( p->pOrderBy ){
89897       int ii;
89898       for(ii=0; ii<p->pOrderBy->nExpr; ii++){
89899         if( p->pOrderBy->a[ii].iCol==0 ) return 0;
89900       }
89901     }
89902   }
89903
89904   /***** If we reach this point, flattening is permitted. *****/
89905
89906   /* Authorize the subquery */
89907   pParse->zAuthContext = pSubitem->zName;
89908   sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
89909   pParse->zAuthContext = zSavedAuthContext;
89910
89911   /* If the sub-query is a compound SELECT statement, then (by restrictions
89912   ** 17 and 18 above) it must be a UNION ALL and the parent query must 
89913   ** be of the form:
89914   **
89915   **     SELECT <expr-list> FROM (<sub-query>) <where-clause> 
89916   **
89917   ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
89918   ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or 
89919   ** OFFSET clauses and joins them to the left-hand-side of the original
89920   ** using UNION ALL operators. In this case N is the number of simple
89921   ** select statements in the compound sub-query.
89922   **
89923   ** Example:
89924   **
89925   **     SELECT a+1 FROM (
89926   **        SELECT x FROM tab
89927   **        UNION ALL
89928   **        SELECT y FROM tab
89929   **        UNION ALL
89930   **        SELECT abs(z*2) FROM tab2
89931   **     ) WHERE a!=5 ORDER BY 1
89932   **
89933   ** Transformed into:
89934   **
89935   **     SELECT x+1 FROM tab WHERE x+1!=5
89936   **     UNION ALL
89937   **     SELECT y+1 FROM tab WHERE y+1!=5
89938   **     UNION ALL
89939   **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
89940   **     ORDER BY 1
89941   **
89942   ** We call this the "compound-subquery flattening".
89943   */
89944   for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
89945     Select *pNew;
89946     ExprList *pOrderBy = p->pOrderBy;
89947     Expr *pLimit = p->pLimit;
89948     Select *pPrior = p->pPrior;
89949     p->pOrderBy = 0;
89950     p->pSrc = 0;
89951     p->pPrior = 0;
89952     p->pLimit = 0;
89953     pNew = sqlite3SelectDup(db, p, 0);
89954     p->pLimit = pLimit;
89955     p->pOrderBy = pOrderBy;
89956     p->pSrc = pSrc;
89957     p->op = TK_ALL;
89958     p->pRightmost = 0;
89959     if( pNew==0 ){
89960       pNew = pPrior;
89961     }else{
89962       pNew->pPrior = pPrior;
89963       pNew->pRightmost = 0;
89964     }
89965     p->pPrior = pNew;
89966     if( db->mallocFailed ) return 1;
89967   }
89968
89969   /* Begin flattening the iFrom-th entry of the FROM clause 
89970   ** in the outer query.
89971   */
89972   pSub = pSub1 = pSubitem->pSelect;
89973
89974   /* Delete the transient table structure associated with the
89975   ** subquery
89976   */
89977   sqlite3DbFree(db, pSubitem->zDatabase);
89978   sqlite3DbFree(db, pSubitem->zName);
89979   sqlite3DbFree(db, pSubitem->zAlias);
89980   pSubitem->zDatabase = 0;
89981   pSubitem->zName = 0;
89982   pSubitem->zAlias = 0;
89983   pSubitem->pSelect = 0;
89984
89985   /* Defer deleting the Table object associated with the
89986   ** subquery until code generation is
89987   ** complete, since there may still exist Expr.pTab entries that
89988   ** refer to the subquery even after flattening.  Ticket #3346.
89989   **
89990   ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
89991   */
89992   if( ALWAYS(pSubitem->pTab!=0) ){
89993     Table *pTabToDel = pSubitem->pTab;
89994     if( pTabToDel->nRef==1 ){
89995       Parse *pToplevel = sqlite3ParseToplevel(pParse);
89996       pTabToDel->pNextZombie = pToplevel->pZombieTab;
89997       pToplevel->pZombieTab = pTabToDel;
89998     }else{
89999       pTabToDel->nRef--;
90000     }
90001     pSubitem->pTab = 0;
90002   }
90003
90004   /* The following loop runs once for each term in a compound-subquery
90005   ** flattening (as described above).  If we are doing a different kind
90006   ** of flattening - a flattening other than a compound-subquery flattening -
90007   ** then this loop only runs once.
90008   **
90009   ** This loop moves all of the FROM elements of the subquery into the
90010   ** the FROM clause of the outer query.  Before doing this, remember
90011   ** the cursor number for the original outer query FROM element in
90012   ** iParent.  The iParent cursor will never be used.  Subsequent code
90013   ** will scan expressions looking for iParent references and replace
90014   ** those references with expressions that resolve to the subquery FROM
90015   ** elements we are now copying in.
90016   */
90017   for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
90018     int nSubSrc;
90019     u8 jointype = 0;
90020     pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
90021     nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
90022     pSrc = pParent->pSrc;     /* FROM clause of the outer query */
90023
90024     if( pSrc ){
90025       assert( pParent==p );  /* First time through the loop */
90026       jointype = pSubitem->jointype;
90027     }else{
90028       assert( pParent!=p );  /* 2nd and subsequent times through the loop */
90029       pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
90030       if( pSrc==0 ){
90031         assert( db->mallocFailed );
90032         break;
90033       }
90034     }
90035
90036     /* The subquery uses a single slot of the FROM clause of the outer
90037     ** query.  If the subquery has more than one element in its FROM clause,
90038     ** then expand the outer query to make space for it to hold all elements
90039     ** of the subquery.
90040     **
90041     ** Example:
90042     **
90043     **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
90044     **
90045     ** The outer query has 3 slots in its FROM clause.  One slot of the
90046     ** outer query (the middle slot) is used by the subquery.  The next
90047     ** block of code will expand the out query to 4 slots.  The middle
90048     ** slot is expanded to two slots in order to make space for the
90049     ** two elements in the FROM clause of the subquery.
90050     */
90051     if( nSubSrc>1 ){
90052       pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
90053       if( db->mallocFailed ){
90054         break;
90055       }
90056     }
90057
90058     /* Transfer the FROM clause terms from the subquery into the
90059     ** outer query.
90060     */
90061     for(i=0; i<nSubSrc; i++){
90062       sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
90063       pSrc->a[i+iFrom] = pSubSrc->a[i];
90064       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
90065     }
90066     pSrc->a[iFrom].jointype = jointype;
90067   
90068     /* Now begin substituting subquery result set expressions for 
90069     ** references to the iParent in the outer query.
90070     ** 
90071     ** Example:
90072     **
90073     **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
90074     **   \                     \_____________ subquery __________/          /
90075     **    \_____________________ outer query ______________________________/
90076     **
90077     ** We look at every expression in the outer query and every place we see
90078     ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
90079     */
90080     pList = pParent->pEList;
90081     for(i=0; i<pList->nExpr; i++){
90082       if( pList->a[i].zName==0 ){
90083         const char *zSpan = pList->a[i].zSpan;
90084         if( ALWAYS(zSpan) ){
90085           pList->a[i].zName = sqlite3DbStrDup(db, zSpan);
90086         }
90087       }
90088     }
90089     substExprList(db, pParent->pEList, iParent, pSub->pEList);
90090     if( isAgg ){
90091       substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
90092       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
90093     }
90094     if( pSub->pOrderBy ){
90095       assert( pParent->pOrderBy==0 );
90096       pParent->pOrderBy = pSub->pOrderBy;
90097       pSub->pOrderBy = 0;
90098     }else if( pParent->pOrderBy ){
90099       substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
90100     }
90101     if( pSub->pWhere ){
90102       pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
90103     }else{
90104       pWhere = 0;
90105     }
90106     if( subqueryIsAgg ){
90107       assert( pParent->pHaving==0 );
90108       pParent->pHaving = pParent->pWhere;
90109       pParent->pWhere = pWhere;
90110       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
90111       pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving, 
90112                                   sqlite3ExprDup(db, pSub->pHaving, 0));
90113       assert( pParent->pGroupBy==0 );
90114       pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
90115     }else{
90116       pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
90117       pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
90118     }
90119   
90120     /* The flattened query is distinct if either the inner or the
90121     ** outer query is distinct. 
90122     */
90123     pParent->selFlags |= pSub->selFlags & SF_Distinct;
90124   
90125     /*
90126     ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
90127     **
90128     ** One is tempted to try to add a and b to combine the limits.  But this
90129     ** does not work if either limit is negative.
90130     */
90131     if( pSub->pLimit ){
90132       pParent->pLimit = pSub->pLimit;
90133       pSub->pLimit = 0;
90134     }
90135   }
90136
90137   /* Finially, delete what is left of the subquery and return
90138   ** success.
90139   */
90140   sqlite3SelectDelete(db, pSub1);
90141
90142   return 1;
90143 }
90144 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
90145
90146 /*
90147 ** Analyze the SELECT statement passed as an argument to see if it
90148 ** is a min() or max() query. Return WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX if 
90149 ** it is, or 0 otherwise. At present, a query is considered to be
90150 ** a min()/max() query if:
90151 **
90152 **   1. There is a single object in the FROM clause.
90153 **
90154 **   2. There is a single expression in the result set, and it is
90155 **      either min(x) or max(x), where x is a column reference.
90156 */
90157 static u8 minMaxQuery(Select *p){
90158   Expr *pExpr;
90159   ExprList *pEList = p->pEList;
90160
90161   if( pEList->nExpr!=1 ) return WHERE_ORDERBY_NORMAL;
90162   pExpr = pEList->a[0].pExpr;
90163   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
90164   if( NEVER(ExprHasProperty(pExpr, EP_xIsSelect)) ) return 0;
90165   pEList = pExpr->x.pList;
90166   if( pEList==0 || pEList->nExpr!=1 ) return 0;
90167   if( pEList->a[0].pExpr->op!=TK_AGG_COLUMN ) return WHERE_ORDERBY_NORMAL;
90168   assert( !ExprHasProperty(pExpr, EP_IntValue) );
90169   if( sqlite3StrICmp(pExpr->u.zToken,"min")==0 ){
90170     return WHERE_ORDERBY_MIN;
90171   }else if( sqlite3StrICmp(pExpr->u.zToken,"max")==0 ){
90172     return WHERE_ORDERBY_MAX;
90173   }
90174   return WHERE_ORDERBY_NORMAL;
90175 }
90176
90177 /*
90178 ** The select statement passed as the first argument is an aggregate query.
90179 ** The second argment is the associated aggregate-info object. This 
90180 ** function tests if the SELECT is of the form:
90181 **
90182 **   SELECT count(*) FROM <tbl>
90183 **
90184 ** where table is a database table, not a sub-select or view. If the query
90185 ** does match this pattern, then a pointer to the Table object representing
90186 ** <tbl> is returned. Otherwise, 0 is returned.
90187 */
90188 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
90189   Table *pTab;
90190   Expr *pExpr;
90191
90192   assert( !p->pGroupBy );
90193
90194   if( p->pWhere || p->pEList->nExpr!=1 
90195    || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
90196   ){
90197     return 0;
90198   }
90199   pTab = p->pSrc->a[0].pTab;
90200   pExpr = p->pEList->a[0].pExpr;
90201   assert( pTab && !pTab->pSelect && pExpr );
90202
90203   if( IsVirtual(pTab) ) return 0;
90204   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
90205   if( (pAggInfo->aFunc[0].pFunc->flags&SQLITE_FUNC_COUNT)==0 ) return 0;
90206   if( pExpr->flags&EP_Distinct ) return 0;
90207
90208   return pTab;
90209 }
90210
90211 /*
90212 ** If the source-list item passed as an argument was augmented with an
90213 ** INDEXED BY clause, then try to locate the specified index. If there
90214 ** was such a clause and the named index cannot be found, return 
90215 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate 
90216 ** pFrom->pIndex and return SQLITE_OK.
90217 */
90218 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
90219   if( pFrom->pTab && pFrom->zIndex ){
90220     Table *pTab = pFrom->pTab;
90221     char *zIndex = pFrom->zIndex;
90222     Index *pIdx;
90223     for(pIdx=pTab->pIndex; 
90224         pIdx && sqlite3StrICmp(pIdx->zName, zIndex); 
90225         pIdx=pIdx->pNext
90226     );
90227     if( !pIdx ){
90228       sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
90229       pParse->checkSchema = 1;
90230       return SQLITE_ERROR;
90231     }
90232     pFrom->pIndex = pIdx;
90233   }
90234   return SQLITE_OK;
90235 }
90236
90237 /*
90238 ** This routine is a Walker callback for "expanding" a SELECT statement.
90239 ** "Expanding" means to do the following:
90240 **
90241 **    (1)  Make sure VDBE cursor numbers have been assigned to every
90242 **         element of the FROM clause.
90243 **
90244 **    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that 
90245 **         defines FROM clause.  When views appear in the FROM clause,
90246 **         fill pTabList->a[].pSelect with a copy of the SELECT statement
90247 **         that implements the view.  A copy is made of the view's SELECT
90248 **         statement so that we can freely modify or delete that statement
90249 **         without worrying about messing up the presistent representation
90250 **         of the view.
90251 **
90252 **    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
90253 **         on joins and the ON and USING clause of joins.
90254 **
90255 **    (4)  Scan the list of columns in the result set (pEList) looking
90256 **         for instances of the "*" operator or the TABLE.* operator.
90257 **         If found, expand each "*" to be every column in every table
90258 **         and TABLE.* to be every column in TABLE.
90259 **
90260 */
90261 static int selectExpander(Walker *pWalker, Select *p){
90262   Parse *pParse = pWalker->pParse;
90263   int i, j, k;
90264   SrcList *pTabList;
90265   ExprList *pEList;
90266   struct SrcList_item *pFrom;
90267   sqlite3 *db = pParse->db;
90268
90269   if( db->mallocFailed  ){
90270     return WRC_Abort;
90271   }
90272   if( NEVER(p->pSrc==0) || (p->selFlags & SF_Expanded)!=0 ){
90273     return WRC_Prune;
90274   }
90275   p->selFlags |= SF_Expanded;
90276   pTabList = p->pSrc;
90277   pEList = p->pEList;
90278
90279   /* Make sure cursor numbers have been assigned to all entries in
90280   ** the FROM clause of the SELECT statement.
90281   */
90282   sqlite3SrcListAssignCursors(pParse, pTabList);
90283
90284   /* Look up every table named in the FROM clause of the select.  If
90285   ** an entry of the FROM clause is a subquery instead of a table or view,
90286   ** then create a transient table structure to describe the subquery.
90287   */
90288   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
90289     Table *pTab;
90290     if( pFrom->pTab!=0 ){
90291       /* This statement has already been prepared.  There is no need
90292       ** to go further. */
90293       assert( i==0 );
90294       return WRC_Prune;
90295     }
90296     if( pFrom->zName==0 ){
90297 #ifndef SQLITE_OMIT_SUBQUERY
90298       Select *pSel = pFrom->pSelect;
90299       /* A sub-query in the FROM clause of a SELECT */
90300       assert( pSel!=0 );
90301       assert( pFrom->pTab==0 );
90302       sqlite3WalkSelect(pWalker, pSel);
90303       pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
90304       if( pTab==0 ) return WRC_Abort;
90305       pTab->nRef = 1;
90306       pTab->zName = sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pTab);
90307       while( pSel->pPrior ){ pSel = pSel->pPrior; }
90308       selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
90309       pTab->iPKey = -1;
90310       pTab->tabFlags |= TF_Ephemeral;
90311 #endif
90312     }else{
90313       /* An ordinary table or view name in the FROM clause */
90314       assert( pFrom->pTab==0 );
90315       pFrom->pTab = pTab = 
90316         sqlite3LocateTable(pParse,0,pFrom->zName,pFrom->zDatabase);
90317       if( pTab==0 ) return WRC_Abort;
90318       pTab->nRef++;
90319 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
90320       if( pTab->pSelect || IsVirtual(pTab) ){
90321         /* We reach here if the named table is a really a view */
90322         if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
90323         assert( pFrom->pSelect==0 );
90324         pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
90325         sqlite3WalkSelect(pWalker, pFrom->pSelect);
90326       }
90327 #endif
90328     }
90329
90330     /* Locate the index named by the INDEXED BY clause, if any. */
90331     if( sqlite3IndexedByLookup(pParse, pFrom) ){
90332       return WRC_Abort;
90333     }
90334   }
90335
90336   /* Process NATURAL keywords, and ON and USING clauses of joins.
90337   */
90338   if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
90339     return WRC_Abort;
90340   }
90341
90342   /* For every "*" that occurs in the column list, insert the names of
90343   ** all columns in all tables.  And for every TABLE.* insert the names
90344   ** of all columns in TABLE.  The parser inserted a special expression
90345   ** with the TK_ALL operator for each "*" that it found in the column list.
90346   ** The following code just has to locate the TK_ALL expressions and expand
90347   ** each one to the list of all columns in all tables.
90348   **
90349   ** The first loop just checks to see if there are any "*" operators
90350   ** that need expanding.
90351   */
90352   for(k=0; k<pEList->nExpr; k++){
90353     Expr *pE = pEList->a[k].pExpr;
90354     if( pE->op==TK_ALL ) break;
90355     assert( pE->op!=TK_DOT || pE->pRight!=0 );
90356     assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
90357     if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
90358   }
90359   if( k<pEList->nExpr ){
90360     /*
90361     ** If we get here it means the result set contains one or more "*"
90362     ** operators that need to be expanded.  Loop through each expression
90363     ** in the result set and expand them one by one.
90364     */
90365     struct ExprList_item *a = pEList->a;
90366     ExprList *pNew = 0;
90367     int flags = pParse->db->flags;
90368     int longNames = (flags & SQLITE_FullColNames)!=0
90369                       && (flags & SQLITE_ShortColNames)==0;
90370
90371     for(k=0; k<pEList->nExpr; k++){
90372       Expr *pE = a[k].pExpr;
90373       assert( pE->op!=TK_DOT || pE->pRight!=0 );
90374       if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pE->pRight->op!=TK_ALL) ){
90375         /* This particular expression does not need to be expanded.
90376         */
90377         pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
90378         if( pNew ){
90379           pNew->a[pNew->nExpr-1].zName = a[k].zName;
90380           pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
90381           a[k].zName = 0;
90382           a[k].zSpan = 0;
90383         }
90384         a[k].pExpr = 0;
90385       }else{
90386         /* This expression is a "*" or a "TABLE.*" and needs to be
90387         ** expanded. */
90388         int tableSeen = 0;      /* Set to 1 when TABLE matches */
90389         char *zTName;            /* text of name of TABLE */
90390         if( pE->op==TK_DOT ){
90391           assert( pE->pLeft!=0 );
90392           assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
90393           zTName = pE->pLeft->u.zToken;
90394         }else{
90395           zTName = 0;
90396         }
90397         for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
90398           Table *pTab = pFrom->pTab;
90399           char *zTabName = pFrom->zAlias;
90400           if( zTabName==0 ){
90401             zTabName = pTab->zName;
90402           }
90403           if( db->mallocFailed ) break;
90404           if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
90405             continue;
90406           }
90407           tableSeen = 1;
90408           for(j=0; j<pTab->nCol; j++){
90409             Expr *pExpr, *pRight;
90410             char *zName = pTab->aCol[j].zName;
90411             char *zColname;  /* The computed column name */
90412             char *zToFree;   /* Malloced string that needs to be freed */
90413             Token sColname;  /* Computed column name as a token */
90414
90415             /* If a column is marked as 'hidden' (currently only possible
90416             ** for virtual tables), do not include it in the expanded
90417             ** result-set list.
90418             */
90419             if( IsHiddenColumn(&pTab->aCol[j]) ){
90420               assert(IsVirtual(pTab));
90421               continue;
90422             }
90423
90424             if( i>0 && zTName==0 ){
90425               if( (pFrom->jointype & JT_NATURAL)!=0
90426                 && tableAndColumnIndex(pTabList, i, zName, 0, 0)
90427               ){
90428                 /* In a NATURAL join, omit the join columns from the 
90429                 ** table to the right of the join */
90430                 continue;
90431               }
90432               if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
90433                 /* In a join with a USING clause, omit columns in the
90434                 ** using clause from the table on the right. */
90435                 continue;
90436               }
90437             }
90438             pRight = sqlite3Expr(db, TK_ID, zName);
90439             zColname = zName;
90440             zToFree = 0;
90441             if( longNames || pTabList->nSrc>1 ){
90442               Expr *pLeft;
90443               pLeft = sqlite3Expr(db, TK_ID, zTabName);
90444               pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
90445               if( longNames ){
90446                 zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
90447                 zToFree = zColname;
90448               }
90449             }else{
90450               pExpr = pRight;
90451             }
90452             pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
90453             sColname.z = zColname;
90454             sColname.n = sqlite3Strlen30(zColname);
90455             sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
90456             sqlite3DbFree(db, zToFree);
90457           }
90458         }
90459         if( !tableSeen ){
90460           if( zTName ){
90461             sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
90462           }else{
90463             sqlite3ErrorMsg(pParse, "no tables specified");
90464           }
90465         }
90466       }
90467     }
90468     sqlite3ExprListDelete(db, pEList);
90469     p->pEList = pNew;
90470   }
90471 #if SQLITE_MAX_COLUMN
90472   if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
90473     sqlite3ErrorMsg(pParse, "too many columns in result set");
90474   }
90475 #endif
90476   return WRC_Continue;
90477 }
90478
90479 /*
90480 ** No-op routine for the parse-tree walker.
90481 **
90482 ** When this routine is the Walker.xExprCallback then expression trees
90483 ** are walked without any actions being taken at each node.  Presumably,
90484 ** when this routine is used for Walker.xExprCallback then 
90485 ** Walker.xSelectCallback is set to do something useful for every 
90486 ** subquery in the parser tree.
90487 */
90488 static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
90489   UNUSED_PARAMETER2(NotUsed, NotUsed2);
90490   return WRC_Continue;
90491 }
90492
90493 /*
90494 ** This routine "expands" a SELECT statement and all of its subqueries.
90495 ** For additional information on what it means to "expand" a SELECT
90496 ** statement, see the comment on the selectExpand worker callback above.
90497 **
90498 ** Expanding a SELECT statement is the first step in processing a
90499 ** SELECT statement.  The SELECT statement must be expanded before
90500 ** name resolution is performed.
90501 **
90502 ** If anything goes wrong, an error message is written into pParse.
90503 ** The calling function can detect the problem by looking at pParse->nErr
90504 ** and/or pParse->db->mallocFailed.
90505 */
90506 static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
90507   Walker w;
90508   w.xSelectCallback = selectExpander;
90509   w.xExprCallback = exprWalkNoop;
90510   w.pParse = pParse;
90511   sqlite3WalkSelect(&w, pSelect);
90512 }
90513
90514
90515 #ifndef SQLITE_OMIT_SUBQUERY
90516 /*
90517 ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
90518 ** interface.
90519 **
90520 ** For each FROM-clause subquery, add Column.zType and Column.zColl
90521 ** information to the Table structure that represents the result set
90522 ** of that subquery.
90523 **
90524 ** The Table structure that represents the result set was constructed
90525 ** by selectExpander() but the type and collation information was omitted
90526 ** at that point because identifiers had not yet been resolved.  This
90527 ** routine is called after identifier resolution.
90528 */
90529 static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
90530   Parse *pParse;
90531   int i;
90532   SrcList *pTabList;
90533   struct SrcList_item *pFrom;
90534
90535   assert( p->selFlags & SF_Resolved );
90536   if( (p->selFlags & SF_HasTypeInfo)==0 ){
90537     p->selFlags |= SF_HasTypeInfo;
90538     pParse = pWalker->pParse;
90539     pTabList = p->pSrc;
90540     for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
90541       Table *pTab = pFrom->pTab;
90542       if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
90543         /* A sub-query in the FROM clause of a SELECT */
90544         Select *pSel = pFrom->pSelect;
90545         assert( pSel );
90546         while( pSel->pPrior ) pSel = pSel->pPrior;
90547         selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSel);
90548       }
90549     }
90550   }
90551   return WRC_Continue;
90552 }
90553 #endif
90554
90555
90556 /*
90557 ** This routine adds datatype and collating sequence information to
90558 ** the Table structures of all FROM-clause subqueries in a
90559 ** SELECT statement.
90560 **
90561 ** Use this routine after name resolution.
90562 */
90563 static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
90564 #ifndef SQLITE_OMIT_SUBQUERY
90565   Walker w;
90566   w.xSelectCallback = selectAddSubqueryTypeInfo;
90567   w.xExprCallback = exprWalkNoop;
90568   w.pParse = pParse;
90569   sqlite3WalkSelect(&w, pSelect);
90570 #endif
90571 }
90572
90573
90574 /*
90575 ** This routine sets of a SELECT statement for processing.  The
90576 ** following is accomplished:
90577 **
90578 **     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
90579 **     *  Ephemeral Table objects are created for all FROM-clause subqueries.
90580 **     *  ON and USING clauses are shifted into WHERE statements
90581 **     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
90582 **     *  Identifiers in expression are matched to tables.
90583 **
90584 ** This routine acts recursively on all subqueries within the SELECT.
90585 */
90586 SQLITE_PRIVATE void sqlite3SelectPrep(
90587   Parse *pParse,         /* The parser context */
90588   Select *p,             /* The SELECT statement being coded. */
90589   NameContext *pOuterNC  /* Name context for container */
90590 ){
90591   sqlite3 *db;
90592   if( NEVER(p==0) ) return;
90593   db = pParse->db;
90594   if( p->selFlags & SF_HasTypeInfo ) return;
90595   sqlite3SelectExpand(pParse, p);
90596   if( pParse->nErr || db->mallocFailed ) return;
90597   sqlite3ResolveSelectNames(pParse, p, pOuterNC);
90598   if( pParse->nErr || db->mallocFailed ) return;
90599   sqlite3SelectAddTypeInfo(pParse, p);
90600 }
90601
90602 /*
90603 ** Reset the aggregate accumulator.
90604 **
90605 ** The aggregate accumulator is a set of memory cells that hold
90606 ** intermediate results while calculating an aggregate.  This
90607 ** routine simply stores NULLs in all of those memory cells.
90608 */
90609 static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
90610   Vdbe *v = pParse->pVdbe;
90611   int i;
90612   struct AggInfo_func *pFunc;
90613   if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
90614     return;
90615   }
90616   for(i=0; i<pAggInfo->nColumn; i++){
90617     sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
90618   }
90619   for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
90620     sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
90621     if( pFunc->iDistinct>=0 ){
90622       Expr *pE = pFunc->pExpr;
90623       assert( !ExprHasProperty(pE, EP_xIsSelect) );
90624       if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
90625         sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
90626            "argument");
90627         pFunc->iDistinct = -1;
90628       }else{
90629         KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList);
90630         sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
90631                           (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
90632       }
90633     }
90634   }
90635 }
90636
90637 /*
90638 ** Invoke the OP_AggFinalize opcode for every aggregate function
90639 ** in the AggInfo structure.
90640 */
90641 static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
90642   Vdbe *v = pParse->pVdbe;
90643   int i;
90644   struct AggInfo_func *pF;
90645   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
90646     ExprList *pList = pF->pExpr->x.pList;
90647     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
90648     sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
90649                       (void*)pF->pFunc, P4_FUNCDEF);
90650   }
90651 }
90652
90653 /*
90654 ** Update the accumulator memory cells for an aggregate based on
90655 ** the current cursor position.
90656 */
90657 static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
90658   Vdbe *v = pParse->pVdbe;
90659   int i;
90660   struct AggInfo_func *pF;
90661   struct AggInfo_col *pC;
90662
90663   pAggInfo->directMode = 1;
90664   sqlite3ExprCacheClear(pParse);
90665   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
90666     int nArg;
90667     int addrNext = 0;
90668     int regAgg;
90669     ExprList *pList = pF->pExpr->x.pList;
90670     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
90671     if( pList ){
90672       nArg = pList->nExpr;
90673       regAgg = sqlite3GetTempRange(pParse, nArg);
90674       sqlite3ExprCodeExprList(pParse, pList, regAgg, 1);
90675     }else{
90676       nArg = 0;
90677       regAgg = 0;
90678     }
90679     if( pF->iDistinct>=0 ){
90680       addrNext = sqlite3VdbeMakeLabel(v);
90681       assert( nArg==1 );
90682       codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
90683     }
90684     if( pF->pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
90685       CollSeq *pColl = 0;
90686       struct ExprList_item *pItem;
90687       int j;
90688       assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
90689       for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
90690         pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
90691       }
90692       if( !pColl ){
90693         pColl = pParse->db->pDfltColl;
90694       }
90695       sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
90696     }
90697     sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
90698                       (void*)pF->pFunc, P4_FUNCDEF);
90699     sqlite3VdbeChangeP5(v, (u8)nArg);
90700     sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
90701     sqlite3ReleaseTempRange(pParse, regAgg, nArg);
90702     if( addrNext ){
90703       sqlite3VdbeResolveLabel(v, addrNext);
90704       sqlite3ExprCacheClear(pParse);
90705     }
90706   }
90707
90708   /* Before populating the accumulator registers, clear the column cache.
90709   ** Otherwise, if any of the required column values are already present 
90710   ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
90711   ** to pC->iMem. But by the time the value is used, the original register
90712   ** may have been used, invalidating the underlying buffer holding the
90713   ** text or blob value. See ticket [883034dcb5].
90714   **
90715   ** Another solution would be to change the OP_SCopy used to copy cached
90716   ** values to an OP_Copy.
90717   */
90718   sqlite3ExprCacheClear(pParse);
90719   for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
90720     sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
90721   }
90722   pAggInfo->directMode = 0;
90723   sqlite3ExprCacheClear(pParse);
90724 }
90725
90726 /*
90727 ** Generate code for the SELECT statement given in the p argument.  
90728 **
90729 ** The results are distributed in various ways depending on the
90730 ** contents of the SelectDest structure pointed to by argument pDest
90731 ** as follows:
90732 **
90733 **     pDest->eDest    Result
90734 **     ------------    -------------------------------------------
90735 **     SRT_Output      Generate a row of output (using the OP_ResultRow
90736 **                     opcode) for each row in the result set.
90737 **
90738 **     SRT_Mem         Only valid if the result is a single column.
90739 **                     Store the first column of the first result row
90740 **                     in register pDest->iParm then abandon the rest
90741 **                     of the query.  This destination implies "LIMIT 1".
90742 **
90743 **     SRT_Set         The result must be a single column.  Store each
90744 **                     row of result as the key in table pDest->iParm. 
90745 **                     Apply the affinity pDest->affinity before storing
90746 **                     results.  Used to implement "IN (SELECT ...)".
90747 **
90748 **     SRT_Union       Store results as a key in a temporary table pDest->iParm.
90749 **
90750 **     SRT_Except      Remove results from the temporary table pDest->iParm.
90751 **
90752 **     SRT_Table       Store results in temporary table pDest->iParm.
90753 **                     This is like SRT_EphemTab except that the table
90754 **                     is assumed to already be open.
90755 **
90756 **     SRT_EphemTab    Create an temporary table pDest->iParm and store
90757 **                     the result there. The cursor is left open after
90758 **                     returning.  This is like SRT_Table except that
90759 **                     this destination uses OP_OpenEphemeral to create
90760 **                     the table first.
90761 **
90762 **     SRT_Coroutine   Generate a co-routine that returns a new row of
90763 **                     results each time it is invoked.  The entry point
90764 **                     of the co-routine is stored in register pDest->iParm.
90765 **
90766 **     SRT_Exists      Store a 1 in memory cell pDest->iParm if the result
90767 **                     set is not empty.
90768 **
90769 **     SRT_Discard     Throw the results away.  This is used by SELECT
90770 **                     statements within triggers whose only purpose is
90771 **                     the side-effects of functions.
90772 **
90773 ** This routine returns the number of errors.  If any errors are
90774 ** encountered, then an appropriate error message is left in
90775 ** pParse->zErrMsg.
90776 **
90777 ** This routine does NOT free the Select structure passed in.  The
90778 ** calling function needs to do that.
90779 */
90780 SQLITE_PRIVATE int sqlite3Select(
90781   Parse *pParse,         /* The parser context */
90782   Select *p,             /* The SELECT statement being coded. */
90783   SelectDest *pDest      /* What to do with the query results */
90784 ){
90785   int i, j;              /* Loop counters */
90786   WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
90787   Vdbe *v;               /* The virtual machine under construction */
90788   int isAgg;             /* True for select lists like "count(*)" */
90789   ExprList *pEList;      /* List of columns to extract. */
90790   SrcList *pTabList;     /* List of tables to select from */
90791   Expr *pWhere;          /* The WHERE clause.  May be NULL */
90792   ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
90793   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
90794   Expr *pHaving;         /* The HAVING clause.  May be NULL */
90795   int isDistinct;        /* True if the DISTINCT keyword is present */
90796   int distinct;          /* Table to use for the distinct set */
90797   int rc = 1;            /* Value to return from this function */
90798   int addrSortIndex;     /* Address of an OP_OpenEphemeral instruction */
90799   AggInfo sAggInfo;      /* Information used by aggregate queries */
90800   int iEnd;              /* Address of the end of the query */
90801   sqlite3 *db;           /* The database connection */
90802
90803   db = pParse->db;
90804   if( p==0 || db->mallocFailed || pParse->nErr ){
90805     return 1;
90806   }
90807   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
90808   memset(&sAggInfo, 0, sizeof(sAggInfo));
90809
90810   if( IgnorableOrderby(pDest) ){
90811     assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union || 
90812            pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
90813     /* If ORDER BY makes no difference in the output then neither does
90814     ** DISTINCT so it can be removed too. */
90815     sqlite3ExprListDelete(db, p->pOrderBy);
90816     p->pOrderBy = 0;
90817     p->selFlags &= ~SF_Distinct;
90818   }
90819   sqlite3SelectPrep(pParse, p, 0);
90820   pOrderBy = p->pOrderBy;
90821   pTabList = p->pSrc;
90822   pEList = p->pEList;
90823   if( pParse->nErr || db->mallocFailed ){
90824     goto select_end;
90825   }
90826   isAgg = (p->selFlags & SF_Aggregate)!=0;
90827   assert( pEList!=0 );
90828
90829   /* Begin generating code.
90830   */
90831   v = sqlite3GetVdbe(pParse);
90832   if( v==0 ) goto select_end;
90833
90834   /* If writing to memory or generating a set
90835   ** only a single column may be output.
90836   */
90837 #ifndef SQLITE_OMIT_SUBQUERY
90838   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
90839     goto select_end;
90840   }
90841 #endif
90842
90843   /* Generate code for all sub-queries in the FROM clause
90844   */
90845 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
90846   for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
90847     struct SrcList_item *pItem = &pTabList->a[i];
90848     SelectDest dest;
90849     Select *pSub = pItem->pSelect;
90850     int isAggSub;
90851
90852     if( pSub==0 || pItem->isPopulated ) continue;
90853
90854     /* Increment Parse.nHeight by the height of the largest expression
90855     ** tree refered to by this, the parent select. The child select
90856     ** may contain expression trees of at most
90857     ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
90858     ** more conservative than necessary, but much easier than enforcing
90859     ** an exact limit.
90860     */
90861     pParse->nHeight += sqlite3SelectExprHeight(p);
90862
90863     /* Check to see if the subquery can be absorbed into the parent. */
90864     isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
90865     if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
90866       if( isAggSub ){
90867         isAgg = 1;
90868         p->selFlags |= SF_Aggregate;
90869       }
90870       i = -1;
90871     }else{
90872       sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
90873       assert( pItem->isPopulated==0 );
90874       sqlite3Select(pParse, pSub, &dest);
90875       pItem->isPopulated = 1;
90876     }
90877     if( /*pParse->nErr ||*/ db->mallocFailed ){
90878       goto select_end;
90879     }
90880     pParse->nHeight -= sqlite3SelectExprHeight(p);
90881     pTabList = p->pSrc;
90882     if( !IgnorableOrderby(pDest) ){
90883       pOrderBy = p->pOrderBy;
90884     }
90885   }
90886   pEList = p->pEList;
90887 #endif
90888   pWhere = p->pWhere;
90889   pGroupBy = p->pGroupBy;
90890   pHaving = p->pHaving;
90891   isDistinct = (p->selFlags & SF_Distinct)!=0;
90892
90893 #ifndef SQLITE_OMIT_COMPOUND_SELECT
90894   /* If there is are a sequence of queries, do the earlier ones first.
90895   */
90896   if( p->pPrior ){
90897     if( p->pRightmost==0 ){
90898       Select *pLoop, *pRight = 0;
90899       int cnt = 0;
90900       int mxSelect;
90901       for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
90902         pLoop->pRightmost = p;
90903         pLoop->pNext = pRight;
90904         pRight = pLoop;
90905       }
90906       mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
90907       if( mxSelect && cnt>mxSelect ){
90908         sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
90909         return 1;
90910       }
90911     }
90912     return multiSelect(pParse, p, pDest);
90913   }
90914 #endif
90915
90916   /* If possible, rewrite the query to use GROUP BY instead of DISTINCT.
90917   ** GROUP BY might use an index, DISTINCT never does.
90918   */
90919   assert( p->pGroupBy==0 || (p->selFlags & SF_Aggregate)!=0 );
90920   if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct ){
90921     p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
90922     pGroupBy = p->pGroupBy;
90923     p->selFlags &= ~SF_Distinct;
90924     isDistinct = 0;
90925   }
90926
90927   /* If there is both a GROUP BY and an ORDER BY clause and they are
90928   ** identical, then disable the ORDER BY clause since the GROUP BY
90929   ** will cause elements to come out in the correct order.  This is
90930   ** an optimization - the correct answer should result regardless.
90931   ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER
90932   ** to disable this optimization for testing purposes.
90933   */
90934   if( sqlite3ExprListCompare(p->pGroupBy, pOrderBy)==0
90935          && (db->flags & SQLITE_GroupByOrder)==0 ){
90936     pOrderBy = 0;
90937   }
90938
90939   /* If there is an ORDER BY clause, then this sorting
90940   ** index might end up being unused if the data can be 
90941   ** extracted in pre-sorted order.  If that is the case, then the
90942   ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
90943   ** we figure out that the sorting index is not needed.  The addrSortIndex
90944   ** variable is used to facilitate that change.
90945   */
90946   if( pOrderBy ){
90947     KeyInfo *pKeyInfo;
90948     pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
90949     pOrderBy->iECursor = pParse->nTab++;
90950     p->addrOpenEphm[2] = addrSortIndex =
90951       sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
90952                            pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
90953                            (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
90954   }else{
90955     addrSortIndex = -1;
90956   }
90957
90958   /* If the output is destined for a temporary table, open that table.
90959   */
90960   if( pDest->eDest==SRT_EphemTab ){
90961     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iParm, pEList->nExpr);
90962   }
90963
90964   /* Set the limiter.
90965   */
90966   iEnd = sqlite3VdbeMakeLabel(v);
90967   computeLimitRegisters(pParse, p, iEnd);
90968
90969   /* Open a virtual index to use for the distinct set.
90970   */
90971   if( isDistinct ){
90972     KeyInfo *pKeyInfo;
90973     assert( isAgg || pGroupBy );
90974     distinct = pParse->nTab++;
90975     pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
90976     sqlite3VdbeAddOp4(v, OP_OpenEphemeral, distinct, 0, 0,
90977                         (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
90978     sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
90979   }else{
90980     distinct = -1;
90981   }
90982
90983   /* Aggregate and non-aggregate queries are handled differently */
90984   if( !isAgg && pGroupBy==0 ){
90985     /* This case is for non-aggregate queries
90986     ** Begin the database scan
90987     */
90988     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy, 0);
90989     if( pWInfo==0 ) goto select_end;
90990
90991     /* If sorting index that was created by a prior OP_OpenEphemeral 
90992     ** instruction ended up not being needed, then change the OP_OpenEphemeral
90993     ** into an OP_Noop.
90994     */
90995     if( addrSortIndex>=0 && pOrderBy==0 ){
90996       sqlite3VdbeChangeToNoop(v, addrSortIndex, 1);
90997       p->addrOpenEphm[2] = -1;
90998     }
90999
91000     /* Use the standard inner loop
91001     */
91002     assert(!isDistinct);
91003     selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, -1, pDest,
91004                     pWInfo->iContinue, pWInfo->iBreak);
91005
91006     /* End the database scan loop.
91007     */
91008     sqlite3WhereEnd(pWInfo);
91009   }else{
91010     /* This is the processing for aggregate queries */
91011     NameContext sNC;    /* Name context for processing aggregate information */
91012     int iAMem;          /* First Mem address for storing current GROUP BY */
91013     int iBMem;          /* First Mem address for previous GROUP BY */
91014     int iUseFlag;       /* Mem address holding flag indicating that at least
91015                         ** one row of the input to the aggregator has been
91016                         ** processed */
91017     int iAbortFlag;     /* Mem address which causes query abort if positive */
91018     int groupBySort;    /* Rows come from source in GROUP BY order */
91019     int addrEnd;        /* End of processing for this SELECT */
91020
91021     /* Remove any and all aliases between the result set and the
91022     ** GROUP BY clause.
91023     */
91024     if( pGroupBy ){
91025       int k;                        /* Loop counter */
91026       struct ExprList_item *pItem;  /* For looping over expression in a list */
91027
91028       for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
91029         pItem->iAlias = 0;
91030       }
91031       for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
91032         pItem->iAlias = 0;
91033       }
91034     }
91035
91036  
91037     /* Create a label to jump to when we want to abort the query */
91038     addrEnd = sqlite3VdbeMakeLabel(v);
91039
91040     /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
91041     ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
91042     ** SELECT statement.
91043     */
91044     memset(&sNC, 0, sizeof(sNC));
91045     sNC.pParse = pParse;
91046     sNC.pSrcList = pTabList;
91047     sNC.pAggInfo = &sAggInfo;
91048     sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
91049     sAggInfo.pGroupBy = pGroupBy;
91050     sqlite3ExprAnalyzeAggList(&sNC, pEList);
91051     sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
91052     if( pHaving ){
91053       sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
91054     }
91055     sAggInfo.nAccumulator = sAggInfo.nColumn;
91056     for(i=0; i<sAggInfo.nFunc; i++){
91057       assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
91058       sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
91059     }
91060     if( db->mallocFailed ) goto select_end;
91061
91062     /* Processing for aggregates with GROUP BY is very different and
91063     ** much more complex than aggregates without a GROUP BY.
91064     */
91065     if( pGroupBy ){
91066       KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
91067       int j1;             /* A-vs-B comparision jump */
91068       int addrOutputRow;  /* Start of subroutine that outputs a result row */
91069       int regOutputRow;   /* Return address register for output subroutine */
91070       int addrSetAbort;   /* Set the abort flag and return */
91071       int addrTopOfLoop;  /* Top of the input loop */
91072       int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
91073       int addrReset;      /* Subroutine for resetting the accumulator */
91074       int regReset;       /* Return address register for reset subroutine */
91075
91076       /* If there is a GROUP BY clause we might need a sorting index to
91077       ** implement it.  Allocate that sorting index now.  If it turns out
91078       ** that we do not need it after all, the OpenEphemeral instruction
91079       ** will be converted into a Noop.  
91080       */
91081       sAggInfo.sortingIdx = pParse->nTab++;
91082       pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
91083       addrSortingIdx = sqlite3VdbeAddOp4(v, OP_OpenEphemeral, 
91084           sAggInfo.sortingIdx, sAggInfo.nSortingColumn, 
91085           0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
91086
91087       /* Initialize memory locations used by GROUP BY aggregate processing
91088       */
91089       iUseFlag = ++pParse->nMem;
91090       iAbortFlag = ++pParse->nMem;
91091       regOutputRow = ++pParse->nMem;
91092       addrOutputRow = sqlite3VdbeMakeLabel(v);
91093       regReset = ++pParse->nMem;
91094       addrReset = sqlite3VdbeMakeLabel(v);
91095       iAMem = pParse->nMem + 1;
91096       pParse->nMem += pGroupBy->nExpr;
91097       iBMem = pParse->nMem + 1;
91098       pParse->nMem += pGroupBy->nExpr;
91099       sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
91100       VdbeComment((v, "clear abort flag"));
91101       sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
91102       VdbeComment((v, "indicate accumulator empty"));
91103
91104       /* Begin a loop that will extract all source rows in GROUP BY order.
91105       ** This might involve two separate loops with an OP_Sort in between, or
91106       ** it might be a single loop that uses an index to extract information
91107       ** in the right order to begin with.
91108       */
91109       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
91110       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy, 0);
91111       if( pWInfo==0 ) goto select_end;
91112       if( pGroupBy==0 ){
91113         /* The optimizer is able to deliver rows in group by order so
91114         ** we do not have to sort.  The OP_OpenEphemeral table will be
91115         ** cancelled later because we still need to use the pKeyInfo
91116         */
91117         pGroupBy = p->pGroupBy;
91118         groupBySort = 0;
91119       }else{
91120         /* Rows are coming out in undetermined order.  We have to push
91121         ** each row into a sorting index, terminate the first loop,
91122         ** then loop over the sorting index in order to get the output
91123         ** in sorted order
91124         */
91125         int regBase;
91126         int regRecord;
91127         int nCol;
91128         int nGroupBy;
91129
91130         groupBySort = 1;
91131         nGroupBy = pGroupBy->nExpr;
91132         nCol = nGroupBy + 1;
91133         j = nGroupBy+1;
91134         for(i=0; i<sAggInfo.nColumn; i++){
91135           if( sAggInfo.aCol[i].iSorterColumn>=j ){
91136             nCol++;
91137             j++;
91138           }
91139         }
91140         regBase = sqlite3GetTempRange(pParse, nCol);
91141         sqlite3ExprCacheClear(pParse);
91142         sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
91143         sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
91144         j = nGroupBy+1;
91145         for(i=0; i<sAggInfo.nColumn; i++){
91146           struct AggInfo_col *pCol = &sAggInfo.aCol[i];
91147           if( pCol->iSorterColumn>=j ){
91148             int r1 = j + regBase;
91149             int r2;
91150
91151             r2 = sqlite3ExprCodeGetColumn(pParse, 
91152                                pCol->pTab, pCol->iColumn, pCol->iTable, r1);
91153             if( r1!=r2 ){
91154               sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
91155             }
91156             j++;
91157           }
91158         }
91159         regRecord = sqlite3GetTempReg(pParse);
91160         sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
91161         sqlite3VdbeAddOp2(v, OP_IdxInsert, sAggInfo.sortingIdx, regRecord);
91162         sqlite3ReleaseTempReg(pParse, regRecord);
91163         sqlite3ReleaseTempRange(pParse, regBase, nCol);
91164         sqlite3WhereEnd(pWInfo);
91165         sqlite3VdbeAddOp2(v, OP_Sort, sAggInfo.sortingIdx, addrEnd);
91166         VdbeComment((v, "GROUP BY sort"));
91167         sAggInfo.useSortingIdx = 1;
91168         sqlite3ExprCacheClear(pParse);
91169       }
91170
91171       /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
91172       ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
91173       ** Then compare the current GROUP BY terms against the GROUP BY terms
91174       ** from the previous row currently stored in a0, a1, a2...
91175       */
91176       addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
91177       sqlite3ExprCacheClear(pParse);
91178       for(j=0; j<pGroupBy->nExpr; j++){
91179         if( groupBySort ){
91180           sqlite3VdbeAddOp3(v, OP_Column, sAggInfo.sortingIdx, j, iBMem+j);
91181         }else{
91182           sAggInfo.directMode = 1;
91183           sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
91184         }
91185       }
91186       sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
91187                           (char*)pKeyInfo, P4_KEYINFO);
91188       j1 = sqlite3VdbeCurrentAddr(v);
91189       sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
91190
91191       /* Generate code that runs whenever the GROUP BY changes.
91192       ** Changes in the GROUP BY are detected by the previous code
91193       ** block.  If there were no changes, this block is skipped.
91194       **
91195       ** This code copies current group by terms in b0,b1,b2,...
91196       ** over to a0,a1,a2.  It then calls the output subroutine
91197       ** and resets the aggregate accumulator registers in preparation
91198       ** for the next GROUP BY batch.
91199       */
91200       sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
91201       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
91202       VdbeComment((v, "output one row"));
91203       sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
91204       VdbeComment((v, "check abort flag"));
91205       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
91206       VdbeComment((v, "reset accumulator"));
91207
91208       /* Update the aggregate accumulators based on the content of
91209       ** the current row
91210       */
91211       sqlite3VdbeJumpHere(v, j1);
91212       updateAccumulator(pParse, &sAggInfo);
91213       sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
91214       VdbeComment((v, "indicate data in accumulator"));
91215
91216       /* End of the loop
91217       */
91218       if( groupBySort ){
91219         sqlite3VdbeAddOp2(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop);
91220       }else{
91221         sqlite3WhereEnd(pWInfo);
91222         sqlite3VdbeChangeToNoop(v, addrSortingIdx, 1);
91223       }
91224
91225       /* Output the final row of result
91226       */
91227       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
91228       VdbeComment((v, "output final row"));
91229
91230       /* Jump over the subroutines
91231       */
91232       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
91233
91234       /* Generate a subroutine that outputs a single row of the result
91235       ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
91236       ** is less than or equal to zero, the subroutine is a no-op.  If
91237       ** the processing calls for the query to abort, this subroutine
91238       ** increments the iAbortFlag memory location before returning in
91239       ** order to signal the caller to abort.
91240       */
91241       addrSetAbort = sqlite3VdbeCurrentAddr(v);
91242       sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
91243       VdbeComment((v, "set abort flag"));
91244       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
91245       sqlite3VdbeResolveLabel(v, addrOutputRow);
91246       addrOutputRow = sqlite3VdbeCurrentAddr(v);
91247       sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
91248       VdbeComment((v, "Groupby result generator entry point"));
91249       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
91250       finalizeAggFunctions(pParse, &sAggInfo);
91251       sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
91252       selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
91253                       distinct, pDest,
91254                       addrOutputRow+1, addrSetAbort);
91255       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
91256       VdbeComment((v, "end groupby result generator"));
91257
91258       /* Generate a subroutine that will reset the group-by accumulator
91259       */
91260       sqlite3VdbeResolveLabel(v, addrReset);
91261       resetAccumulator(pParse, &sAggInfo);
91262       sqlite3VdbeAddOp1(v, OP_Return, regReset);
91263      
91264     } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
91265     else {
91266       ExprList *pDel = 0;
91267 #ifndef SQLITE_OMIT_BTREECOUNT
91268       Table *pTab;
91269       if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
91270         /* If isSimpleCount() returns a pointer to a Table structure, then
91271         ** the SQL statement is of the form:
91272         **
91273         **   SELECT count(*) FROM <tbl>
91274         **
91275         ** where the Table structure returned represents table <tbl>.
91276         **
91277         ** This statement is so common that it is optimized specially. The
91278         ** OP_Count instruction is executed either on the intkey table that
91279         ** contains the data for table <tbl> or on one of its indexes. It
91280         ** is better to execute the op on an index, as indexes are almost
91281         ** always spread across less pages than their corresponding tables.
91282         */
91283         const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
91284         const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */
91285         Index *pIdx;                         /* Iterator variable */
91286         KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
91287         Index *pBest = 0;                    /* Best index found so far */
91288         int iRoot = pTab->tnum;              /* Root page of scanned b-tree */
91289
91290         sqlite3CodeVerifySchema(pParse, iDb);
91291         sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
91292
91293         /* Search for the index that has the least amount of columns. If
91294         ** there is such an index, and it has less columns than the table
91295         ** does, then we can assume that it consumes less space on disk and
91296         ** will therefore be cheaper to scan to determine the query result.
91297         ** In this case set iRoot to the root page number of the index b-tree
91298         ** and pKeyInfo to the KeyInfo structure required to navigate the
91299         ** index.
91300         **
91301         ** In practice the KeyInfo structure will not be used. It is only 
91302         ** passed to keep OP_OpenRead happy.
91303         */
91304         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
91305           if( !pBest || pIdx->nColumn<pBest->nColumn ){
91306             pBest = pIdx;
91307           }
91308         }
91309         if( pBest && pBest->nColumn<pTab->nCol ){
91310           iRoot = pBest->tnum;
91311           pKeyInfo = sqlite3IndexKeyinfo(pParse, pBest);
91312         }
91313
91314         /* Open a read-only cursor, execute the OP_Count, close the cursor. */
91315         sqlite3VdbeAddOp3(v, OP_OpenRead, iCsr, iRoot, iDb);
91316         if( pKeyInfo ){
91317           sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO_HANDOFF);
91318         }
91319         sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
91320         sqlite3VdbeAddOp1(v, OP_Close, iCsr);
91321       }else
91322 #endif /* SQLITE_OMIT_BTREECOUNT */
91323       {
91324         /* Check if the query is of one of the following forms:
91325         **
91326         **   SELECT min(x) FROM ...
91327         **   SELECT max(x) FROM ...
91328         **
91329         ** If it is, then ask the code in where.c to attempt to sort results
91330         ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause. 
91331         ** If where.c is able to produce results sorted in this order, then
91332         ** add vdbe code to break out of the processing loop after the 
91333         ** first iteration (since the first iteration of the loop is 
91334         ** guaranteed to operate on the row with the minimum or maximum 
91335         ** value of x, the only row required).
91336         **
91337         ** A special flag must be passed to sqlite3WhereBegin() to slightly
91338         ** modify behaviour as follows:
91339         **
91340         **   + If the query is a "SELECT min(x)", then the loop coded by
91341         **     where.c should not iterate over any values with a NULL value
91342         **     for x.
91343         **
91344         **   + The optimizer code in where.c (the thing that decides which
91345         **     index or indices to use) should place a different priority on 
91346         **     satisfying the 'ORDER BY' clause than it does in other cases.
91347         **     Refer to code and comments in where.c for details.
91348         */
91349         ExprList *pMinMax = 0;
91350         u8 flag = minMaxQuery(p);
91351         if( flag ){
91352           assert( !ExprHasProperty(p->pEList->a[0].pExpr, EP_xIsSelect) );
91353           pMinMax = sqlite3ExprListDup(db, p->pEList->a[0].pExpr->x.pList,0);
91354           pDel = pMinMax;
91355           if( pMinMax && !db->mallocFailed ){
91356             pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
91357             pMinMax->a[0].pExpr->op = TK_COLUMN;
91358           }
91359         }
91360   
91361         /* This case runs if the aggregate has no GROUP BY clause.  The
91362         ** processing is much simpler since there is only a single row
91363         ** of output.
91364         */
91365         resetAccumulator(pParse, &sAggInfo);
91366         pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pMinMax, flag);
91367         if( pWInfo==0 ){
91368           sqlite3ExprListDelete(db, pDel);
91369           goto select_end;
91370         }
91371         updateAccumulator(pParse, &sAggInfo);
91372         if( !pMinMax && flag ){
91373           sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak);
91374           VdbeComment((v, "%s() by index",
91375                 (flag==WHERE_ORDERBY_MIN?"min":"max")));
91376         }
91377         sqlite3WhereEnd(pWInfo);
91378         finalizeAggFunctions(pParse, &sAggInfo);
91379       }
91380
91381       pOrderBy = 0;
91382       sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
91383       selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1, 
91384                       pDest, addrEnd, addrEnd);
91385       sqlite3ExprListDelete(db, pDel);
91386     }
91387     sqlite3VdbeResolveLabel(v, addrEnd);
91388     
91389   } /* endif aggregate query */
91390
91391   /* If there is an ORDER BY clause, then we need to sort the results
91392   ** and send them to the callback one by one.
91393   */
91394   if( pOrderBy ){
91395     generateSortTail(pParse, p, v, pEList->nExpr, pDest);
91396   }
91397
91398   /* Jump here to skip this query
91399   */
91400   sqlite3VdbeResolveLabel(v, iEnd);
91401
91402   /* The SELECT was successfully coded.   Set the return code to 0
91403   ** to indicate no errors.
91404   */
91405   rc = 0;
91406
91407   /* Control jumps to here if an error is encountered above, or upon
91408   ** successful coding of the SELECT.
91409   */
91410 select_end:
91411
91412   /* Identify column names if results of the SELECT are to be output.
91413   */
91414   if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
91415     generateColumnNames(pParse, pTabList, pEList);
91416   }
91417
91418   sqlite3DbFree(db, sAggInfo.aCol);
91419   sqlite3DbFree(db, sAggInfo.aFunc);
91420   return rc;
91421 }
91422
91423 #if defined(SQLITE_DEBUG)
91424 /*
91425 *******************************************************************************
91426 ** The following code is used for testing and debugging only.  The code
91427 ** that follows does not appear in normal builds.
91428 **
91429 ** These routines are used to print out the content of all or part of a 
91430 ** parse structures such as Select or Expr.  Such printouts are useful
91431 ** for helping to understand what is happening inside the code generator
91432 ** during the execution of complex SELECT statements.
91433 **
91434 ** These routine are not called anywhere from within the normal
91435 ** code base.  Then are intended to be called from within the debugger
91436 ** or from temporary "printf" statements inserted for debugging.
91437 */
91438 SQLITE_PRIVATE void sqlite3PrintExpr(Expr *p){
91439   if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
91440     sqlite3DebugPrintf("(%s", p->u.zToken);
91441   }else{
91442     sqlite3DebugPrintf("(%d", p->op);
91443   }
91444   if( p->pLeft ){
91445     sqlite3DebugPrintf(" ");
91446     sqlite3PrintExpr(p->pLeft);
91447   }
91448   if( p->pRight ){
91449     sqlite3DebugPrintf(" ");
91450     sqlite3PrintExpr(p->pRight);
91451   }
91452   sqlite3DebugPrintf(")");
91453 }
91454 SQLITE_PRIVATE void sqlite3PrintExprList(ExprList *pList){
91455   int i;
91456   for(i=0; i<pList->nExpr; i++){
91457     sqlite3PrintExpr(pList->a[i].pExpr);
91458     if( i<pList->nExpr-1 ){
91459       sqlite3DebugPrintf(", ");
91460     }
91461   }
91462 }
91463 SQLITE_PRIVATE void sqlite3PrintSelect(Select *p, int indent){
91464   sqlite3DebugPrintf("%*sSELECT(%p) ", indent, "", p);
91465   sqlite3PrintExprList(p->pEList);
91466   sqlite3DebugPrintf("\n");
91467   if( p->pSrc ){
91468     char *zPrefix;
91469     int i;
91470     zPrefix = "FROM";
91471     for(i=0; i<p->pSrc->nSrc; i++){
91472       struct SrcList_item *pItem = &p->pSrc->a[i];
91473       sqlite3DebugPrintf("%*s ", indent+6, zPrefix);
91474       zPrefix = "";
91475       if( pItem->pSelect ){
91476         sqlite3DebugPrintf("(\n");
91477         sqlite3PrintSelect(pItem->pSelect, indent+10);
91478         sqlite3DebugPrintf("%*s)", indent+8, "");
91479       }else if( pItem->zName ){
91480         sqlite3DebugPrintf("%s", pItem->zName);
91481       }
91482       if( pItem->pTab ){
91483         sqlite3DebugPrintf("(table: %s)", pItem->pTab->zName);
91484       }
91485       if( pItem->zAlias ){
91486         sqlite3DebugPrintf(" AS %s", pItem->zAlias);
91487       }
91488       if( i<p->pSrc->nSrc-1 ){
91489         sqlite3DebugPrintf(",");
91490       }
91491       sqlite3DebugPrintf("\n");
91492     }
91493   }
91494   if( p->pWhere ){
91495     sqlite3DebugPrintf("%*s WHERE ", indent, "");
91496     sqlite3PrintExpr(p->pWhere);
91497     sqlite3DebugPrintf("\n");
91498   }
91499   if( p->pGroupBy ){
91500     sqlite3DebugPrintf("%*s GROUP BY ", indent, "");
91501     sqlite3PrintExprList(p->pGroupBy);
91502     sqlite3DebugPrintf("\n");
91503   }
91504   if( p->pHaving ){
91505     sqlite3DebugPrintf("%*s HAVING ", indent, "");
91506     sqlite3PrintExpr(p->pHaving);
91507     sqlite3DebugPrintf("\n");
91508   }
91509   if( p->pOrderBy ){
91510     sqlite3DebugPrintf("%*s ORDER BY ", indent, "");
91511     sqlite3PrintExprList(p->pOrderBy);
91512     sqlite3DebugPrintf("\n");
91513   }
91514 }
91515 /* End of the structure debug printing code
91516 *****************************************************************************/
91517 #endif /* defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
91518
91519 /************** End of select.c **********************************************/
91520 /************** Begin file table.c *******************************************/
91521 /*
91522 ** 2001 September 15
91523 **
91524 ** The author disclaims copyright to this source code.  In place of
91525 ** a legal notice, here is a blessing:
91526 **
91527 **    May you do good and not evil.
91528 **    May you find forgiveness for yourself and forgive others.
91529 **    May you share freely, never taking more than you give.
91530 **
91531 *************************************************************************
91532 ** This file contains the sqlite3_get_table() and sqlite3_free_table()
91533 ** interface routines.  These are just wrappers around the main
91534 ** interface routine of sqlite3_exec().
91535 **
91536 ** These routines are in a separate files so that they will not be linked
91537 ** if they are not used.
91538 */
91539
91540 #ifndef SQLITE_OMIT_GET_TABLE
91541
91542 /*
91543 ** This structure is used to pass data from sqlite3_get_table() through
91544 ** to the callback function is uses to build the result.
91545 */
91546 typedef struct TabResult {
91547   char **azResult;   /* Accumulated output */
91548   char *zErrMsg;     /* Error message text, if an error occurs */
91549   int nAlloc;        /* Slots allocated for azResult[] */
91550   int nRow;          /* Number of rows in the result */
91551   int nColumn;       /* Number of columns in the result */
91552   int nData;         /* Slots used in azResult[].  (nRow+1)*nColumn */
91553   int rc;            /* Return code from sqlite3_exec() */
91554 } TabResult;
91555
91556 /*
91557 ** This routine is called once for each row in the result table.  Its job
91558 ** is to fill in the TabResult structure appropriately, allocating new
91559 ** memory as necessary.
91560 */
91561 static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
91562   TabResult *p = (TabResult*)pArg;  /* Result accumulator */
91563   int need;                         /* Slots needed in p->azResult[] */
91564   int i;                            /* Loop counter */
91565   char *z;                          /* A single column of result */
91566
91567   /* Make sure there is enough space in p->azResult to hold everything
91568   ** we need to remember from this invocation of the callback.
91569   */
91570   if( p->nRow==0 && argv!=0 ){
91571     need = nCol*2;
91572   }else{
91573     need = nCol;
91574   }
91575   if( p->nData + need > p->nAlloc ){
91576     char **azNew;
91577     p->nAlloc = p->nAlloc*2 + need;
91578     azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc );
91579     if( azNew==0 ) goto malloc_failed;
91580     p->azResult = azNew;
91581   }
91582
91583   /* If this is the first row, then generate an extra row containing
91584   ** the names of all columns.
91585   */
91586   if( p->nRow==0 ){
91587     p->nColumn = nCol;
91588     for(i=0; i<nCol; i++){
91589       z = sqlite3_mprintf("%s", colv[i]);
91590       if( z==0 ) goto malloc_failed;
91591       p->azResult[p->nData++] = z;
91592     }
91593   }else if( p->nColumn!=nCol ){
91594     sqlite3_free(p->zErrMsg);
91595     p->zErrMsg = sqlite3_mprintf(
91596        "sqlite3_get_table() called with two or more incompatible queries"
91597     );
91598     p->rc = SQLITE_ERROR;
91599     return 1;
91600   }
91601
91602   /* Copy over the row data
91603   */
91604   if( argv!=0 ){
91605     for(i=0; i<nCol; i++){
91606       if( argv[i]==0 ){
91607         z = 0;
91608       }else{
91609         int n = sqlite3Strlen30(argv[i])+1;
91610         z = sqlite3_malloc( n );
91611         if( z==0 ) goto malloc_failed;
91612         memcpy(z, argv[i], n);
91613       }
91614       p->azResult[p->nData++] = z;
91615     }
91616     p->nRow++;
91617   }
91618   return 0;
91619
91620 malloc_failed:
91621   p->rc = SQLITE_NOMEM;
91622   return 1;
91623 }
91624
91625 /*
91626 ** Query the database.  But instead of invoking a callback for each row,
91627 ** malloc() for space to hold the result and return the entire results
91628 ** at the conclusion of the call.
91629 **
91630 ** The result that is written to ***pazResult is held in memory obtained
91631 ** from malloc().  But the caller cannot free this memory directly.  
91632 ** Instead, the entire table should be passed to sqlite3_free_table() when
91633 ** the calling procedure is finished using it.
91634 */
91635 SQLITE_API int sqlite3_get_table(
91636   sqlite3 *db,                /* The database on which the SQL executes */
91637   const char *zSql,           /* The SQL to be executed */
91638   char ***pazResult,          /* Write the result table here */
91639   int *pnRow,                 /* Write the number of rows in the result here */
91640   int *pnColumn,              /* Write the number of columns of result here */
91641   char **pzErrMsg             /* Write error messages here */
91642 ){
91643   int rc;
91644   TabResult res;
91645
91646   *pazResult = 0;
91647   if( pnColumn ) *pnColumn = 0;
91648   if( pnRow ) *pnRow = 0;
91649   if( pzErrMsg ) *pzErrMsg = 0;
91650   res.zErrMsg = 0;
91651   res.nRow = 0;
91652   res.nColumn = 0;
91653   res.nData = 1;
91654   res.nAlloc = 20;
91655   res.rc = SQLITE_OK;
91656   res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
91657   if( res.azResult==0 ){
91658      db->errCode = SQLITE_NOMEM;
91659      return SQLITE_NOMEM;
91660   }
91661   res.azResult[0] = 0;
91662   rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
91663   assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
91664   res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
91665   if( (rc&0xff)==SQLITE_ABORT ){
91666     sqlite3_free_table(&res.azResult[1]);
91667     if( res.zErrMsg ){
91668       if( pzErrMsg ){
91669         sqlite3_free(*pzErrMsg);
91670         *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
91671       }
91672       sqlite3_free(res.zErrMsg);
91673     }
91674     db->errCode = res.rc;  /* Assume 32-bit assignment is atomic */
91675     return res.rc;
91676   }
91677   sqlite3_free(res.zErrMsg);
91678   if( rc!=SQLITE_OK ){
91679     sqlite3_free_table(&res.azResult[1]);
91680     return rc;
91681   }
91682   if( res.nAlloc>res.nData ){
91683     char **azNew;
91684     azNew = sqlite3_realloc( res.azResult, sizeof(char*)*res.nData );
91685     if( azNew==0 ){
91686       sqlite3_free_table(&res.azResult[1]);
91687       db->errCode = SQLITE_NOMEM;
91688       return SQLITE_NOMEM;
91689     }
91690     res.azResult = azNew;
91691   }
91692   *pazResult = &res.azResult[1];
91693   if( pnColumn ) *pnColumn = res.nColumn;
91694   if( pnRow ) *pnRow = res.nRow;
91695   return rc;
91696 }
91697
91698 /*
91699 ** This routine frees the space the sqlite3_get_table() malloced.
91700 */
91701 SQLITE_API void sqlite3_free_table(
91702   char **azResult            /* Result returned from from sqlite3_get_table() */
91703 ){
91704   if( azResult ){
91705     int i, n;
91706     azResult--;
91707     assert( azResult!=0 );
91708     n = SQLITE_PTR_TO_INT(azResult[0]);
91709     for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
91710     sqlite3_free(azResult);
91711   }
91712 }
91713
91714 #endif /* SQLITE_OMIT_GET_TABLE */
91715
91716 /************** End of table.c ***********************************************/
91717 /************** Begin file trigger.c *****************************************/
91718 /*
91719 **
91720 ** The author disclaims copyright to this source code.  In place of
91721 ** a legal notice, here is a blessing:
91722 **
91723 **    May you do good and not evil.
91724 **    May you find forgiveness for yourself and forgive others.
91725 **    May you share freely, never taking more than you give.
91726 **
91727 *************************************************************************
91728 ** This file contains the implementation for TRIGGERs
91729 */
91730
91731 #ifndef SQLITE_OMIT_TRIGGER
91732 /*
91733 ** Delete a linked list of TriggerStep structures.
91734 */
91735 SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
91736   while( pTriggerStep ){
91737     TriggerStep * pTmp = pTriggerStep;
91738     pTriggerStep = pTriggerStep->pNext;
91739
91740     sqlite3ExprDelete(db, pTmp->pWhere);
91741     sqlite3ExprListDelete(db, pTmp->pExprList);
91742     sqlite3SelectDelete(db, pTmp->pSelect);
91743     sqlite3IdListDelete(db, pTmp->pIdList);
91744
91745     sqlite3DbFree(db, pTmp);
91746   }
91747 }
91748
91749 /*
91750 ** Given table pTab, return a list of all the triggers attached to 
91751 ** the table. The list is connected by Trigger.pNext pointers.
91752 **
91753 ** All of the triggers on pTab that are in the same database as pTab
91754 ** are already attached to pTab->pTrigger.  But there might be additional
91755 ** triggers on pTab in the TEMP schema.  This routine prepends all
91756 ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
91757 ** and returns the combined list.
91758 **
91759 ** To state it another way:  This routine returns a list of all triggers
91760 ** that fire off of pTab.  The list will include any TEMP triggers on
91761 ** pTab as well as the triggers lised in pTab->pTrigger.
91762 */
91763 SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
91764   Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
91765   Trigger *pList = 0;                  /* List of triggers to return */
91766
91767   if( pParse->disableTriggers ){
91768     return 0;
91769   }
91770
91771   if( pTmpSchema!=pTab->pSchema ){
91772     HashElem *p;
91773     for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
91774       Trigger *pTrig = (Trigger *)sqliteHashData(p);
91775       if( pTrig->pTabSchema==pTab->pSchema
91776        && 0==sqlite3StrICmp(pTrig->table, pTab->zName) 
91777       ){
91778         pTrig->pNext = (pList ? pList : pTab->pTrigger);
91779         pList = pTrig;
91780       }
91781     }
91782   }
91783
91784   return (pList ? pList : pTab->pTrigger);
91785 }
91786
91787 /*
91788 ** This is called by the parser when it sees a CREATE TRIGGER statement
91789 ** up to the point of the BEGIN before the trigger actions.  A Trigger
91790 ** structure is generated based on the information available and stored
91791 ** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
91792 ** sqlite3FinishTrigger() function is called to complete the trigger
91793 ** construction process.
91794 */
91795 SQLITE_PRIVATE void sqlite3BeginTrigger(
91796   Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
91797   Token *pName1,      /* The name of the trigger */
91798   Token *pName2,      /* The name of the trigger */
91799   int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
91800   int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
91801   IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
91802   SrcList *pTableName,/* The name of the table/view the trigger applies to */
91803   Expr *pWhen,        /* WHEN clause */
91804   int isTemp,         /* True if the TEMPORARY keyword is present */
91805   int noErr           /* Suppress errors if the trigger already exists */
91806 ){
91807   Trigger *pTrigger = 0;  /* The new trigger */
91808   Table *pTab;            /* Table that the trigger fires off of */
91809   char *zName = 0;        /* Name of the trigger */
91810   sqlite3 *db = pParse->db;  /* The database connection */
91811   int iDb;                /* The database to store the trigger in */
91812   Token *pName;           /* The unqualified db name */
91813   DbFixer sFix;           /* State vector for the DB fixer */
91814   int iTabDb;             /* Index of the database holding pTab */
91815
91816   assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
91817   assert( pName2!=0 );
91818   assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
91819   assert( op>0 && op<0xff );
91820   if( isTemp ){
91821     /* If TEMP was specified, then the trigger name may not be qualified. */
91822     if( pName2->n>0 ){
91823       sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
91824       goto trigger_cleanup;
91825     }
91826     iDb = 1;
91827     pName = pName1;
91828   }else{
91829     /* Figure out the db that the the trigger will be created in */
91830     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
91831     if( iDb<0 ){
91832       goto trigger_cleanup;
91833     }
91834   }
91835
91836   /* If the trigger name was unqualified, and the table is a temp table,
91837   ** then set iDb to 1 to create the trigger in the temporary database.
91838   ** If sqlite3SrcListLookup() returns 0, indicating the table does not
91839   ** exist, the error is caught by the block below.
91840   */
91841   if( !pTableName || db->mallocFailed ){
91842     goto trigger_cleanup;
91843   }
91844   pTab = sqlite3SrcListLookup(pParse, pTableName);
91845   if( db->init.busy==0 && pName2->n==0 && pTab
91846         && pTab->pSchema==db->aDb[1].pSchema ){
91847     iDb = 1;
91848   }
91849
91850   /* Ensure the table name matches database name and that the table exists */
91851   if( db->mallocFailed ) goto trigger_cleanup;
91852   assert( pTableName->nSrc==1 );
91853   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName) && 
91854       sqlite3FixSrcList(&sFix, pTableName) ){
91855     goto trigger_cleanup;
91856   }
91857   pTab = sqlite3SrcListLookup(pParse, pTableName);
91858   if( !pTab ){
91859     /* The table does not exist. */
91860     if( db->init.iDb==1 ){
91861       /* Ticket #3810.
91862       ** Normally, whenever a table is dropped, all associated triggers are
91863       ** dropped too.  But if a TEMP trigger is created on a non-TEMP table
91864       ** and the table is dropped by a different database connection, the
91865       ** trigger is not visible to the database connection that does the
91866       ** drop so the trigger cannot be dropped.  This results in an
91867       ** "orphaned trigger" - a trigger whose associated table is missing.
91868       */
91869       db->init.orphanTrigger = 1;
91870     }
91871     goto trigger_cleanup;
91872   }
91873   if( IsVirtual(pTab) ){
91874     sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
91875     goto trigger_cleanup;
91876   }
91877
91878   /* Check that the trigger name is not reserved and that no trigger of the
91879   ** specified name exists */
91880   zName = sqlite3NameFromToken(db, pName);
91881   if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
91882     goto trigger_cleanup;
91883   }
91884   if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),
91885                       zName, sqlite3Strlen30(zName)) ){
91886     if( !noErr ){
91887       sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
91888     }
91889     goto trigger_cleanup;
91890   }
91891
91892   /* Do not create a trigger on a system table */
91893   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
91894     sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
91895     pParse->nErr++;
91896     goto trigger_cleanup;
91897   }
91898
91899   /* INSTEAD of triggers are only for views and views only support INSTEAD
91900   ** of triggers.
91901   */
91902   if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
91903     sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S", 
91904         (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
91905     goto trigger_cleanup;
91906   }
91907   if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
91908     sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
91909         " trigger on table: %S", pTableName, 0);
91910     goto trigger_cleanup;
91911   }
91912   iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
91913
91914 #ifndef SQLITE_OMIT_AUTHORIZATION
91915   {
91916     int code = SQLITE_CREATE_TRIGGER;
91917     const char *zDb = db->aDb[iTabDb].zName;
91918     const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
91919     if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
91920     if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
91921       goto trigger_cleanup;
91922     }
91923     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
91924       goto trigger_cleanup;
91925     }
91926   }
91927 #endif
91928
91929   /* INSTEAD OF triggers can only appear on views and BEFORE triggers
91930   ** cannot appear on views.  So we might as well translate every
91931   ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
91932   ** elsewhere.
91933   */
91934   if (tr_tm == TK_INSTEAD){
91935     tr_tm = TK_BEFORE;
91936   }
91937
91938   /* Build the Trigger object */
91939   pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
91940   if( pTrigger==0 ) goto trigger_cleanup;
91941   pTrigger->zName = zName;
91942   zName = 0;
91943   pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
91944   pTrigger->pSchema = db->aDb[iDb].pSchema;
91945   pTrigger->pTabSchema = pTab->pSchema;
91946   pTrigger->op = (u8)op;
91947   pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
91948   pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
91949   pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
91950   assert( pParse->pNewTrigger==0 );
91951   pParse->pNewTrigger = pTrigger;
91952
91953 trigger_cleanup:
91954   sqlite3DbFree(db, zName);
91955   sqlite3SrcListDelete(db, pTableName);
91956   sqlite3IdListDelete(db, pColumns);
91957   sqlite3ExprDelete(db, pWhen);
91958   if( !pParse->pNewTrigger ){
91959     sqlite3DeleteTrigger(db, pTrigger);
91960   }else{
91961     assert( pParse->pNewTrigger==pTrigger );
91962   }
91963 }
91964
91965 /*
91966 ** This routine is called after all of the trigger actions have been parsed
91967 ** in order to complete the process of building the trigger.
91968 */
91969 SQLITE_PRIVATE void sqlite3FinishTrigger(
91970   Parse *pParse,          /* Parser context */
91971   TriggerStep *pStepList, /* The triggered program */
91972   Token *pAll             /* Token that describes the complete CREATE TRIGGER */
91973 ){
91974   Trigger *pTrig = pParse->pNewTrigger;   /* Trigger being finished */
91975   char *zName;                            /* Name of trigger */
91976   sqlite3 *db = pParse->db;               /* The database */
91977   DbFixer sFix;                           /* Fixer object */
91978   int iDb;                                /* Database containing the trigger */
91979   Token nameToken;                        /* Trigger name for error reporting */
91980
91981   pTrig = pParse->pNewTrigger;
91982   pParse->pNewTrigger = 0;
91983   if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
91984   zName = pTrig->zName;
91985   iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
91986   pTrig->step_list = pStepList;
91987   while( pStepList ){
91988     pStepList->pTrig = pTrig;
91989     pStepList = pStepList->pNext;
91990   }
91991   nameToken.z = pTrig->zName;
91992   nameToken.n = sqlite3Strlen30(nameToken.z);
91993   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken) 
91994           && sqlite3FixTriggerStep(&sFix, pTrig->step_list) ){
91995     goto triggerfinish_cleanup;
91996   }
91997
91998   /* if we are not initializing,
91999   ** build the sqlite_master entry
92000   */
92001   if( !db->init.busy ){
92002     Vdbe *v;
92003     char *z;
92004
92005     /* Make an entry in the sqlite_master table */
92006     v = sqlite3GetVdbe(pParse);
92007     if( v==0 ) goto triggerfinish_cleanup;
92008     sqlite3BeginWriteOperation(pParse, 0, iDb);
92009     z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
92010     sqlite3NestedParse(pParse,
92011        "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
92012        db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
92013        pTrig->table, z);
92014     sqlite3DbFree(db, z);
92015     sqlite3ChangeCookie(pParse, iDb);
92016     sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, sqlite3MPrintf(
92017         db, "type='trigger' AND name='%q'", zName), P4_DYNAMIC
92018     );
92019   }
92020
92021   if( db->init.busy ){
92022     Trigger *pLink = pTrig;
92023     Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
92024     pTrig = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), pTrig);
92025     if( pTrig ){
92026       db->mallocFailed = 1;
92027     }else if( pLink->pSchema==pLink->pTabSchema ){
92028       Table *pTab;
92029       int n = sqlite3Strlen30(pLink->table);
92030       pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n);
92031       assert( pTab!=0 );
92032       pLink->pNext = pTab->pTrigger;
92033       pTab->pTrigger = pLink;
92034     }
92035   }
92036
92037 triggerfinish_cleanup:
92038   sqlite3DeleteTrigger(db, pTrig);
92039   assert( !pParse->pNewTrigger );
92040   sqlite3DeleteTriggerStep(db, pStepList);
92041 }
92042
92043 /*
92044 ** Turn a SELECT statement (that the pSelect parameter points to) into
92045 ** a trigger step.  Return a pointer to a TriggerStep structure.
92046 **
92047 ** The parser calls this routine when it finds a SELECT statement in
92048 ** body of a TRIGGER.  
92049 */
92050 SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
92051   TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
92052   if( pTriggerStep==0 ) {
92053     sqlite3SelectDelete(db, pSelect);
92054     return 0;
92055   }
92056   pTriggerStep->op = TK_SELECT;
92057   pTriggerStep->pSelect = pSelect;
92058   pTriggerStep->orconf = OE_Default;
92059   return pTriggerStep;
92060 }
92061
92062 /*
92063 ** Allocate space to hold a new trigger step.  The allocated space
92064 ** holds both the TriggerStep object and the TriggerStep.target.z string.
92065 **
92066 ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
92067 */
92068 static TriggerStep *triggerStepAllocate(
92069   sqlite3 *db,                /* Database connection */
92070   u8 op,                      /* Trigger opcode */
92071   Token *pName                /* The target name */
92072 ){
92073   TriggerStep *pTriggerStep;
92074
92075   pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n);
92076   if( pTriggerStep ){
92077     char *z = (char*)&pTriggerStep[1];
92078     memcpy(z, pName->z, pName->n);
92079     pTriggerStep->target.z = z;
92080     pTriggerStep->target.n = pName->n;
92081     pTriggerStep->op = op;
92082   }
92083   return pTriggerStep;
92084 }
92085
92086 /*
92087 ** Build a trigger step out of an INSERT statement.  Return a pointer
92088 ** to the new trigger step.
92089 **
92090 ** The parser calls this routine when it sees an INSERT inside the
92091 ** body of a trigger.
92092 */
92093 SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
92094   sqlite3 *db,        /* The database connection */
92095   Token *pTableName,  /* Name of the table into which we insert */
92096   IdList *pColumn,    /* List of columns in pTableName to insert into */
92097   ExprList *pEList,   /* The VALUE clause: a list of values to be inserted */
92098   Select *pSelect,    /* A SELECT statement that supplies values */
92099   u8 orconf           /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
92100 ){
92101   TriggerStep *pTriggerStep;
92102
92103   assert(pEList == 0 || pSelect == 0);
92104   assert(pEList != 0 || pSelect != 0 || db->mallocFailed);
92105
92106   pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
92107   if( pTriggerStep ){
92108     pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
92109     pTriggerStep->pIdList = pColumn;
92110     pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
92111     pTriggerStep->orconf = orconf;
92112   }else{
92113     sqlite3IdListDelete(db, pColumn);
92114   }
92115   sqlite3ExprListDelete(db, pEList);
92116   sqlite3SelectDelete(db, pSelect);
92117
92118   return pTriggerStep;
92119 }
92120
92121 /*
92122 ** Construct a trigger step that implements an UPDATE statement and return
92123 ** a pointer to that trigger step.  The parser calls this routine when it
92124 ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
92125 */
92126 SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
92127   sqlite3 *db,         /* The database connection */
92128   Token *pTableName,   /* Name of the table to be updated */
92129   ExprList *pEList,    /* The SET clause: list of column and new values */
92130   Expr *pWhere,        /* The WHERE clause */
92131   u8 orconf            /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
92132 ){
92133   TriggerStep *pTriggerStep;
92134
92135   pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
92136   if( pTriggerStep ){
92137     pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
92138     pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
92139     pTriggerStep->orconf = orconf;
92140   }
92141   sqlite3ExprListDelete(db, pEList);
92142   sqlite3ExprDelete(db, pWhere);
92143   return pTriggerStep;
92144 }
92145
92146 /*
92147 ** Construct a trigger step that implements a DELETE statement and return
92148 ** a pointer to that trigger step.  The parser calls this routine when it
92149 ** sees a DELETE statement inside the body of a CREATE TRIGGER.
92150 */
92151 SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
92152   sqlite3 *db,            /* Database connection */
92153   Token *pTableName,      /* The table from which rows are deleted */
92154   Expr *pWhere            /* The WHERE clause */
92155 ){
92156   TriggerStep *pTriggerStep;
92157
92158   pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
92159   if( pTriggerStep ){
92160     pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
92161     pTriggerStep->orconf = OE_Default;
92162   }
92163   sqlite3ExprDelete(db, pWhere);
92164   return pTriggerStep;
92165 }
92166
92167 /* 
92168 ** Recursively delete a Trigger structure
92169 */
92170 SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
92171   if( pTrigger==0 ) return;
92172   sqlite3DeleteTriggerStep(db, pTrigger->step_list);
92173   sqlite3DbFree(db, pTrigger->zName);
92174   sqlite3DbFree(db, pTrigger->table);
92175   sqlite3ExprDelete(db, pTrigger->pWhen);
92176   sqlite3IdListDelete(db, pTrigger->pColumns);
92177   sqlite3DbFree(db, pTrigger);
92178 }
92179
92180 /*
92181 ** This function is called to drop a trigger from the database schema. 
92182 **
92183 ** This may be called directly from the parser and therefore identifies
92184 ** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
92185 ** same job as this routine except it takes a pointer to the trigger
92186 ** instead of the trigger name.
92187 **/
92188 SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
92189   Trigger *pTrigger = 0;
92190   int i;
92191   const char *zDb;
92192   const char *zName;
92193   int nName;
92194   sqlite3 *db = pParse->db;
92195
92196   if( db->mallocFailed ) goto drop_trigger_cleanup;
92197   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
92198     goto drop_trigger_cleanup;
92199   }
92200
92201   assert( pName->nSrc==1 );
92202   zDb = pName->a[0].zDatabase;
92203   zName = pName->a[0].zName;
92204   nName = sqlite3Strlen30(zName);
92205   for(i=OMIT_TEMPDB; i<db->nDb; i++){
92206     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
92207     if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
92208     pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
92209     if( pTrigger ) break;
92210   }
92211   if( !pTrigger ){
92212     if( !noErr ){
92213       sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
92214     }
92215     pParse->checkSchema = 1;
92216     goto drop_trigger_cleanup;
92217   }
92218   sqlite3DropTriggerPtr(pParse, pTrigger);
92219
92220 drop_trigger_cleanup:
92221   sqlite3SrcListDelete(db, pName);
92222 }
92223
92224 /*
92225 ** Return a pointer to the Table structure for the table that a trigger
92226 ** is set on.
92227 */
92228 static Table *tableOfTrigger(Trigger *pTrigger){
92229   int n = sqlite3Strlen30(pTrigger->table);
92230   return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
92231 }
92232
92233
92234 /*
92235 ** Drop a trigger given a pointer to that trigger. 
92236 */
92237 SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
92238   Table   *pTable;
92239   Vdbe *v;
92240   sqlite3 *db = pParse->db;
92241   int iDb;
92242
92243   iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
92244   assert( iDb>=0 && iDb<db->nDb );
92245   pTable = tableOfTrigger(pTrigger);
92246   assert( pTable );
92247   assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
92248 #ifndef SQLITE_OMIT_AUTHORIZATION
92249   {
92250     int code = SQLITE_DROP_TRIGGER;
92251     const char *zDb = db->aDb[iDb].zName;
92252     const char *zTab = SCHEMA_TABLE(iDb);
92253     if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
92254     if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
92255       sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
92256       return;
92257     }
92258   }
92259 #endif
92260
92261   /* Generate code to destroy the database record of the trigger.
92262   */
92263   assert( pTable!=0 );
92264   if( (v = sqlite3GetVdbe(pParse))!=0 ){
92265     int base;
92266     static const VdbeOpList dropTrigger[] = {
92267       { OP_Rewind,     0, ADDR(9),  0},
92268       { OP_String8,    0, 1,        0}, /* 1 */
92269       { OP_Column,     0, 1,        2},
92270       { OP_Ne,         2, ADDR(8),  1},
92271       { OP_String8,    0, 1,        0}, /* 4: "trigger" */
92272       { OP_Column,     0, 0,        2},
92273       { OP_Ne,         2, ADDR(8),  1},
92274       { OP_Delete,     0, 0,        0},
92275       { OP_Next,       0, ADDR(1),  0}, /* 8 */
92276     };
92277
92278     sqlite3BeginWriteOperation(pParse, 0, iDb);
92279     sqlite3OpenMasterTable(pParse, iDb);
92280     base = sqlite3VdbeAddOpList(v,  ArraySize(dropTrigger), dropTrigger);
92281     sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, 0);
92282     sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
92283     sqlite3ChangeCookie(pParse, iDb);
92284     sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
92285     sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
92286     if( pParse->nMem<3 ){
92287       pParse->nMem = 3;
92288     }
92289   }
92290 }
92291
92292 /*
92293 ** Remove a trigger from the hash tables of the sqlite* pointer.
92294 */
92295 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
92296   Hash *pHash = &(db->aDb[iDb].pSchema->trigHash);
92297   Trigger *pTrigger;
92298   pTrigger = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), 0);
92299   if( ALWAYS(pTrigger) ){
92300     if( pTrigger->pSchema==pTrigger->pTabSchema ){
92301       Table *pTab = tableOfTrigger(pTrigger);
92302       Trigger **pp;
92303       for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
92304       *pp = (*pp)->pNext;
92305     }
92306     sqlite3DeleteTrigger(db, pTrigger);
92307     db->flags |= SQLITE_InternChanges;
92308   }
92309 }
92310
92311 /*
92312 ** pEList is the SET clause of an UPDATE statement.  Each entry
92313 ** in pEList is of the format <id>=<expr>.  If any of the entries
92314 ** in pEList have an <id> which matches an identifier in pIdList,
92315 ** then return TRUE.  If pIdList==NULL, then it is considered a
92316 ** wildcard that matches anything.  Likewise if pEList==NULL then
92317 ** it matches anything so always return true.  Return false only
92318 ** if there is no match.
92319 */
92320 static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
92321   int e;
92322   if( pIdList==0 || NEVER(pEList==0) ) return 1;
92323   for(e=0; e<pEList->nExpr; e++){
92324     if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
92325   }
92326   return 0; 
92327 }
92328
92329 /*
92330 ** Return a list of all triggers on table pTab if there exists at least
92331 ** one trigger that must be fired when an operation of type 'op' is 
92332 ** performed on the table, and, if that operation is an UPDATE, if at
92333 ** least one of the columns in pChanges is being modified.
92334 */
92335 SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
92336   Parse *pParse,          /* Parse context */
92337   Table *pTab,            /* The table the contains the triggers */
92338   int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
92339   ExprList *pChanges,     /* Columns that change in an UPDATE statement */
92340   int *pMask              /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
92341 ){
92342   int mask = 0;
92343   Trigger *pList = sqlite3TriggerList(pParse, pTab);
92344   Trigger *p;
92345   assert( pList==0 || IsVirtual(pTab)==0 );
92346   for(p=pList; p; p=p->pNext){
92347     if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
92348       mask |= p->tr_tm;
92349     }
92350   }
92351   if( pMask ){
92352     *pMask = mask;
92353   }
92354   return (mask ? pList : 0);
92355 }
92356
92357 /*
92358 ** Convert the pStep->target token into a SrcList and return a pointer
92359 ** to that SrcList.
92360 **
92361 ** This routine adds a specific database name, if needed, to the target when
92362 ** forming the SrcList.  This prevents a trigger in one database from
92363 ** referring to a target in another database.  An exception is when the
92364 ** trigger is in TEMP in which case it can refer to any other database it
92365 ** wants.
92366 */
92367 static SrcList *targetSrcList(
92368   Parse *pParse,       /* The parsing context */
92369   TriggerStep *pStep   /* The trigger containing the target token */
92370 ){
92371   int iDb;             /* Index of the database to use */
92372   SrcList *pSrc;       /* SrcList to be returned */
92373
92374   pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
92375   if( pSrc ){
92376     assert( pSrc->nSrc>0 );
92377     assert( pSrc->a!=0 );
92378     iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
92379     if( iDb==0 || iDb>=2 ){
92380       sqlite3 *db = pParse->db;
92381       assert( iDb<pParse->db->nDb );
92382       pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
92383     }
92384   }
92385   return pSrc;
92386 }
92387
92388 /*
92389 ** Generate VDBE code for the statements inside the body of a single 
92390 ** trigger.
92391 */
92392 static int codeTriggerProgram(
92393   Parse *pParse,            /* The parser context */
92394   TriggerStep *pStepList,   /* List of statements inside the trigger body */
92395   int orconf                /* Conflict algorithm. (OE_Abort, etc) */  
92396 ){
92397   TriggerStep *pStep;
92398   Vdbe *v = pParse->pVdbe;
92399   sqlite3 *db = pParse->db;
92400
92401   assert( pParse->pTriggerTab && pParse->pToplevel );
92402   assert( pStepList );
92403   assert( v!=0 );
92404   for(pStep=pStepList; pStep; pStep=pStep->pNext){
92405     /* Figure out the ON CONFLICT policy that will be used for this step
92406     ** of the trigger program. If the statement that caused this trigger
92407     ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
92408     ** the ON CONFLICT policy that was specified as part of the trigger
92409     ** step statement. Example:
92410     **
92411     **   CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
92412     **     INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
92413     **   END;
92414     **
92415     **   INSERT INTO t1 ... ;            -- insert into t2 uses REPLACE policy
92416     **   INSERT OR IGNORE INTO t1 ... ;  -- insert into t2 uses IGNORE policy
92417     */
92418     pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
92419
92420     switch( pStep->op ){
92421       case TK_UPDATE: {
92422         sqlite3Update(pParse, 
92423           targetSrcList(pParse, pStep),
92424           sqlite3ExprListDup(db, pStep->pExprList, 0), 
92425           sqlite3ExprDup(db, pStep->pWhere, 0), 
92426           pParse->eOrconf
92427         );
92428         break;
92429       }
92430       case TK_INSERT: {
92431         sqlite3Insert(pParse, 
92432           targetSrcList(pParse, pStep),
92433           sqlite3ExprListDup(db, pStep->pExprList, 0), 
92434           sqlite3SelectDup(db, pStep->pSelect, 0), 
92435           sqlite3IdListDup(db, pStep->pIdList), 
92436           pParse->eOrconf
92437         );
92438         break;
92439       }
92440       case TK_DELETE: {
92441         sqlite3DeleteFrom(pParse, 
92442           targetSrcList(pParse, pStep),
92443           sqlite3ExprDup(db, pStep->pWhere, 0)
92444         );
92445         break;
92446       }
92447       default: assert( pStep->op==TK_SELECT ); {
92448         SelectDest sDest;
92449         Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
92450         sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
92451         sqlite3Select(pParse, pSelect, &sDest);
92452         sqlite3SelectDelete(db, pSelect);
92453         break;
92454       }
92455     } 
92456     if( pStep->op!=TK_SELECT ){
92457       sqlite3VdbeAddOp0(v, OP_ResetCount);
92458     }
92459   }
92460
92461   return 0;
92462 }
92463
92464 #ifdef SQLITE_DEBUG
92465 /*
92466 ** This function is used to add VdbeComment() annotations to a VDBE
92467 ** program. It is not used in production code, only for debugging.
92468 */
92469 static const char *onErrorText(int onError){
92470   switch( onError ){
92471     case OE_Abort:    return "abort";
92472     case OE_Rollback: return "rollback";
92473     case OE_Fail:     return "fail";
92474     case OE_Replace:  return "replace";
92475     case OE_Ignore:   return "ignore";
92476     case OE_Default:  return "default";
92477   }
92478   return "n/a";
92479 }
92480 #endif
92481
92482 /*
92483 ** Parse context structure pFrom has just been used to create a sub-vdbe
92484 ** (trigger program). If an error has occurred, transfer error information
92485 ** from pFrom to pTo.
92486 */
92487 static void transferParseError(Parse *pTo, Parse *pFrom){
92488   assert( pFrom->zErrMsg==0 || pFrom->nErr );
92489   assert( pTo->zErrMsg==0 || pTo->nErr );
92490   if( pTo->nErr==0 ){
92491     pTo->zErrMsg = pFrom->zErrMsg;
92492     pTo->nErr = pFrom->nErr;
92493   }else{
92494     sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
92495   }
92496 }
92497
92498 /*
92499 ** Create and populate a new TriggerPrg object with a sub-program 
92500 ** implementing trigger pTrigger with ON CONFLICT policy orconf.
92501 */
92502 static TriggerPrg *codeRowTrigger(
92503   Parse *pParse,       /* Current parse context */
92504   Trigger *pTrigger,   /* Trigger to code */
92505   Table *pTab,         /* The table pTrigger is attached to */
92506   int orconf           /* ON CONFLICT policy to code trigger program with */
92507 ){
92508   Parse *pTop = sqlite3ParseToplevel(pParse);
92509   sqlite3 *db = pParse->db;   /* Database handle */
92510   TriggerPrg *pPrg;           /* Value to return */
92511   Expr *pWhen = 0;            /* Duplicate of trigger WHEN expression */
92512   Vdbe *v;                    /* Temporary VM */
92513   NameContext sNC;            /* Name context for sub-vdbe */
92514   SubProgram *pProgram = 0;   /* Sub-vdbe for trigger program */
92515   Parse *pSubParse;           /* Parse context for sub-vdbe */
92516   int iEndTrigger = 0;        /* Label to jump to if WHEN is false */
92517
92518   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
92519   assert( pTop->pVdbe );
92520
92521   /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
92522   ** are freed if an error occurs, link them into the Parse.pTriggerPrg 
92523   ** list of the top-level Parse object sooner rather than later.  */
92524   pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
92525   if( !pPrg ) return 0;
92526   pPrg->pNext = pTop->pTriggerPrg;
92527   pTop->pTriggerPrg = pPrg;
92528   pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
92529   if( !pProgram ) return 0;
92530   sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
92531   pPrg->pTrigger = pTrigger;
92532   pPrg->orconf = orconf;
92533   pPrg->aColmask[0] = 0xffffffff;
92534   pPrg->aColmask[1] = 0xffffffff;
92535
92536   /* Allocate and populate a new Parse context to use for coding the 
92537   ** trigger sub-program.  */
92538   pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
92539   if( !pSubParse ) return 0;
92540   memset(&sNC, 0, sizeof(sNC));
92541   sNC.pParse = pSubParse;
92542   pSubParse->db = db;
92543   pSubParse->pTriggerTab = pTab;
92544   pSubParse->pToplevel = pTop;
92545   pSubParse->zAuthContext = pTrigger->zName;
92546   pSubParse->eTriggerOp = pTrigger->op;
92547   pSubParse->nQueryLoop = pParse->nQueryLoop;
92548
92549   v = sqlite3GetVdbe(pSubParse);
92550   if( v ){
92551     VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)", 
92552       pTrigger->zName, onErrorText(orconf),
92553       (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
92554         (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
92555         (pTrigger->op==TK_INSERT ? "INSERT" : ""),
92556         (pTrigger->op==TK_DELETE ? "DELETE" : ""),
92557       pTab->zName
92558     ));
92559 #ifndef SQLITE_OMIT_TRACE
92560     sqlite3VdbeChangeP4(v, -1, 
92561       sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
92562     );
92563 #endif
92564
92565     /* If one was specified, code the WHEN clause. If it evaluates to false
92566     ** (or NULL) the sub-vdbe is immediately halted by jumping to the 
92567     ** OP_Halt inserted at the end of the program.  */
92568     if( pTrigger->pWhen ){
92569       pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
92570       if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen) 
92571        && db->mallocFailed==0 
92572       ){
92573         iEndTrigger = sqlite3VdbeMakeLabel(v);
92574         sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
92575       }
92576       sqlite3ExprDelete(db, pWhen);
92577     }
92578
92579     /* Code the trigger program into the sub-vdbe. */
92580     codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
92581
92582     /* Insert an OP_Halt at the end of the sub-program. */
92583     if( iEndTrigger ){
92584       sqlite3VdbeResolveLabel(v, iEndTrigger);
92585     }
92586     sqlite3VdbeAddOp0(v, OP_Halt);
92587     VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
92588
92589     transferParseError(pParse, pSubParse);
92590     if( db->mallocFailed==0 ){
92591       pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
92592     }
92593     pProgram->nMem = pSubParse->nMem;
92594     pProgram->nCsr = pSubParse->nTab;
92595     pProgram->token = (void *)pTrigger;
92596     pPrg->aColmask[0] = pSubParse->oldmask;
92597     pPrg->aColmask[1] = pSubParse->newmask;
92598     sqlite3VdbeDelete(v);
92599   }
92600
92601   assert( !pSubParse->pAinc       && !pSubParse->pZombieTab );
92602   assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
92603   sqlite3StackFree(db, pSubParse);
92604
92605   return pPrg;
92606 }
92607     
92608 /*
92609 ** Return a pointer to a TriggerPrg object containing the sub-program for
92610 ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
92611 ** TriggerPrg object exists, a new object is allocated and populated before
92612 ** being returned.
92613 */
92614 static TriggerPrg *getRowTrigger(
92615   Parse *pParse,       /* Current parse context */
92616   Trigger *pTrigger,   /* Trigger to code */
92617   Table *pTab,         /* The table trigger pTrigger is attached to */
92618   int orconf           /* ON CONFLICT algorithm. */
92619 ){
92620   Parse *pRoot = sqlite3ParseToplevel(pParse);
92621   TriggerPrg *pPrg;
92622
92623   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
92624
92625   /* It may be that this trigger has already been coded (or is in the
92626   ** process of being coded). If this is the case, then an entry with
92627   ** a matching TriggerPrg.pTrigger field will be present somewhere
92628   ** in the Parse.pTriggerPrg list. Search for such an entry.  */
92629   for(pPrg=pRoot->pTriggerPrg; 
92630       pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf); 
92631       pPrg=pPrg->pNext
92632   );
92633
92634   /* If an existing TriggerPrg could not be located, create a new one. */
92635   if( !pPrg ){
92636     pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
92637   }
92638
92639   return pPrg;
92640 }
92641
92642 /*
92643 ** Generate code for the trigger program associated with trigger p on 
92644 ** table pTab. The reg, orconf and ignoreJump parameters passed to this
92645 ** function are the same as those described in the header function for
92646 ** sqlite3CodeRowTrigger()
92647 */
92648 SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
92649   Parse *pParse,       /* Parse context */
92650   Trigger *p,          /* Trigger to code */
92651   Table *pTab,         /* The table to code triggers from */
92652   int reg,             /* Reg array containing OLD.* and NEW.* values */
92653   int orconf,          /* ON CONFLICT policy */
92654   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
92655 ){
92656   Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
92657   TriggerPrg *pPrg;
92658   pPrg = getRowTrigger(pParse, p, pTab, orconf);
92659   assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
92660
92661   /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program 
92662   ** is a pointer to the sub-vdbe containing the trigger program.  */
92663   if( pPrg ){
92664     int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
92665
92666     sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
92667     sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
92668     VdbeComment(
92669         (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
92670
92671     /* Set the P5 operand of the OP_Program instruction to non-zero if
92672     ** recursive invocation of this trigger program is disallowed. Recursive
92673     ** invocation is disallowed if (a) the sub-program is really a trigger,
92674     ** not a foreign key action, and (b) the flag to enable recursive triggers
92675     ** is clear.  */
92676     sqlite3VdbeChangeP5(v, (u8)bRecursive);
92677   }
92678 }
92679
92680 /*
92681 ** This is called to code the required FOR EACH ROW triggers for an operation
92682 ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
92683 ** is given by the op paramater. The tr_tm parameter determines whether the
92684 ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
92685 ** parameter pChanges is passed the list of columns being modified.
92686 **
92687 ** If there are no triggers that fire at the specified time for the specified
92688 ** operation on pTab, this function is a no-op.
92689 **
92690 ** The reg argument is the address of the first in an array of registers 
92691 ** that contain the values substituted for the new.* and old.* references
92692 ** in the trigger program. If N is the number of columns in table pTab
92693 ** (a copy of pTab->nCol), then registers are populated as follows:
92694 **
92695 **   Register       Contains
92696 **   ------------------------------------------------------
92697 **   reg+0          OLD.rowid
92698 **   reg+1          OLD.* value of left-most column of pTab
92699 **   ...            ...
92700 **   reg+N          OLD.* value of right-most column of pTab
92701 **   reg+N+1        NEW.rowid
92702 **   reg+N+2        OLD.* value of left-most column of pTab
92703 **   ...            ...
92704 **   reg+N+N+1      NEW.* value of right-most column of pTab
92705 **
92706 ** For ON DELETE triggers, the registers containing the NEW.* values will
92707 ** never be accessed by the trigger program, so they are not allocated or 
92708 ** populated by the caller (there is no data to populate them with anyway). 
92709 ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
92710 ** are never accessed, and so are not allocated by the caller. So, for an
92711 ** ON INSERT trigger, the value passed to this function as parameter reg
92712 ** is not a readable register, although registers (reg+N) through 
92713 ** (reg+N+N+1) are.
92714 **
92715 ** Parameter orconf is the default conflict resolution algorithm for the
92716 ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
92717 ** is the instruction that control should jump to if a trigger program
92718 ** raises an IGNORE exception.
92719 */
92720 SQLITE_PRIVATE void sqlite3CodeRowTrigger(
92721   Parse *pParse,       /* Parse context */
92722   Trigger *pTrigger,   /* List of triggers on table pTab */
92723   int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
92724   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
92725   int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
92726   Table *pTab,         /* The table to code triggers from */
92727   int reg,             /* The first in an array of registers (see above) */
92728   int orconf,          /* ON CONFLICT policy */
92729   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
92730 ){
92731   Trigger *p;          /* Used to iterate through pTrigger list */
92732
92733   assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
92734   assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
92735   assert( (op==TK_UPDATE)==(pChanges!=0) );
92736
92737   for(p=pTrigger; p; p=p->pNext){
92738
92739     /* Sanity checking:  The schema for the trigger and for the table are
92740     ** always defined.  The trigger must be in the same schema as the table
92741     ** or else it must be a TEMP trigger. */
92742     assert( p->pSchema!=0 );
92743     assert( p->pTabSchema!=0 );
92744     assert( p->pSchema==p->pTabSchema 
92745          || p->pSchema==pParse->db->aDb[1].pSchema );
92746
92747     /* Determine whether we should code this trigger */
92748     if( p->op==op 
92749      && p->tr_tm==tr_tm 
92750      && checkColumnOverlap(p->pColumns, pChanges)
92751     ){
92752       sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
92753     }
92754   }
92755 }
92756
92757 /*
92758 ** Triggers may access values stored in the old.* or new.* pseudo-table. 
92759 ** This function returns a 32-bit bitmask indicating which columns of the 
92760 ** old.* or new.* tables actually are used by triggers. This information 
92761 ** may be used by the caller, for example, to avoid having to load the entire
92762 ** old.* record into memory when executing an UPDATE or DELETE command.
92763 **
92764 ** Bit 0 of the returned mask is set if the left-most column of the
92765 ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
92766 ** the second leftmost column value is required, and so on. If there
92767 ** are more than 32 columns in the table, and at least one of the columns
92768 ** with an index greater than 32 may be accessed, 0xffffffff is returned.
92769 **
92770 ** It is not possible to determine if the old.rowid or new.rowid column is 
92771 ** accessed by triggers. The caller must always assume that it is.
92772 **
92773 ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
92774 ** applies to the old.* table. If 1, the new.* table.
92775 **
92776 ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
92777 ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
92778 ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
92779 ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
92780 ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
92781 */
92782 SQLITE_PRIVATE u32 sqlite3TriggerColmask(
92783   Parse *pParse,       /* Parse context */
92784   Trigger *pTrigger,   /* List of triggers on table pTab */
92785   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
92786   int isNew,           /* 1 for new.* ref mask, 0 for old.* ref mask */
92787   int tr_tm,           /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
92788   Table *pTab,         /* The table to code triggers from */
92789   int orconf           /* Default ON CONFLICT policy for trigger steps */
92790 ){
92791   const int op = pChanges ? TK_UPDATE : TK_DELETE;
92792   u32 mask = 0;
92793   Trigger *p;
92794
92795   assert( isNew==1 || isNew==0 );
92796   for(p=pTrigger; p; p=p->pNext){
92797     if( p->op==op && (tr_tm&p->tr_tm)
92798      && checkColumnOverlap(p->pColumns,pChanges)
92799     ){
92800       TriggerPrg *pPrg;
92801       pPrg = getRowTrigger(pParse, p, pTab, orconf);
92802       if( pPrg ){
92803         mask |= pPrg->aColmask[isNew];
92804       }
92805     }
92806   }
92807
92808   return mask;
92809 }
92810
92811 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
92812
92813 /************** End of trigger.c *********************************************/
92814 /************** Begin file update.c ******************************************/
92815 /*
92816 ** 2001 September 15
92817 **
92818 ** The author disclaims copyright to this source code.  In place of
92819 ** a legal notice, here is a blessing:
92820 **
92821 **    May you do good and not evil.
92822 **    May you find forgiveness for yourself and forgive others.
92823 **    May you share freely, never taking more than you give.
92824 **
92825 *************************************************************************
92826 ** This file contains C code routines that are called by the parser
92827 ** to handle UPDATE statements.
92828 */
92829
92830 #ifndef SQLITE_OMIT_VIRTUALTABLE
92831 /* Forward declaration */
92832 static void updateVirtualTable(
92833   Parse *pParse,       /* The parsing context */
92834   SrcList *pSrc,       /* The virtual table to be modified */
92835   Table *pTab,         /* The virtual table */
92836   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
92837   Expr *pRowidExpr,    /* Expression used to recompute the rowid */
92838   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
92839   Expr *pWhere         /* WHERE clause of the UPDATE statement */
92840 );
92841 #endif /* SQLITE_OMIT_VIRTUALTABLE */
92842
92843 /*
92844 ** The most recently coded instruction was an OP_Column to retrieve the
92845 ** i-th column of table pTab. This routine sets the P4 parameter of the 
92846 ** OP_Column to the default value, if any.
92847 **
92848 ** The default value of a column is specified by a DEFAULT clause in the 
92849 ** column definition. This was either supplied by the user when the table
92850 ** was created, or added later to the table definition by an ALTER TABLE
92851 ** command. If the latter, then the row-records in the table btree on disk
92852 ** may not contain a value for the column and the default value, taken
92853 ** from the P4 parameter of the OP_Column instruction, is returned instead.
92854 ** If the former, then all row-records are guaranteed to include a value
92855 ** for the column and the P4 value is not required.
92856 **
92857 ** Column definitions created by an ALTER TABLE command may only have 
92858 ** literal default values specified: a number, null or a string. (If a more
92859 ** complicated default expression value was provided, it is evaluated 
92860 ** when the ALTER TABLE is executed and one of the literal values written
92861 ** into the sqlite_master table.)
92862 **
92863 ** Therefore, the P4 parameter is only required if the default value for
92864 ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
92865 ** function is capable of transforming these types of expressions into
92866 ** sqlite3_value objects.
92867 **
92868 ** If parameter iReg is not negative, code an OP_RealAffinity instruction
92869 ** on register iReg. This is used when an equivalent integer value is 
92870 ** stored in place of an 8-byte floating point value in order to save 
92871 ** space.
92872 */
92873 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
92874   assert( pTab!=0 );
92875   if( !pTab->pSelect ){
92876     sqlite3_value *pValue;
92877     u8 enc = ENC(sqlite3VdbeDb(v));
92878     Column *pCol = &pTab->aCol[i];
92879     VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
92880     assert( i<pTab->nCol );
92881     sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc, 
92882                          pCol->affinity, &pValue);
92883     if( pValue ){
92884       sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
92885     }
92886 #ifndef SQLITE_OMIT_FLOATING_POINT
92887     if( iReg>=0 && pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
92888       sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
92889     }
92890 #endif
92891   }
92892 }
92893
92894 /*
92895 ** Process an UPDATE statement.
92896 **
92897 **   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
92898 **          \_______/ \________/     \______/       \________________/
92899 *            onError   pTabList      pChanges             pWhere
92900 */
92901 SQLITE_PRIVATE void sqlite3Update(
92902   Parse *pParse,         /* The parser context */
92903   SrcList *pTabList,     /* The table in which we should change things */
92904   ExprList *pChanges,    /* Things to be changed */
92905   Expr *pWhere,          /* The WHERE clause.  May be null */
92906   int onError            /* How to handle constraint errors */
92907 ){
92908   int i, j;              /* Loop counters */
92909   Table *pTab;           /* The table to be updated */
92910   int addr = 0;          /* VDBE instruction address of the start of the loop */
92911   WhereInfo *pWInfo;     /* Information about the WHERE clause */
92912   Vdbe *v;               /* The virtual database engine */
92913   Index *pIdx;           /* For looping over indices */
92914   int nIdx;              /* Number of indices that need updating */
92915   int iCur;              /* VDBE Cursor number of pTab */
92916   sqlite3 *db;           /* The database structure */
92917   int *aRegIdx = 0;      /* One register assigned to each index to be updated */
92918   int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
92919                          ** an expression for the i-th column of the table.
92920                          ** aXRef[i]==-1 if the i-th column is not changed. */
92921   int chngRowid;         /* True if the record number is being changed */
92922   Expr *pRowidExpr = 0;  /* Expression defining the new record number */
92923   int openAll = 0;       /* True if all indices need to be opened */
92924   AuthContext sContext;  /* The authorization context */
92925   NameContext sNC;       /* The name-context to resolve expressions in */
92926   int iDb;               /* Database containing the table being updated */
92927   int okOnePass;         /* True for one-pass algorithm without the FIFO */
92928   int hasFK;             /* True if foreign key processing is required */
92929
92930 #ifndef SQLITE_OMIT_TRIGGER
92931   int isView;            /* True when updating a view (INSTEAD OF trigger) */
92932   Trigger *pTrigger;     /* List of triggers on pTab, if required */
92933   int tmask;             /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
92934 #endif
92935   int newmask;           /* Mask of NEW.* columns accessed by BEFORE triggers */
92936
92937   /* Register Allocations */
92938   int regRowCount = 0;   /* A count of rows changed */
92939   int regOldRowid;       /* The old rowid */
92940   int regNewRowid;       /* The new rowid */
92941   int regNew;
92942   int regOld = 0;
92943   int regRowSet = 0;     /* Rowset of rows to be updated */
92944   int regRec;            /* Register used for new table record to insert */
92945
92946   memset(&sContext, 0, sizeof(sContext));
92947   db = pParse->db;
92948   if( pParse->nErr || db->mallocFailed ){
92949     goto update_cleanup;
92950   }
92951   assert( pTabList->nSrc==1 );
92952
92953   /* Locate the table which we want to update. 
92954   */
92955   pTab = sqlite3SrcListLookup(pParse, pTabList);
92956   if( pTab==0 ) goto update_cleanup;
92957   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
92958
92959   /* Figure out if we have any triggers and if the table being
92960   ** updated is a view.
92961   */
92962 #ifndef SQLITE_OMIT_TRIGGER
92963   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
92964   isView = pTab->pSelect!=0;
92965   assert( pTrigger || tmask==0 );
92966 #else
92967 # define pTrigger 0
92968 # define isView 0
92969 # define tmask 0
92970 #endif
92971 #ifdef SQLITE_OMIT_VIEW
92972 # undef isView
92973 # define isView 0
92974 #endif
92975
92976   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
92977     goto update_cleanup;
92978   }
92979   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
92980     goto update_cleanup;
92981   }
92982   aXRef = sqlite3DbMallocRaw(db, sizeof(int) * pTab->nCol );
92983   if( aXRef==0 ) goto update_cleanup;
92984   for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
92985
92986   /* Allocate a cursors for the main database table and for all indices.
92987   ** The index cursors might not be used, but if they are used they
92988   ** need to occur right after the database cursor.  So go ahead and
92989   ** allocate enough space, just in case.
92990   */
92991   pTabList->a[0].iCursor = iCur = pParse->nTab++;
92992   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
92993     pParse->nTab++;
92994   }
92995
92996   /* Initialize the name-context */
92997   memset(&sNC, 0, sizeof(sNC));
92998   sNC.pParse = pParse;
92999   sNC.pSrcList = pTabList;
93000
93001   /* Resolve the column names in all the expressions of the
93002   ** of the UPDATE statement.  Also find the column index
93003   ** for each column to be updated in the pChanges array.  For each
93004   ** column to be updated, make sure we have authorization to change
93005   ** that column.
93006   */
93007   chngRowid = 0;
93008   for(i=0; i<pChanges->nExpr; i++){
93009     if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
93010       goto update_cleanup;
93011     }
93012     for(j=0; j<pTab->nCol; j++){
93013       if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
93014         if( j==pTab->iPKey ){
93015           chngRowid = 1;
93016           pRowidExpr = pChanges->a[i].pExpr;
93017         }
93018         aXRef[j] = i;
93019         break;
93020       }
93021     }
93022     if( j>=pTab->nCol ){
93023       if( sqlite3IsRowid(pChanges->a[i].zName) ){
93024         chngRowid = 1;
93025         pRowidExpr = pChanges->a[i].pExpr;
93026       }else{
93027         sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
93028         pParse->checkSchema = 1;
93029         goto update_cleanup;
93030       }
93031     }
93032 #ifndef SQLITE_OMIT_AUTHORIZATION
93033     {
93034       int rc;
93035       rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
93036                            pTab->aCol[j].zName, db->aDb[iDb].zName);
93037       if( rc==SQLITE_DENY ){
93038         goto update_cleanup;
93039       }else if( rc==SQLITE_IGNORE ){
93040         aXRef[j] = -1;
93041       }
93042     }
93043 #endif
93044   }
93045
93046   hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngRowid);
93047
93048   /* Allocate memory for the array aRegIdx[].  There is one entry in the
93049   ** array for each index associated with table being updated.  Fill in
93050   ** the value with a register number for indices that are to be used
93051   ** and with zero for unused indices.
93052   */
93053   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
93054   if( nIdx>0 ){
93055     aRegIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx );
93056     if( aRegIdx==0 ) goto update_cleanup;
93057   }
93058   for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
93059     int reg;
93060     if( chngRowid ){
93061       reg = ++pParse->nMem;
93062     }else{
93063       reg = 0;
93064       for(i=0; i<pIdx->nColumn; i++){
93065         if( aXRef[pIdx->aiColumn[i]]>=0 ){
93066           reg = ++pParse->nMem;
93067           break;
93068         }
93069       }
93070     }
93071     aRegIdx[j] = reg;
93072   }
93073
93074   /* Begin generating code. */
93075   v = sqlite3GetVdbe(pParse);
93076   if( v==0 ) goto update_cleanup;
93077   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
93078   sqlite3BeginWriteOperation(pParse, 1, iDb);
93079
93080 #ifndef SQLITE_OMIT_VIRTUALTABLE
93081   /* Virtual tables must be handled separately */
93082   if( IsVirtual(pTab) ){
93083     updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
93084                        pWhere);
93085     pWhere = 0;
93086     pTabList = 0;
93087     goto update_cleanup;
93088   }
93089 #endif
93090
93091   /* Allocate required registers. */
93092   regOldRowid = regNewRowid = ++pParse->nMem;
93093   if( pTrigger || hasFK ){
93094     regOld = pParse->nMem + 1;
93095     pParse->nMem += pTab->nCol;
93096   }
93097   if( chngRowid || pTrigger || hasFK ){
93098     regNewRowid = ++pParse->nMem;
93099   }
93100   regNew = pParse->nMem + 1;
93101   pParse->nMem += pTab->nCol;
93102   regRec = ++pParse->nMem;
93103
93104   /* Start the view context. */
93105   if( isView ){
93106     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
93107   }
93108
93109   /* If we are trying to update a view, realize that view into
93110   ** a ephemeral table.
93111   */
93112 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
93113   if( isView ){
93114     sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
93115   }
93116 #endif
93117
93118   /* Resolve the column names in all the expressions in the
93119   ** WHERE clause.
93120   */
93121   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
93122     goto update_cleanup;
93123   }
93124
93125   /* Begin the database scan
93126   */
93127   sqlite3VdbeAddOp2(v, OP_Null, 0, regOldRowid);
93128   pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,0, WHERE_ONEPASS_DESIRED);
93129   if( pWInfo==0 ) goto update_cleanup;
93130   okOnePass = pWInfo->okOnePass;
93131
93132   /* Remember the rowid of every item to be updated.
93133   */
93134   sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid);
93135   if( !okOnePass ){
93136     regRowSet = ++pParse->nMem;
93137     sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
93138   }
93139
93140   /* End the database scan loop.
93141   */
93142   sqlite3WhereEnd(pWInfo);
93143
93144   /* Initialize the count of updated rows
93145   */
93146   if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
93147     regRowCount = ++pParse->nMem;
93148     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
93149   }
93150
93151   if( !isView ){
93152     /* 
93153     ** Open every index that needs updating.  Note that if any
93154     ** index could potentially invoke a REPLACE conflict resolution 
93155     ** action, then we need to open all indices because we might need
93156     ** to be deleting some records.
93157     */
93158     if( !okOnePass ) sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite); 
93159     if( onError==OE_Replace ){
93160       openAll = 1;
93161     }else{
93162       openAll = 0;
93163       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
93164         if( pIdx->onError==OE_Replace ){
93165           openAll = 1;
93166           break;
93167         }
93168       }
93169     }
93170     for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
93171       if( openAll || aRegIdx[i]>0 ){
93172         KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
93173         sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb,
93174                        (char*)pKey, P4_KEYINFO_HANDOFF);
93175         assert( pParse->nTab>iCur+i+1 );
93176       }
93177     }
93178   }
93179
93180   /* Top of the update loop */
93181   if( okOnePass ){
93182     int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid);
93183     addr = sqlite3VdbeAddOp0(v, OP_Goto);
93184     sqlite3VdbeJumpHere(v, a1);
93185   }else{
93186     addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, 0, regOldRowid);
93187   }
93188
93189   /* Make cursor iCur point to the record that is being updated. If
93190   ** this record does not exist for some reason (deleted by a trigger,
93191   ** for example, then jump to the next iteration of the RowSet loop.  */
93192   sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
93193
93194   /* If the record number will change, set register regNewRowid to
93195   ** contain the new value. If the record number is not being modified,
93196   ** then regNewRowid is the same register as regOldRowid, which is
93197   ** already populated.  */
93198   assert( chngRowid || pTrigger || hasFK || regOldRowid==regNewRowid );
93199   if( chngRowid ){
93200     sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
93201     sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
93202   }
93203
93204   /* If there are triggers on this table, populate an array of registers 
93205   ** with the required old.* column data.  */
93206   if( hasFK || pTrigger ){
93207     u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
93208     oldmask |= sqlite3TriggerColmask(pParse, 
93209         pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
93210     );
93211     for(i=0; i<pTab->nCol; i++){
93212       if( aXRef[i]<0 || oldmask==0xffffffff || (oldmask & (1<<i)) ){
93213         sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOld+i);
93214       }else{
93215         sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
93216       }
93217     }
93218     if( chngRowid==0 ){
93219       sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
93220     }
93221   }
93222
93223   /* Populate the array of registers beginning at regNew with the new
93224   ** row data. This array is used to check constaints, create the new
93225   ** table and index records, and as the values for any new.* references
93226   ** made by triggers.
93227   **
93228   ** If there are one or more BEFORE triggers, then do not populate the
93229   ** registers associated with columns that are (a) not modified by
93230   ** this UPDATE statement and (b) not accessed by new.* references. The
93231   ** values for registers not modified by the UPDATE must be reloaded from 
93232   ** the database after the BEFORE triggers are fired anyway (as the trigger 
93233   ** may have modified them). So not loading those that are not going to
93234   ** be used eliminates some redundant opcodes.
93235   */
93236   newmask = sqlite3TriggerColmask(
93237       pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
93238   );
93239   for(i=0; i<pTab->nCol; i++){
93240     if( i==pTab->iPKey ){
93241       sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
93242     }else{
93243       j = aXRef[i];
93244       if( j>=0 ){
93245         sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
93246       }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask&(1<<i)) ){
93247         /* This branch loads the value of a column that will not be changed 
93248         ** into a register. This is done if there are no BEFORE triggers, or
93249         ** if there are one or more BEFORE triggers that use this value via
93250         ** a new.* reference in a trigger program.
93251         */
93252         testcase( i==31 );
93253         testcase( i==32 );
93254         sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
93255         sqlite3ColumnDefault(v, pTab, i, regNew+i);
93256       }
93257     }
93258   }
93259
93260   /* Fire any BEFORE UPDATE triggers. This happens before constraints are
93261   ** verified. One could argue that this is wrong.
93262   */
93263   if( tmask&TRIGGER_BEFORE ){
93264     sqlite3VdbeAddOp2(v, OP_Affinity, regNew, pTab->nCol);
93265     sqlite3TableAffinityStr(v, pTab);
93266     sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, 
93267         TRIGGER_BEFORE, pTab, regOldRowid, onError, addr);
93268
93269     /* The row-trigger may have deleted the row being updated. In this
93270     ** case, jump to the next row. No updates or AFTER triggers are 
93271     ** required. This behaviour - what happens when the row being updated
93272     ** is deleted or renamed by a BEFORE trigger - is left undefined in the
93273     ** documentation.
93274     */
93275     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
93276
93277     /* If it did not delete it, the row-trigger may still have modified 
93278     ** some of the columns of the row being updated. Load the values for 
93279     ** all columns not modified by the update statement into their 
93280     ** registers in case this has happened.
93281     */
93282     for(i=0; i<pTab->nCol; i++){
93283       if( aXRef[i]<0 && i!=pTab->iPKey ){
93284         sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
93285         sqlite3ColumnDefault(v, pTab, i, regNew+i);
93286       }
93287     }
93288   }
93289
93290   if( !isView ){
93291     int j1;                       /* Address of jump instruction */
93292
93293     /* Do constraint checks. */
93294     sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
93295         aRegIdx, (chngRowid?regOldRowid:0), 1, onError, addr, 0);
93296
93297     /* Do FK constraint checks. */
93298     if( hasFK ){
93299       sqlite3FkCheck(pParse, pTab, regOldRowid, 0);
93300     }
93301
93302     /* Delete the index entries associated with the current record.  */
93303     j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
93304     sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);
93305   
93306     /* If changing the record number, delete the old record.  */
93307     if( hasFK || chngRowid ){
93308       sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0);
93309     }
93310     sqlite3VdbeJumpHere(v, j1);
93311
93312     if( hasFK ){
93313       sqlite3FkCheck(pParse, pTab, 0, regNewRowid);
93314     }
93315   
93316     /* Insert the new index entries and the new record. */
93317     sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, aRegIdx, 1, 0, 0);
93318
93319     /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
93320     ** handle rows (possibly in other tables) that refer via a foreign key
93321     ** to the row just updated. */ 
93322     if( hasFK ){
93323       sqlite3FkActions(pParse, pTab, pChanges, regOldRowid);
93324     }
93325   }
93326
93327   /* Increment the row counter 
93328   */
93329   if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
93330     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
93331   }
93332
93333   sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, 
93334       TRIGGER_AFTER, pTab, regOldRowid, onError, addr);
93335
93336   /* Repeat the above with the next record to be updated, until
93337   ** all record selected by the WHERE clause have been updated.
93338   */
93339   sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
93340   sqlite3VdbeJumpHere(v, addr);
93341
93342   /* Close all tables */
93343   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
93344     if( openAll || aRegIdx[i]>0 ){
93345       sqlite3VdbeAddOp2(v, OP_Close, iCur+i+1, 0);
93346     }
93347   }
93348   sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
93349
93350   /* Update the sqlite_sequence table by storing the content of the
93351   ** maximum rowid counter values recorded while inserting into
93352   ** autoincrement tables.
93353   */
93354   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
93355     sqlite3AutoincrementEnd(pParse);
93356   }
93357
93358   /*
93359   ** Return the number of rows that were changed. If this routine is 
93360   ** generating code because of a call to sqlite3NestedParse(), do not
93361   ** invoke the callback function.
93362   */
93363   if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
93364     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
93365     sqlite3VdbeSetNumCols(v, 1);
93366     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
93367   }
93368
93369 update_cleanup:
93370   sqlite3AuthContextPop(&sContext);
93371   sqlite3DbFree(db, aRegIdx);
93372   sqlite3DbFree(db, aXRef);
93373   sqlite3SrcListDelete(db, pTabList);
93374   sqlite3ExprListDelete(db, pChanges);
93375   sqlite3ExprDelete(db, pWhere);
93376   return;
93377 }
93378 /* Make sure "isView" and other macros defined above are undefined. Otherwise
93379 ** thely may interfere with compilation of other functions in this file
93380 ** (or in another file, if this file becomes part of the amalgamation).  */
93381 #ifdef isView
93382  #undef isView
93383 #endif
93384 #ifdef pTrigger
93385  #undef pTrigger
93386 #endif
93387
93388 #ifndef SQLITE_OMIT_VIRTUALTABLE
93389 /*
93390 ** Generate code for an UPDATE of a virtual table.
93391 **
93392 ** The strategy is that we create an ephemerial table that contains
93393 ** for each row to be changed:
93394 **
93395 **   (A)  The original rowid of that row.
93396 **   (B)  The revised rowid for the row. (note1)
93397 **   (C)  The content of every column in the row.
93398 **
93399 ** Then we loop over this ephemeral table and for each row in
93400 ** the ephermeral table call VUpdate.
93401 **
93402 ** When finished, drop the ephemeral table.
93403 **
93404 ** (note1) Actually, if we know in advance that (A) is always the same
93405 ** as (B) we only store (A), then duplicate (A) when pulling
93406 ** it out of the ephemeral table before calling VUpdate.
93407 */
93408 static void updateVirtualTable(
93409   Parse *pParse,       /* The parsing context */
93410   SrcList *pSrc,       /* The virtual table to be modified */
93411   Table *pTab,         /* The virtual table */
93412   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
93413   Expr *pRowid,        /* Expression used to recompute the rowid */
93414   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
93415   Expr *pWhere         /* WHERE clause of the UPDATE statement */
93416 ){
93417   Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
93418   ExprList *pEList = 0;     /* The result set of the SELECT statement */
93419   Select *pSelect = 0;      /* The SELECT statement */
93420   Expr *pExpr;              /* Temporary expression */
93421   int ephemTab;             /* Table holding the result of the SELECT */
93422   int i;                    /* Loop counter */
93423   int addr;                 /* Address of top of loop */
93424   int iReg;                 /* First register in set passed to OP_VUpdate */
93425   sqlite3 *db = pParse->db; /* Database connection */
93426   const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
93427   SelectDest dest;
93428
93429   /* Construct the SELECT statement that will find the new values for
93430   ** all updated rows. 
93431   */
93432   pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, "_rowid_"));
93433   if( pRowid ){
93434     pEList = sqlite3ExprListAppend(pParse, pEList,
93435                                    sqlite3ExprDup(db, pRowid, 0));
93436   }
93437   assert( pTab->iPKey<0 );
93438   for(i=0; i<pTab->nCol; i++){
93439     if( aXRef[i]>=0 ){
93440       pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);
93441     }else{
93442       pExpr = sqlite3Expr(db, TK_ID, pTab->aCol[i].zName);
93443     }
93444     pEList = sqlite3ExprListAppend(pParse, pEList, pExpr);
93445   }
93446   pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
93447   
93448   /* Create the ephemeral table into which the update results will
93449   ** be stored.
93450   */
93451   assert( v );
93452   ephemTab = pParse->nTab++;
93453   sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
93454   sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
93455
93456   /* fill the ephemeral table 
93457   */
93458   sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
93459   sqlite3Select(pParse, pSelect, &dest);
93460
93461   /* Generate code to scan the ephemeral table and call VUpdate. */
93462   iReg = ++pParse->nMem;
93463   pParse->nMem += pTab->nCol+1;
93464   addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0);
93465   sqlite3VdbeAddOp3(v, OP_Column,  ephemTab, 0, iReg);
93466   sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
93467   for(i=0; i<pTab->nCol; i++){
93468     sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
93469   }
93470   sqlite3VtabMakeWritable(pParse, pTab);
93471   sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);
93472   sqlite3MayAbort(pParse);
93473   sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1);
93474   sqlite3VdbeJumpHere(v, addr);
93475   sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
93476
93477   /* Cleanup */
93478   sqlite3SelectDelete(db, pSelect);  
93479 }
93480 #endif /* SQLITE_OMIT_VIRTUALTABLE */
93481
93482 /************** End of update.c **********************************************/
93483 /************** Begin file vacuum.c ******************************************/
93484 /*
93485 ** 2003 April 6
93486 **
93487 ** The author disclaims copyright to this source code.  In place of
93488 ** a legal notice, here is a blessing:
93489 **
93490 **    May you do good and not evil.
93491 **    May you find forgiveness for yourself and forgive others.
93492 **    May you share freely, never taking more than you give.
93493 **
93494 *************************************************************************
93495 ** This file contains code used to implement the VACUUM command.
93496 **
93497 ** Most of the code in this file may be omitted by defining the
93498 ** SQLITE_OMIT_VACUUM macro.
93499 */
93500
93501 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
93502 /*
93503 ** Finalize a prepared statement.  If there was an error, store the
93504 ** text of the error message in *pzErrMsg.  Return the result code.
93505 */
93506 static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
93507   int rc;
93508   rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
93509   if( rc ){
93510     sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
93511   }
93512   return rc;
93513 }
93514
93515 /*
93516 ** Execute zSql on database db. Return an error code.
93517 */
93518 static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
93519   sqlite3_stmt *pStmt;
93520   VVA_ONLY( int rc; )
93521   if( !zSql ){
93522     return SQLITE_NOMEM;
93523   }
93524   if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
93525     sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
93526     return sqlite3_errcode(db);
93527   }
93528   VVA_ONLY( rc = ) sqlite3_step(pStmt);
93529   assert( rc!=SQLITE_ROW );
93530   return vacuumFinalize(db, pStmt, pzErrMsg);
93531 }
93532
93533 /*
93534 ** Execute zSql on database db. The statement returns exactly
93535 ** one column. Execute this as SQL on the same database.
93536 */
93537 static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
93538   sqlite3_stmt *pStmt;
93539   int rc;
93540
93541   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
93542   if( rc!=SQLITE_OK ) return rc;
93543
93544   while( SQLITE_ROW==sqlite3_step(pStmt) ){
93545     rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
93546     if( rc!=SQLITE_OK ){
93547       vacuumFinalize(db, pStmt, pzErrMsg);
93548       return rc;
93549     }
93550   }
93551
93552   return vacuumFinalize(db, pStmt, pzErrMsg);
93553 }
93554
93555 /*
93556 ** The non-standard VACUUM command is used to clean up the database,
93557 ** collapse free space, etc.  It is modelled after the VACUUM command
93558 ** in PostgreSQL.
93559 **
93560 ** In version 1.0.x of SQLite, the VACUUM command would call
93561 ** gdbm_reorganize() on all the database tables.  But beginning
93562 ** with 2.0.0, SQLite no longer uses GDBM so this command has
93563 ** become a no-op.
93564 */
93565 SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
93566   Vdbe *v = sqlite3GetVdbe(pParse);
93567   if( v ){
93568     sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
93569   }
93570   return;
93571 }
93572
93573 /*
93574 ** This routine implements the OP_Vacuum opcode of the VDBE.
93575 */
93576 SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
93577   int rc = SQLITE_OK;     /* Return code from service routines */
93578   Btree *pMain;           /* The database being vacuumed */
93579   Btree *pTemp;           /* The temporary database we vacuum into */
93580   char *zSql = 0;         /* SQL statements */
93581   int saved_flags;        /* Saved value of the db->flags */
93582   int saved_nChange;      /* Saved value of db->nChange */
93583   int saved_nTotalChange; /* Saved value of db->nTotalChange */
93584   void (*saved_xTrace)(void*,const char*);  /* Saved db->xTrace */
93585   Db *pDb = 0;            /* Database to detach at end of vacuum */
93586   int isMemDb;            /* True if vacuuming a :memory: database */
93587   int nRes;               /* Bytes of reserved space at the end of each page */
93588   int nDb;                /* Number of attached databases */
93589
93590   if( !db->autoCommit ){
93591     sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
93592     return SQLITE_ERROR;
93593   }
93594   if( db->activeVdbeCnt>1 ){
93595     sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
93596     return SQLITE_ERROR;
93597   }
93598
93599   /* Save the current value of the database flags so that it can be 
93600   ** restored before returning. Then set the writable-schema flag, and
93601   ** disable CHECK and foreign key constraints.  */
93602   saved_flags = db->flags;
93603   saved_nChange = db->nChange;
93604   saved_nTotalChange = db->nTotalChange;
93605   saved_xTrace = db->xTrace;
93606   db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
93607   db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
93608   db->xTrace = 0;
93609
93610   pMain = db->aDb[0].pBt;
93611   isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
93612
93613   /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
93614   ** can be set to 'off' for this file, as it is not recovered if a crash
93615   ** occurs anyway. The integrity of the database is maintained by a
93616   ** (possibly synchronous) transaction opened on the main database before
93617   ** sqlite3BtreeCopyFile() is called.
93618   **
93619   ** An optimisation would be to use a non-journaled pager.
93620   ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
93621   ** that actually made the VACUUM run slower.  Very little journalling
93622   ** actually occurs when doing a vacuum since the vacuum_db is initially
93623   ** empty.  Only the journal header is written.  Apparently it takes more
93624   ** time to parse and run the PRAGMA to turn journalling off than it does
93625   ** to write the journal header file.
93626   */
93627   nDb = db->nDb;
93628   if( sqlite3TempInMemory(db) ){
93629     zSql = "ATTACH ':memory:' AS vacuum_db;";
93630   }else{
93631     zSql = "ATTACH '' AS vacuum_db;";
93632   }
93633   rc = execSql(db, pzErrMsg, zSql);
93634   if( db->nDb>nDb ){
93635     pDb = &db->aDb[db->nDb-1];
93636     assert( strcmp(pDb->zName,"vacuum_db")==0 );
93637   }
93638   if( rc!=SQLITE_OK ) goto end_of_vacuum;
93639   pTemp = db->aDb[db->nDb-1].pBt;
93640
93641   /* The call to execSql() to attach the temp database has left the file
93642   ** locked (as there was more than one active statement when the transaction
93643   ** to read the schema was concluded. Unlock it here so that this doesn't
93644   ** cause problems for the call to BtreeSetPageSize() below.  */
93645   sqlite3BtreeCommit(pTemp);
93646
93647   nRes = sqlite3BtreeGetReserve(pMain);
93648
93649   /* A VACUUM cannot change the pagesize of an encrypted database. */
93650 #ifdef SQLITE_HAS_CODEC
93651   if( db->nextPagesize ){
93652     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
93653     int nKey;
93654     char *zKey;
93655     sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
93656     if( nKey ) db->nextPagesize = 0;
93657   }
93658 #endif
93659
93660   /* Do not attempt to change the page size for a WAL database */
93661   if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
93662                                                ==PAGER_JOURNALMODE_WAL ){
93663     db->nextPagesize = 0;
93664   }
93665
93666   if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
93667    || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
93668    || NEVER(db->mallocFailed)
93669   ){
93670     rc = SQLITE_NOMEM;
93671     goto end_of_vacuum;
93672   }
93673   rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
93674   if( rc!=SQLITE_OK ){
93675     goto end_of_vacuum;
93676   }
93677
93678 #ifndef SQLITE_OMIT_AUTOVACUUM
93679   sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
93680                                            sqlite3BtreeGetAutoVacuum(pMain));
93681 #endif
93682
93683   /* Begin a transaction */
93684   rc = execSql(db, pzErrMsg, "BEGIN EXCLUSIVE;");
93685   if( rc!=SQLITE_OK ) goto end_of_vacuum;
93686
93687   /* Query the schema of the main database. Create a mirror schema
93688   ** in the temporary database.
93689   */
93690   rc = execExecSql(db, pzErrMsg,
93691       "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
93692       "  FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
93693       "   AND rootpage>0"
93694   );
93695   if( rc!=SQLITE_OK ) goto end_of_vacuum;
93696   rc = execExecSql(db, pzErrMsg,
93697       "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
93698       "  FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
93699   if( rc!=SQLITE_OK ) goto end_of_vacuum;
93700   rc = execExecSql(db, pzErrMsg,
93701       "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
93702       "  FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
93703   if( rc!=SQLITE_OK ) goto end_of_vacuum;
93704
93705   /* Loop through the tables in the main database. For each, do
93706   ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
93707   ** the contents to the temporary database.
93708   */
93709   rc = execExecSql(db, pzErrMsg,
93710       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
93711       "|| ' SELECT * FROM main.' || quote(name) || ';'"
93712       "FROM main.sqlite_master "
93713       "WHERE type = 'table' AND name!='sqlite_sequence' "
93714       "  AND rootpage>0"
93715   );
93716   if( rc!=SQLITE_OK ) goto end_of_vacuum;
93717
93718   /* Copy over the sequence table
93719   */
93720   rc = execExecSql(db, pzErrMsg,
93721       "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
93722       "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
93723   );
93724   if( rc!=SQLITE_OK ) goto end_of_vacuum;
93725   rc = execExecSql(db, pzErrMsg,
93726       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
93727       "|| ' SELECT * FROM main.' || quote(name) || ';' "
93728       "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
93729   );
93730   if( rc!=SQLITE_OK ) goto end_of_vacuum;
93731
93732
93733   /* Copy the triggers, views, and virtual tables from the main database
93734   ** over to the temporary database.  None of these objects has any
93735   ** associated storage, so all we have to do is copy their entries
93736   ** from the SQLITE_MASTER table.
93737   */
93738   rc = execSql(db, pzErrMsg,
93739       "INSERT INTO vacuum_db.sqlite_master "
93740       "  SELECT type, name, tbl_name, rootpage, sql"
93741       "    FROM main.sqlite_master"
93742       "   WHERE type='view' OR type='trigger'"
93743       "      OR (type='table' AND rootpage=0)"
93744   );
93745   if( rc ) goto end_of_vacuum;
93746
93747   /* At this point, unless the main db was completely empty, there is now a
93748   ** transaction open on the vacuum database, but not on the main database.
93749   ** Open a btree level transaction on the main database. This allows a
93750   ** call to sqlite3BtreeCopyFile(). The main database btree level
93751   ** transaction is then committed, so the SQL level never knows it was
93752   ** opened for writing. This way, the SQL transaction used to create the
93753   ** temporary database never needs to be committed.
93754   */
93755   {
93756     u32 meta;
93757     int i;
93758
93759     /* This array determines which meta meta values are preserved in the
93760     ** vacuum.  Even entries are the meta value number and odd entries
93761     ** are an increment to apply to the meta value after the vacuum.
93762     ** The increment is used to increase the schema cookie so that other
93763     ** connections to the same database will know to reread the schema.
93764     */
93765     static const unsigned char aCopy[] = {
93766        BTREE_SCHEMA_VERSION,     1,  /* Add one to the old schema cookie */
93767        BTREE_DEFAULT_CACHE_SIZE, 0,  /* Preserve the default page cache size */
93768        BTREE_TEXT_ENCODING,      0,  /* Preserve the text encoding */
93769        BTREE_USER_VERSION,       0,  /* Preserve the user version */
93770     };
93771
93772     assert( 1==sqlite3BtreeIsInTrans(pTemp) );
93773     assert( 1==sqlite3BtreeIsInTrans(pMain) );
93774
93775     /* Copy Btree meta values */
93776     for(i=0; i<ArraySize(aCopy); i+=2){
93777       /* GetMeta() and UpdateMeta() cannot fail in this context because
93778       ** we already have page 1 loaded into cache and marked dirty. */
93779       sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
93780       rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
93781       if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
93782     }
93783
93784     rc = sqlite3BtreeCopyFile(pMain, pTemp);
93785     if( rc!=SQLITE_OK ) goto end_of_vacuum;
93786     rc = sqlite3BtreeCommit(pTemp);
93787     if( rc!=SQLITE_OK ) goto end_of_vacuum;
93788 #ifndef SQLITE_OMIT_AUTOVACUUM
93789     sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
93790 #endif
93791   }
93792
93793   assert( rc==SQLITE_OK );
93794   rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
93795
93796 end_of_vacuum:
93797   /* Restore the original value of db->flags */
93798   db->flags = saved_flags;
93799   db->nChange = saved_nChange;
93800   db->nTotalChange = saved_nTotalChange;
93801   db->xTrace = saved_xTrace;
93802   sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
93803
93804   /* Currently there is an SQL level transaction open on the vacuum
93805   ** database. No locks are held on any other files (since the main file
93806   ** was committed at the btree level). So it safe to end the transaction
93807   ** by manually setting the autoCommit flag to true and detaching the
93808   ** vacuum database. The vacuum_db journal file is deleted when the pager
93809   ** is closed by the DETACH.
93810   */
93811   db->autoCommit = 1;
93812
93813   if( pDb ){
93814     sqlite3BtreeClose(pDb->pBt);
93815     pDb->pBt = 0;
93816     pDb->pSchema = 0;
93817   }
93818
93819   sqlite3ResetInternalSchema(db, 0);
93820
93821   return rc;
93822 }
93823 #endif  /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
93824
93825 /************** End of vacuum.c **********************************************/
93826 /************** Begin file vtab.c ********************************************/
93827 /*
93828 ** 2006 June 10
93829 **
93830 ** The author disclaims copyright to this source code.  In place of
93831 ** a legal notice, here is a blessing:
93832 **
93833 **    May you do good and not evil.
93834 **    May you find forgiveness for yourself and forgive others.
93835 **    May you share freely, never taking more than you give.
93836 **
93837 *************************************************************************
93838 ** This file contains code used to help implement virtual tables.
93839 */
93840 #ifndef SQLITE_OMIT_VIRTUALTABLE
93841
93842 /*
93843 ** The actual function that does the work of creating a new module.
93844 ** This function implements the sqlite3_create_module() and
93845 ** sqlite3_create_module_v2() interfaces.
93846 */
93847 static int createModule(
93848   sqlite3 *db,                    /* Database in which module is registered */
93849   const char *zName,              /* Name assigned to this module */
93850   const sqlite3_module *pModule,  /* The definition of the module */
93851   void *pAux,                     /* Context pointer for xCreate/xConnect */
93852   void (*xDestroy)(void *)        /* Module destructor function */
93853 ){
93854   int rc, nName;
93855   Module *pMod;
93856
93857   sqlite3_mutex_enter(db->mutex);
93858   nName = sqlite3Strlen30(zName);
93859   pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
93860   if( pMod ){
93861     Module *pDel;
93862     char *zCopy = (char *)(&pMod[1]);
93863     memcpy(zCopy, zName, nName+1);
93864     pMod->zName = zCopy;
93865     pMod->pModule = pModule;
93866     pMod->pAux = pAux;
93867     pMod->xDestroy = xDestroy;
93868     pDel = (Module *)sqlite3HashInsert(&db->aModule, zCopy, nName, (void*)pMod);
93869     if( pDel && pDel->xDestroy ){
93870       pDel->xDestroy(pDel->pAux);
93871     }
93872     sqlite3DbFree(db, pDel);
93873     if( pDel==pMod ){
93874       db->mallocFailed = 1;
93875     }
93876     sqlite3ResetInternalSchema(db, 0);
93877   }else if( xDestroy ){
93878     xDestroy(pAux);
93879   }
93880   rc = sqlite3ApiExit(db, SQLITE_OK);
93881   sqlite3_mutex_leave(db->mutex);
93882   return rc;
93883 }
93884
93885
93886 /*
93887 ** External API function used to create a new virtual-table module.
93888 */
93889 SQLITE_API int sqlite3_create_module(
93890   sqlite3 *db,                    /* Database in which module is registered */
93891   const char *zName,              /* Name assigned to this module */
93892   const sqlite3_module *pModule,  /* The definition of the module */
93893   void *pAux                      /* Context pointer for xCreate/xConnect */
93894 ){
93895   return createModule(db, zName, pModule, pAux, 0);
93896 }
93897
93898 /*
93899 ** External API function used to create a new virtual-table module.
93900 */
93901 SQLITE_API int sqlite3_create_module_v2(
93902   sqlite3 *db,                    /* Database in which module is registered */
93903   const char *zName,              /* Name assigned to this module */
93904   const sqlite3_module *pModule,  /* The definition of the module */
93905   void *pAux,                     /* Context pointer for xCreate/xConnect */
93906   void (*xDestroy)(void *)        /* Module destructor function */
93907 ){
93908   return createModule(db, zName, pModule, pAux, xDestroy);
93909 }
93910
93911 /*
93912 ** Lock the virtual table so that it cannot be disconnected.
93913 ** Locks nest.  Every lock should have a corresponding unlock.
93914 ** If an unlock is omitted, resources leaks will occur.  
93915 **
93916 ** If a disconnect is attempted while a virtual table is locked,
93917 ** the disconnect is deferred until all locks have been removed.
93918 */
93919 SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
93920   pVTab->nRef++;
93921 }
93922
93923
93924 /*
93925 ** pTab is a pointer to a Table structure representing a virtual-table.
93926 ** Return a pointer to the VTable object used by connection db to access 
93927 ** this virtual-table, if one has been created, or NULL otherwise.
93928 */
93929 SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
93930   VTable *pVtab;
93931   assert( IsVirtual(pTab) );
93932   for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
93933   return pVtab;
93934 }
93935
93936 /*
93937 ** Decrement the ref-count on a virtual table object. When the ref-count
93938 ** reaches zero, call the xDisconnect() method to delete the object.
93939 */
93940 SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
93941   sqlite3 *db = pVTab->db;
93942
93943   assert( db );
93944   assert( pVTab->nRef>0 );
93945   assert( sqlite3SafetyCheckOk(db) );
93946
93947   pVTab->nRef--;
93948   if( pVTab->nRef==0 ){
93949     sqlite3_vtab *p = pVTab->pVtab;
93950     if( p ){
93951       p->pModule->xDisconnect(p);
93952     }
93953     sqlite3DbFree(db, pVTab);
93954   }
93955 }
93956
93957 /*
93958 ** Table p is a virtual table. This function moves all elements in the
93959 ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
93960 ** database connections to be disconnected at the next opportunity. 
93961 ** Except, if argument db is not NULL, then the entry associated with
93962 ** connection db is left in the p->pVTable list.
93963 */
93964 static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
93965   VTable *pRet = 0;
93966   VTable *pVTable = p->pVTable;
93967   p->pVTable = 0;
93968
93969   /* Assert that the mutex (if any) associated with the BtShared database 
93970   ** that contains table p is held by the caller. See header comments 
93971   ** above function sqlite3VtabUnlockList() for an explanation of why
93972   ** this makes it safe to access the sqlite3.pDisconnect list of any
93973   ** database connection that may have an entry in the p->pVTable list.  */
93974   assert( db==0 ||
93975     sqlite3BtreeHoldsMutex(db->aDb[sqlite3SchemaToIndex(db, p->pSchema)].pBt) 
93976   );
93977
93978   while( pVTable ){
93979     sqlite3 *db2 = pVTable->db;
93980     VTable *pNext = pVTable->pNext;
93981     assert( db2 );
93982     if( db2==db ){
93983       pRet = pVTable;
93984       p->pVTable = pRet;
93985       pRet->pNext = 0;
93986     }else{
93987       pVTable->pNext = db2->pDisconnect;
93988       db2->pDisconnect = pVTable;
93989     }
93990     pVTable = pNext;
93991   }
93992
93993   assert( !db || pRet );
93994   return pRet;
93995 }
93996
93997
93998 /*
93999 ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
94000 **
94001 ** This function may only be called when the mutexes associated with all
94002 ** shared b-tree databases opened using connection db are held by the 
94003 ** caller. This is done to protect the sqlite3.pDisconnect list. The
94004 ** sqlite3.pDisconnect list is accessed only as follows:
94005 **
94006 **   1) By this function. In this case, all BtShared mutexes and the mutex
94007 **      associated with the database handle itself must be held.
94008 **
94009 **   2) By function vtabDisconnectAll(), when it adds a VTable entry to
94010 **      the sqlite3.pDisconnect list. In this case either the BtShared mutex
94011 **      associated with the database the virtual table is stored in is held
94012 **      or, if the virtual table is stored in a non-sharable database, then
94013 **      the database handle mutex is held.
94014 **
94015 ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously 
94016 ** by multiple threads. It is thread-safe.
94017 */
94018 SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
94019   VTable *p = db->pDisconnect;
94020   db->pDisconnect = 0;
94021
94022   assert( sqlite3BtreeHoldsAllMutexes(db) );
94023   assert( sqlite3_mutex_held(db->mutex) );
94024
94025   if( p ){
94026     sqlite3ExpirePreparedStatements(db);
94027     do {
94028       VTable *pNext = p->pNext;
94029       sqlite3VtabUnlock(p);
94030       p = pNext;
94031     }while( p );
94032   }
94033 }
94034
94035 /*
94036 ** Clear any and all virtual-table information from the Table record.
94037 ** This routine is called, for example, just before deleting the Table
94038 ** record.
94039 **
94040 ** Since it is a virtual-table, the Table structure contains a pointer
94041 ** to the head of a linked list of VTable structures. Each VTable 
94042 ** structure is associated with a single sqlite3* user of the schema.
94043 ** The reference count of the VTable structure associated with database 
94044 ** connection db is decremented immediately (which may lead to the 
94045 ** structure being xDisconnected and free). Any other VTable structures
94046 ** in the list are moved to the sqlite3.pDisconnect list of the associated 
94047 ** database connection.
94048 */
94049 SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
94050   if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
94051   if( p->azModuleArg ){
94052     int i;
94053     for(i=0; i<p->nModuleArg; i++){
94054       sqlite3DbFree(db, p->azModuleArg[i]);
94055     }
94056     sqlite3DbFree(db, p->azModuleArg);
94057   }
94058 }
94059
94060 /*
94061 ** Add a new module argument to pTable->azModuleArg[].
94062 ** The string is not copied - the pointer is stored.  The
94063 ** string will be freed automatically when the table is
94064 ** deleted.
94065 */
94066 static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
94067   int i = pTable->nModuleArg++;
94068   int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
94069   char **azModuleArg;
94070   azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
94071   if( azModuleArg==0 ){
94072     int j;
94073     for(j=0; j<i; j++){
94074       sqlite3DbFree(db, pTable->azModuleArg[j]);
94075     }
94076     sqlite3DbFree(db, zArg);
94077     sqlite3DbFree(db, pTable->azModuleArg);
94078     pTable->nModuleArg = 0;
94079   }else{
94080     azModuleArg[i] = zArg;
94081     azModuleArg[i+1] = 0;
94082   }
94083   pTable->azModuleArg = azModuleArg;
94084 }
94085
94086 /*
94087 ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
94088 ** statement.  The module name has been parsed, but the optional list
94089 ** of parameters that follow the module name are still pending.
94090 */
94091 SQLITE_PRIVATE void sqlite3VtabBeginParse(
94092   Parse *pParse,        /* Parsing context */
94093   Token *pName1,        /* Name of new table, or database name */
94094   Token *pName2,        /* Name of new table or NULL */
94095   Token *pModuleName    /* Name of the module for the virtual table */
94096 ){
94097   int iDb;              /* The database the table is being created in */
94098   Table *pTable;        /* The new virtual table */
94099   sqlite3 *db;          /* Database connection */
94100
94101   sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, 0);
94102   pTable = pParse->pNewTable;
94103   if( pTable==0 ) return;
94104   assert( 0==pTable->pIndex );
94105
94106   db = pParse->db;
94107   iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
94108   assert( iDb>=0 );
94109
94110   pTable->tabFlags |= TF_Virtual;
94111   pTable->nModuleArg = 0;
94112   addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
94113   addModuleArgument(db, pTable, sqlite3DbStrDup(db, db->aDb[iDb].zName));
94114   addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
94115   pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z);
94116
94117 #ifndef SQLITE_OMIT_AUTHORIZATION
94118   /* Creating a virtual table invokes the authorization callback twice.
94119   ** The first invocation, to obtain permission to INSERT a row into the
94120   ** sqlite_master table, has already been made by sqlite3StartTable().
94121   ** The second call, to obtain permission to create the table, is made now.
94122   */
94123   if( pTable->azModuleArg ){
94124     sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName, 
94125             pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
94126   }
94127 #endif
94128 }
94129
94130 /*
94131 ** This routine takes the module argument that has been accumulating
94132 ** in pParse->zArg[] and appends it to the list of arguments on the
94133 ** virtual table currently under construction in pParse->pTable.
94134 */
94135 static void addArgumentToVtab(Parse *pParse){
94136   if( pParse->sArg.z && ALWAYS(pParse->pNewTable) ){
94137     const char *z = (const char*)pParse->sArg.z;
94138     int n = pParse->sArg.n;
94139     sqlite3 *db = pParse->db;
94140     addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
94141   }
94142 }
94143
94144 /*
94145 ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
94146 ** has been completely parsed.
94147 */
94148 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
94149   Table *pTab = pParse->pNewTable;  /* The table being constructed */
94150   sqlite3 *db = pParse->db;         /* The database connection */
94151
94152   if( pTab==0 ) return;
94153   addArgumentToVtab(pParse);
94154   pParse->sArg.z = 0;
94155   if( pTab->nModuleArg<1 ) return;
94156   
94157   /* If the CREATE VIRTUAL TABLE statement is being entered for the
94158   ** first time (in other words if the virtual table is actually being
94159   ** created now instead of just being read out of sqlite_master) then
94160   ** do additional initialization work and store the statement text
94161   ** in the sqlite_master table.
94162   */
94163   if( !db->init.busy ){
94164     char *zStmt;
94165     char *zWhere;
94166     int iDb;
94167     Vdbe *v;
94168
94169     /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
94170     if( pEnd ){
94171       pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
94172     }
94173     zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
94174
94175     /* A slot for the record has already been allocated in the 
94176     ** SQLITE_MASTER table.  We just need to update that slot with all
94177     ** the information we've collected.  
94178     **
94179     ** The VM register number pParse->regRowid holds the rowid of an
94180     ** entry in the sqlite_master table tht was created for this vtab
94181     ** by sqlite3StartTable().
94182     */
94183     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
94184     sqlite3NestedParse(pParse,
94185       "UPDATE %Q.%s "
94186          "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
94187        "WHERE rowid=#%d",
94188       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
94189       pTab->zName,
94190       pTab->zName,
94191       zStmt,
94192       pParse->regRowid
94193     );
94194     sqlite3DbFree(db, zStmt);
94195     v = sqlite3GetVdbe(pParse);
94196     sqlite3ChangeCookie(pParse, iDb);
94197
94198     sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
94199     zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
94200     sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 1, 0, zWhere, P4_DYNAMIC);
94201     sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0, 
94202                          pTab->zName, sqlite3Strlen30(pTab->zName) + 1);
94203   }
94204
94205   /* If we are rereading the sqlite_master table create the in-memory
94206   ** record of the table. The xConnect() method is not called until
94207   ** the first time the virtual table is used in an SQL statement. This
94208   ** allows a schema that contains virtual tables to be loaded before
94209   ** the required virtual table implementations are registered.  */
94210   else {
94211     Table *pOld;
94212     Schema *pSchema = pTab->pSchema;
94213     const char *zName = pTab->zName;
94214     int nName = sqlite3Strlen30(zName);
94215     pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
94216     if( pOld ){
94217       db->mallocFailed = 1;
94218       assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
94219       return;
94220     }
94221     pParse->pNewTable = 0;
94222   }
94223 }
94224
94225 /*
94226 ** The parser calls this routine when it sees the first token
94227 ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
94228 */
94229 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
94230   addArgumentToVtab(pParse);
94231   pParse->sArg.z = 0;
94232   pParse->sArg.n = 0;
94233 }
94234
94235 /*
94236 ** The parser calls this routine for each token after the first token
94237 ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
94238 */
94239 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
94240   Token *pArg = &pParse->sArg;
94241   if( pArg->z==0 ){
94242     pArg->z = p->z;
94243     pArg->n = p->n;
94244   }else{
94245     assert(pArg->z < p->z);
94246     pArg->n = (int)(&p->z[p->n] - pArg->z);
94247   }
94248 }
94249
94250 /*
94251 ** Invoke a virtual table constructor (either xCreate or xConnect). The
94252 ** pointer to the function to invoke is passed as the fourth parameter
94253 ** to this procedure.
94254 */
94255 static int vtabCallConstructor(
94256   sqlite3 *db, 
94257   Table *pTab,
94258   Module *pMod,
94259   int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
94260   char **pzErr
94261 ){
94262   VTable *pVTable;
94263   int rc;
94264   const char *const*azArg = (const char *const*)pTab->azModuleArg;
94265   int nArg = pTab->nModuleArg;
94266   char *zErr = 0;
94267   char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
94268
94269   if( !zModuleName ){
94270     return SQLITE_NOMEM;
94271   }
94272
94273   pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
94274   if( !pVTable ){
94275     sqlite3DbFree(db, zModuleName);
94276     return SQLITE_NOMEM;
94277   }
94278   pVTable->db = db;
94279   pVTable->pMod = pMod;
94280
94281   assert( !db->pVTab );
94282   assert( xConstruct );
94283   db->pVTab = pTab;
94284
94285   /* Invoke the virtual table constructor */
94286   rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
94287   if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
94288
94289   if( SQLITE_OK!=rc ){
94290     if( zErr==0 ){
94291       *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
94292     }else {
94293       *pzErr = sqlite3MPrintf(db, "%s", zErr);
94294       sqlite3_free(zErr);
94295     }
94296     sqlite3DbFree(db, pVTable);
94297   }else if( ALWAYS(pVTable->pVtab) ){
94298     /* Justification of ALWAYS():  A correct vtab constructor must allocate
94299     ** the sqlite3_vtab object if successful.  */
94300     pVTable->pVtab->pModule = pMod->pModule;
94301     pVTable->nRef = 1;
94302     if( db->pVTab ){
94303       const char *zFormat = "vtable constructor did not declare schema: %s";
94304       *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
94305       sqlite3VtabUnlock(pVTable);
94306       rc = SQLITE_ERROR;
94307     }else{
94308       int iCol;
94309       /* If everything went according to plan, link the new VTable structure
94310       ** into the linked list headed by pTab->pVTable. Then loop through the 
94311       ** columns of the table to see if any of them contain the token "hidden".
94312       ** If so, set the Column.isHidden flag and remove the token from
94313       ** the type string.  */
94314       pVTable->pNext = pTab->pVTable;
94315       pTab->pVTable = pVTable;
94316
94317       for(iCol=0; iCol<pTab->nCol; iCol++){
94318         char *zType = pTab->aCol[iCol].zType;
94319         int nType;
94320         int i = 0;
94321         if( !zType ) continue;
94322         nType = sqlite3Strlen30(zType);
94323         if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
94324           for(i=0; i<nType; i++){
94325             if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
94326              && (zType[i+7]=='\0' || zType[i+7]==' ')
94327             ){
94328               i++;
94329               break;
94330             }
94331           }
94332         }
94333         if( i<nType ){
94334           int j;
94335           int nDel = 6 + (zType[i+6] ? 1 : 0);
94336           for(j=i; (j+nDel)<=nType; j++){
94337             zType[j] = zType[j+nDel];
94338           }
94339           if( zType[i]=='\0' && i>0 ){
94340             assert(zType[i-1]==' ');
94341             zType[i-1] = '\0';
94342           }
94343           pTab->aCol[iCol].isHidden = 1;
94344         }
94345       }
94346     }
94347   }
94348
94349   sqlite3DbFree(db, zModuleName);
94350   db->pVTab = 0;
94351   return rc;
94352 }
94353
94354 /*
94355 ** This function is invoked by the parser to call the xConnect() method
94356 ** of the virtual table pTab. If an error occurs, an error code is returned 
94357 ** and an error left in pParse.
94358 **
94359 ** This call is a no-op if table pTab is not a virtual table.
94360 */
94361 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
94362   sqlite3 *db = pParse->db;
94363   const char *zMod;
94364   Module *pMod;
94365   int rc;
94366
94367   assert( pTab );
94368   if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
94369     return SQLITE_OK;
94370   }
94371
94372   /* Locate the required virtual table module */
94373   zMod = pTab->azModuleArg[0];
94374   pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
94375
94376   if( !pMod ){
94377     const char *zModule = pTab->azModuleArg[0];
94378     sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
94379     rc = SQLITE_ERROR;
94380   }else{
94381     char *zErr = 0;
94382     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
94383     if( rc!=SQLITE_OK ){
94384       sqlite3ErrorMsg(pParse, "%s", zErr);
94385     }
94386     sqlite3DbFree(db, zErr);
94387   }
94388
94389   return rc;
94390 }
94391
94392 /*
94393 ** Add the virtual table pVTab to the array sqlite3.aVTrans[].
94394 */
94395 static int addToVTrans(sqlite3 *db, VTable *pVTab){
94396   const int ARRAY_INCR = 5;
94397
94398   /* Grow the sqlite3.aVTrans array if required */
94399   if( (db->nVTrans%ARRAY_INCR)==0 ){
94400     VTable **aVTrans;
94401     int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
94402     aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
94403     if( !aVTrans ){
94404       return SQLITE_NOMEM;
94405     }
94406     memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
94407     db->aVTrans = aVTrans;
94408   }
94409
94410   /* Add pVtab to the end of sqlite3.aVTrans */
94411   db->aVTrans[db->nVTrans++] = pVTab;
94412   sqlite3VtabLock(pVTab);
94413   return SQLITE_OK;
94414 }
94415
94416 /*
94417 ** This function is invoked by the vdbe to call the xCreate method
94418 ** of the virtual table named zTab in database iDb. 
94419 **
94420 ** If an error occurs, *pzErr is set to point an an English language
94421 ** description of the error and an SQLITE_XXX error code is returned.
94422 ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
94423 */
94424 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
94425   int rc = SQLITE_OK;
94426   Table *pTab;
94427   Module *pMod;
94428   const char *zMod;
94429
94430   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
94431   assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
94432
94433   /* Locate the required virtual table module */
94434   zMod = pTab->azModuleArg[0];
94435   pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
94436
94437   /* If the module has been registered and includes a Create method, 
94438   ** invoke it now. If the module has not been registered, return an 
94439   ** error. Otherwise, do nothing.
94440   */
94441   if( !pMod ){
94442     *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
94443     rc = SQLITE_ERROR;
94444   }else{
94445     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
94446   }
94447
94448   /* Justification of ALWAYS():  The xConstructor method is required to
94449   ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
94450   if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
94451       rc = addToVTrans(db, sqlite3GetVTable(db, pTab));
94452   }
94453
94454   return rc;
94455 }
94456
94457 /*
94458 ** This function is used to set the schema of a virtual table.  It is only
94459 ** valid to call this function from within the xCreate() or xConnect() of a
94460 ** virtual table module.
94461 */
94462 SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
94463   Parse *pParse;
94464
94465   int rc = SQLITE_OK;
94466   Table *pTab;
94467   char *zErr = 0;
94468
94469   sqlite3_mutex_enter(db->mutex);
94470   pTab = db->pVTab;
94471   if( !pTab ){
94472     sqlite3Error(db, SQLITE_MISUSE, 0);
94473     sqlite3_mutex_leave(db->mutex);
94474     return SQLITE_MISUSE_BKPT;
94475   }
94476   assert( (pTab->tabFlags & TF_Virtual)!=0 );
94477
94478   pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
94479   if( pParse==0 ){
94480     rc = SQLITE_NOMEM;
94481   }else{
94482     pParse->declareVtab = 1;
94483     pParse->db = db;
94484     pParse->nQueryLoop = 1;
94485   
94486     if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr) 
94487      && pParse->pNewTable
94488      && !db->mallocFailed
94489      && !pParse->pNewTable->pSelect
94490      && (pParse->pNewTable->tabFlags & TF_Virtual)==0
94491     ){
94492       if( !pTab->aCol ){
94493         pTab->aCol = pParse->pNewTable->aCol;
94494         pTab->nCol = pParse->pNewTable->nCol;
94495         pParse->pNewTable->nCol = 0;
94496         pParse->pNewTable->aCol = 0;
94497       }
94498       db->pVTab = 0;
94499     }else{
94500       sqlite3Error(db, SQLITE_ERROR, zErr);
94501       sqlite3DbFree(db, zErr);
94502       rc = SQLITE_ERROR;
94503     }
94504     pParse->declareVtab = 0;
94505   
94506     if( pParse->pVdbe ){
94507       sqlite3VdbeFinalize(pParse->pVdbe);
94508     }
94509     sqlite3DeleteTable(db, pParse->pNewTable);
94510     sqlite3StackFree(db, pParse);
94511   }
94512
94513   assert( (rc&0xff)==rc );
94514   rc = sqlite3ApiExit(db, rc);
94515   sqlite3_mutex_leave(db->mutex);
94516   return rc;
94517 }
94518
94519 /*
94520 ** This function is invoked by the vdbe to call the xDestroy method
94521 ** of the virtual table named zTab in database iDb. This occurs
94522 ** when a DROP TABLE is mentioned.
94523 **
94524 ** This call is a no-op if zTab is not a virtual table.
94525 */
94526 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
94527   int rc = SQLITE_OK;
94528   Table *pTab;
94529
94530   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
94531   if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
94532     VTable *p = vtabDisconnectAll(db, pTab);
94533
94534     assert( rc==SQLITE_OK );
94535     rc = p->pMod->pModule->xDestroy(p->pVtab);
94536
94537     /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
94538     if( rc==SQLITE_OK ){
94539       assert( pTab->pVTable==p && p->pNext==0 );
94540       p->pVtab = 0;
94541       pTab->pVTable = 0;
94542       sqlite3VtabUnlock(p);
94543     }
94544   }
94545
94546   return rc;
94547 }
94548
94549 /*
94550 ** This function invokes either the xRollback or xCommit method
94551 ** of each of the virtual tables in the sqlite3.aVTrans array. The method
94552 ** called is identified by the second argument, "offset", which is
94553 ** the offset of the method to call in the sqlite3_module structure.
94554 **
94555 ** The array is cleared after invoking the callbacks. 
94556 */
94557 static void callFinaliser(sqlite3 *db, int offset){
94558   int i;
94559   if( db->aVTrans ){
94560     for(i=0; i<db->nVTrans; i++){
94561       VTable *pVTab = db->aVTrans[i];
94562       sqlite3_vtab *p = pVTab->pVtab;
94563       if( p ){
94564         int (*x)(sqlite3_vtab *);
94565         x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
94566         if( x ) x(p);
94567       }
94568       sqlite3VtabUnlock(pVTab);
94569     }
94570     sqlite3DbFree(db, db->aVTrans);
94571     db->nVTrans = 0;
94572     db->aVTrans = 0;
94573   }
94574 }
94575
94576 /*
94577 ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
94578 ** array. Return the error code for the first error that occurs, or
94579 ** SQLITE_OK if all xSync operations are successful.
94580 **
94581 ** Set *pzErrmsg to point to a buffer that should be released using 
94582 ** sqlite3DbFree() containing an error message, if one is available.
94583 */
94584 SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, char **pzErrmsg){
94585   int i;
94586   int rc = SQLITE_OK;
94587   VTable **aVTrans = db->aVTrans;
94588
94589   db->aVTrans = 0;
94590   for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
94591     int (*x)(sqlite3_vtab *);
94592     sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
94593     if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
94594       rc = x(pVtab);
94595       sqlite3DbFree(db, *pzErrmsg);
94596       *pzErrmsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
94597       sqlite3_free(pVtab->zErrMsg);
94598     }
94599   }
94600   db->aVTrans = aVTrans;
94601   return rc;
94602 }
94603
94604 /*
94605 ** Invoke the xRollback method of all virtual tables in the 
94606 ** sqlite3.aVTrans array. Then clear the array itself.
94607 */
94608 SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
94609   callFinaliser(db, offsetof(sqlite3_module,xRollback));
94610   return SQLITE_OK;
94611 }
94612
94613 /*
94614 ** Invoke the xCommit method of all virtual tables in the 
94615 ** sqlite3.aVTrans array. Then clear the array itself.
94616 */
94617 SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
94618   callFinaliser(db, offsetof(sqlite3_module,xCommit));
94619   return SQLITE_OK;
94620 }
94621
94622 /*
94623 ** If the virtual table pVtab supports the transaction interface
94624 ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
94625 ** not currently open, invoke the xBegin method now.
94626 **
94627 ** If the xBegin call is successful, place the sqlite3_vtab pointer
94628 ** in the sqlite3.aVTrans array.
94629 */
94630 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
94631   int rc = SQLITE_OK;
94632   const sqlite3_module *pModule;
94633
94634   /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
94635   ** than zero, then this function is being called from within a
94636   ** virtual module xSync() callback. It is illegal to write to 
94637   ** virtual module tables in this case, so return SQLITE_LOCKED.
94638   */
94639   if( sqlite3VtabInSync(db) ){
94640     return SQLITE_LOCKED;
94641   }
94642   if( !pVTab ){
94643     return SQLITE_OK;
94644   } 
94645   pModule = pVTab->pVtab->pModule;
94646
94647   if( pModule->xBegin ){
94648     int i;
94649
94650
94651     /* If pVtab is already in the aVTrans array, return early */
94652     for(i=0; i<db->nVTrans; i++){
94653       if( db->aVTrans[i]==pVTab ){
94654         return SQLITE_OK;
94655       }
94656     }
94657
94658     /* Invoke the xBegin method */
94659     rc = pModule->xBegin(pVTab->pVtab);
94660     if( rc==SQLITE_OK ){
94661       rc = addToVTrans(db, pVTab);
94662     }
94663   }
94664   return rc;
94665 }
94666
94667 /*
94668 ** The first parameter (pDef) is a function implementation.  The
94669 ** second parameter (pExpr) is the first argument to this function.
94670 ** If pExpr is a column in a virtual table, then let the virtual
94671 ** table implementation have an opportunity to overload the function.
94672 **
94673 ** This routine is used to allow virtual table implementations to
94674 ** overload MATCH, LIKE, GLOB, and REGEXP operators.
94675 **
94676 ** Return either the pDef argument (indicating no change) or a 
94677 ** new FuncDef structure that is marked as ephemeral using the
94678 ** SQLITE_FUNC_EPHEM flag.
94679 */
94680 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
94681   sqlite3 *db,    /* Database connection for reporting malloc problems */
94682   FuncDef *pDef,  /* Function to possibly overload */
94683   int nArg,       /* Number of arguments to the function */
94684   Expr *pExpr     /* First argument to the function */
94685 ){
94686   Table *pTab;
94687   sqlite3_vtab *pVtab;
94688   sqlite3_module *pMod;
94689   void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
94690   void *pArg = 0;
94691   FuncDef *pNew;
94692   int rc = 0;
94693   char *zLowerName;
94694   unsigned char *z;
94695
94696
94697   /* Check to see the left operand is a column in a virtual table */
94698   if( NEVER(pExpr==0) ) return pDef;
94699   if( pExpr->op!=TK_COLUMN ) return pDef;
94700   pTab = pExpr->pTab;
94701   if( NEVER(pTab==0) ) return pDef;
94702   if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
94703   pVtab = sqlite3GetVTable(db, pTab)->pVtab;
94704   assert( pVtab!=0 );
94705   assert( pVtab->pModule!=0 );
94706   pMod = (sqlite3_module *)pVtab->pModule;
94707   if( pMod->xFindFunction==0 ) return pDef;
94708  
94709   /* Call the xFindFunction method on the virtual table implementation
94710   ** to see if the implementation wants to overload this function 
94711   */
94712   zLowerName = sqlite3DbStrDup(db, pDef->zName);
94713   if( zLowerName ){
94714     for(z=(unsigned char*)zLowerName; *z; z++){
94715       *z = sqlite3UpperToLower[*z];
94716     }
94717     rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
94718     sqlite3DbFree(db, zLowerName);
94719   }
94720   if( rc==0 ){
94721     return pDef;
94722   }
94723
94724   /* Create a new ephemeral function definition for the overloaded
94725   ** function */
94726   pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
94727                              + sqlite3Strlen30(pDef->zName) + 1);
94728   if( pNew==0 ){
94729     return pDef;
94730   }
94731   *pNew = *pDef;
94732   pNew->zName = (char *)&pNew[1];
94733   memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
94734   pNew->xFunc = xFunc;
94735   pNew->pUserData = pArg;
94736   pNew->flags |= SQLITE_FUNC_EPHEM;
94737   return pNew;
94738 }
94739
94740 /*
94741 ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
94742 ** array so that an OP_VBegin will get generated for it.  Add pTab to the
94743 ** array if it is missing.  If pTab is already in the array, this routine
94744 ** is a no-op.
94745 */
94746 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
94747   Parse *pToplevel = sqlite3ParseToplevel(pParse);
94748   int i, n;
94749   Table **apVtabLock;
94750
94751   assert( IsVirtual(pTab) );
94752   for(i=0; i<pToplevel->nVtabLock; i++){
94753     if( pTab==pToplevel->apVtabLock[i] ) return;
94754   }
94755   n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
94756   apVtabLock = sqlite3_realloc(pToplevel->apVtabLock, n);
94757   if( apVtabLock ){
94758     pToplevel->apVtabLock = apVtabLock;
94759     pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
94760   }else{
94761     pToplevel->db->mallocFailed = 1;
94762   }
94763 }
94764
94765 #endif /* SQLITE_OMIT_VIRTUALTABLE */
94766
94767 /************** End of vtab.c ************************************************/
94768 /************** Begin file where.c *******************************************/
94769 /*
94770 ** 2001 September 15
94771 **
94772 ** The author disclaims copyright to this source code.  In place of
94773 ** a legal notice, here is a blessing:
94774 **
94775 **    May you do good and not evil.
94776 **    May you find forgiveness for yourself and forgive others.
94777 **    May you share freely, never taking more than you give.
94778 **
94779 *************************************************************************
94780 ** This module contains C code that generates VDBE code used to process
94781 ** the WHERE clause of SQL statements.  This module is responsible for
94782 ** generating the code that loops through a table looking for applicable
94783 ** rows.  Indices are selected and used to speed the search when doing
94784 ** so is applicable.  Because this module is responsible for selecting
94785 ** indices, you might also think of this module as the "query optimizer".
94786 */
94787
94788 /*
94789 ** Trace output macros
94790 */
94791 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
94792 SQLITE_PRIVATE int sqlite3WhereTrace = 0;
94793 #endif
94794 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
94795 # define WHERETRACE(X)  if(sqlite3WhereTrace) sqlite3DebugPrintf X
94796 #else
94797 # define WHERETRACE(X)
94798 #endif
94799
94800 /* Forward reference
94801 */
94802 typedef struct WhereClause WhereClause;
94803 typedef struct WhereMaskSet WhereMaskSet;
94804 typedef struct WhereOrInfo WhereOrInfo;
94805 typedef struct WhereAndInfo WhereAndInfo;
94806 typedef struct WhereCost WhereCost;
94807
94808 /*
94809 ** The query generator uses an array of instances of this structure to
94810 ** help it analyze the subexpressions of the WHERE clause.  Each WHERE
94811 ** clause subexpression is separated from the others by AND operators,
94812 ** usually, or sometimes subexpressions separated by OR.
94813 **
94814 ** All WhereTerms are collected into a single WhereClause structure.  
94815 ** The following identity holds:
94816 **
94817 **        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
94818 **
94819 ** When a term is of the form:
94820 **
94821 **              X <op> <expr>
94822 **
94823 ** where X is a column name and <op> is one of certain operators,
94824 ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
94825 ** cursor number and column number for X.  WhereTerm.eOperator records
94826 ** the <op> using a bitmask encoding defined by WO_xxx below.  The
94827 ** use of a bitmask encoding for the operator allows us to search
94828 ** quickly for terms that match any of several different operators.
94829 **
94830 ** A WhereTerm might also be two or more subterms connected by OR:
94831 **
94832 **         (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
94833 **
94834 ** In this second case, wtFlag as the TERM_ORINFO set and eOperator==WO_OR
94835 ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
94836 ** is collected about the
94837 **
94838 ** If a term in the WHERE clause does not match either of the two previous
94839 ** categories, then eOperator==0.  The WhereTerm.pExpr field is still set
94840 ** to the original subexpression content and wtFlags is set up appropriately
94841 ** but no other fields in the WhereTerm object are meaningful.
94842 **
94843 ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
94844 ** but they do so indirectly.  A single WhereMaskSet structure translates
94845 ** cursor number into bits and the translated bit is stored in the prereq
94846 ** fields.  The translation is used in order to maximize the number of
94847 ** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
94848 ** spread out over the non-negative integers.  For example, the cursor
94849 ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The WhereMaskSet
94850 ** translates these sparse cursor numbers into consecutive integers
94851 ** beginning with 0 in order to make the best possible use of the available
94852 ** bits in the Bitmask.  So, in the example above, the cursor numbers
94853 ** would be mapped into integers 0 through 7.
94854 **
94855 ** The number of terms in a join is limited by the number of bits
94856 ** in prereqRight and prereqAll.  The default is 64 bits, hence SQLite
94857 ** is only able to process joins with 64 or fewer tables.
94858 */
94859 typedef struct WhereTerm WhereTerm;
94860 struct WhereTerm {
94861   Expr *pExpr;            /* Pointer to the subexpression that is this term */
94862   int iParent;            /* Disable pWC->a[iParent] when this term disabled */
94863   int leftCursor;         /* Cursor number of X in "X <op> <expr>" */
94864   union {
94865     int leftColumn;         /* Column number of X in "X <op> <expr>" */
94866     WhereOrInfo *pOrInfo;   /* Extra information if eOperator==WO_OR */
94867     WhereAndInfo *pAndInfo; /* Extra information if eOperator==WO_AND */
94868   } u;
94869   u16 eOperator;          /* A WO_xx value describing <op> */
94870   u8 wtFlags;             /* TERM_xxx bit flags.  See below */
94871   u8 nChild;              /* Number of children that must disable us */
94872   WhereClause *pWC;       /* The clause this term is part of */
94873   Bitmask prereqRight;    /* Bitmask of tables used by pExpr->pRight */
94874   Bitmask prereqAll;      /* Bitmask of tables referenced by pExpr */
94875 };
94876
94877 /*
94878 ** Allowed values of WhereTerm.wtFlags
94879 */
94880 #define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(db, pExpr) */
94881 #define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
94882 #define TERM_CODED      0x04   /* This term is already coded */
94883 #define TERM_COPIED     0x08   /* Has a child */
94884 #define TERM_ORINFO     0x10   /* Need to free the WhereTerm.u.pOrInfo object */
94885 #define TERM_ANDINFO    0x20   /* Need to free the WhereTerm.u.pAndInfo obj */
94886 #define TERM_OR_OK      0x40   /* Used during OR-clause processing */
94887
94888 /*
94889 ** An instance of the following structure holds all information about a
94890 ** WHERE clause.  Mostly this is a container for one or more WhereTerms.
94891 */
94892 struct WhereClause {
94893   Parse *pParse;           /* The parser context */
94894   WhereMaskSet *pMaskSet;  /* Mapping of table cursor numbers to bitmasks */
94895   Bitmask vmask;           /* Bitmask identifying virtual table cursors */
94896   u8 op;                   /* Split operator.  TK_AND or TK_OR */
94897   int nTerm;               /* Number of terms */
94898   int nSlot;               /* Number of entries in a[] */
94899   WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
94900 #if defined(SQLITE_SMALL_STACK)
94901   WhereTerm aStatic[1];    /* Initial static space for a[] */
94902 #else
94903   WhereTerm aStatic[8];    /* Initial static space for a[] */
94904 #endif
94905 };
94906
94907 /*
94908 ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
94909 ** a dynamically allocated instance of the following structure.
94910 */
94911 struct WhereOrInfo {
94912   WhereClause wc;          /* Decomposition into subterms */
94913   Bitmask indexable;       /* Bitmask of all indexable tables in the clause */
94914 };
94915
94916 /*
94917 ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
94918 ** a dynamically allocated instance of the following structure.
94919 */
94920 struct WhereAndInfo {
94921   WhereClause wc;          /* The subexpression broken out */
94922 };
94923
94924 /*
94925 ** An instance of the following structure keeps track of a mapping
94926 ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
94927 **
94928 ** The VDBE cursor numbers are small integers contained in 
94929 ** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE 
94930 ** clause, the cursor numbers might not begin with 0 and they might
94931 ** contain gaps in the numbering sequence.  But we want to make maximum
94932 ** use of the bits in our bitmasks.  This structure provides a mapping
94933 ** from the sparse cursor numbers into consecutive integers beginning
94934 ** with 0.
94935 **
94936 ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
94937 ** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
94938 **
94939 ** For example, if the WHERE clause expression used these VDBE
94940 ** cursors:  4, 5, 8, 29, 57, 73.  Then the  WhereMaskSet structure
94941 ** would map those cursor numbers into bits 0 through 5.
94942 **
94943 ** Note that the mapping is not necessarily ordered.  In the example
94944 ** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
94945 ** 57->5, 73->4.  Or one of 719 other combinations might be used. It
94946 ** does not really matter.  What is important is that sparse cursor
94947 ** numbers all get mapped into bit numbers that begin with 0 and contain
94948 ** no gaps.
94949 */
94950 struct WhereMaskSet {
94951   int n;                        /* Number of assigned cursor values */
94952   int ix[BMS];                  /* Cursor assigned to each bit */
94953 };
94954
94955 /*
94956 ** A WhereCost object records a lookup strategy and the estimated
94957 ** cost of pursuing that strategy.
94958 */
94959 struct WhereCost {
94960   WherePlan plan;    /* The lookup strategy */
94961   double rCost;      /* Overall cost of pursuing this search strategy */
94962   double nRow;       /* Estimated number of output rows */
94963   Bitmask used;      /* Bitmask of cursors used by this plan */
94964 };
94965
94966 /*
94967 ** Bitmasks for the operators that indices are able to exploit.  An
94968 ** OR-ed combination of these values can be used when searching for
94969 ** terms in the where clause.
94970 */
94971 #define WO_IN     0x001
94972 #define WO_EQ     0x002
94973 #define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
94974 #define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
94975 #define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
94976 #define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
94977 #define WO_MATCH  0x040
94978 #define WO_ISNULL 0x080
94979 #define WO_OR     0x100       /* Two or more OR-connected terms */
94980 #define WO_AND    0x200       /* Two or more AND-connected terms */
94981
94982 #define WO_ALL    0xfff       /* Mask of all possible WO_* values */
94983 #define WO_SINGLE 0x0ff       /* Mask of all non-compound WO_* values */
94984
94985 /*
94986 ** Value for wsFlags returned by bestIndex() and stored in
94987 ** WhereLevel.wsFlags.  These flags determine which search
94988 ** strategies are appropriate.
94989 **
94990 ** The least significant 12 bits is reserved as a mask for WO_ values above.
94991 ** The WhereLevel.wsFlags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
94992 ** But if the table is the right table of a left join, WhereLevel.wsFlags
94993 ** is set to WO_IN|WO_EQ.  The WhereLevel.wsFlags field can then be used as
94994 ** the "op" parameter to findTerm when we are resolving equality constraints.
94995 ** ISNULL constraints will then not be used on the right table of a left
94996 ** join.  Tickets #2177 and #2189.
94997 */
94998 #define WHERE_ROWID_EQ     0x00001000  /* rowid=EXPR or rowid IN (...) */
94999 #define WHERE_ROWID_RANGE  0x00002000  /* rowid<EXPR and/or rowid>EXPR */
95000 #define WHERE_COLUMN_EQ    0x00010000  /* x=EXPR or x IN (...) or x IS NULL */
95001 #define WHERE_COLUMN_RANGE 0x00020000  /* x<EXPR and/or x>EXPR */
95002 #define WHERE_COLUMN_IN    0x00040000  /* x IN (...) */
95003 #define WHERE_COLUMN_NULL  0x00080000  /* x IS NULL */
95004 #define WHERE_INDEXED      0x000f0000  /* Anything that uses an index */
95005 #define WHERE_NOT_FULLSCAN 0x000f3000  /* Does not do a full table scan */
95006 #define WHERE_IN_ABLE      0x000f1000  /* Able to support an IN operator */
95007 #define WHERE_TOP_LIMIT    0x00100000  /* x<EXPR or x<=EXPR constraint */
95008 #define WHERE_BTM_LIMIT    0x00200000  /* x>EXPR or x>=EXPR constraint */
95009 #define WHERE_IDX_ONLY     0x00800000  /* Use index only - omit table */
95010 #define WHERE_ORDERBY      0x01000000  /* Output will appear in correct order */
95011 #define WHERE_REVERSE      0x02000000  /* Scan in reverse order */
95012 #define WHERE_UNIQUE       0x04000000  /* Selects no more than one row */
95013 #define WHERE_VIRTUALTABLE 0x08000000  /* Use virtual-table processing */
95014 #define WHERE_MULTI_OR     0x10000000  /* OR using multiple indices */
95015 #define WHERE_TEMP_INDEX   0x20000000  /* Uses an ephemeral index */
95016
95017 /*
95018 ** Initialize a preallocated WhereClause structure.
95019 */
95020 static void whereClauseInit(
95021   WhereClause *pWC,        /* The WhereClause to be initialized */
95022   Parse *pParse,           /* The parsing context */
95023   WhereMaskSet *pMaskSet   /* Mapping from table cursor numbers to bitmasks */
95024 ){
95025   pWC->pParse = pParse;
95026   pWC->pMaskSet = pMaskSet;
95027   pWC->nTerm = 0;
95028   pWC->nSlot = ArraySize(pWC->aStatic);
95029   pWC->a = pWC->aStatic;
95030   pWC->vmask = 0;
95031 }
95032
95033 /* Forward reference */
95034 static void whereClauseClear(WhereClause*);
95035
95036 /*
95037 ** Deallocate all memory associated with a WhereOrInfo object.
95038 */
95039 static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
95040   whereClauseClear(&p->wc);
95041   sqlite3DbFree(db, p);
95042 }
95043
95044 /*
95045 ** Deallocate all memory associated with a WhereAndInfo object.
95046 */
95047 static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
95048   whereClauseClear(&p->wc);
95049   sqlite3DbFree(db, p);
95050 }
95051
95052 /*
95053 ** Deallocate a WhereClause structure.  The WhereClause structure
95054 ** itself is not freed.  This routine is the inverse of whereClauseInit().
95055 */
95056 static void whereClauseClear(WhereClause *pWC){
95057   int i;
95058   WhereTerm *a;
95059   sqlite3 *db = pWC->pParse->db;
95060   for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
95061     if( a->wtFlags & TERM_DYNAMIC ){
95062       sqlite3ExprDelete(db, a->pExpr);
95063     }
95064     if( a->wtFlags & TERM_ORINFO ){
95065       whereOrInfoDelete(db, a->u.pOrInfo);
95066     }else if( a->wtFlags & TERM_ANDINFO ){
95067       whereAndInfoDelete(db, a->u.pAndInfo);
95068     }
95069   }
95070   if( pWC->a!=pWC->aStatic ){
95071     sqlite3DbFree(db, pWC->a);
95072   }
95073 }
95074
95075 /*
95076 ** Add a single new WhereTerm entry to the WhereClause object pWC.
95077 ** The new WhereTerm object is constructed from Expr p and with wtFlags.
95078 ** The index in pWC->a[] of the new WhereTerm is returned on success.
95079 ** 0 is returned if the new WhereTerm could not be added due to a memory
95080 ** allocation error.  The memory allocation failure will be recorded in
95081 ** the db->mallocFailed flag so that higher-level functions can detect it.
95082 **
95083 ** This routine will increase the size of the pWC->a[] array as necessary.
95084 **
95085 ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
95086 ** for freeing the expression p is assumed by the WhereClause object pWC.
95087 ** This is true even if this routine fails to allocate a new WhereTerm.
95088 **
95089 ** WARNING:  This routine might reallocate the space used to store
95090 ** WhereTerms.  All pointers to WhereTerms should be invalidated after
95091 ** calling this routine.  Such pointers may be reinitialized by referencing
95092 ** the pWC->a[] array.
95093 */
95094 static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
95095   WhereTerm *pTerm;
95096   int idx;
95097   testcase( wtFlags & TERM_VIRTUAL );  /* EV: R-00211-15100 */
95098   if( pWC->nTerm>=pWC->nSlot ){
95099     WhereTerm *pOld = pWC->a;
95100     sqlite3 *db = pWC->pParse->db;
95101     pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
95102     if( pWC->a==0 ){
95103       if( wtFlags & TERM_DYNAMIC ){
95104         sqlite3ExprDelete(db, p);
95105       }
95106       pWC->a = pOld;
95107       return 0;
95108     }
95109     memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
95110     if( pOld!=pWC->aStatic ){
95111       sqlite3DbFree(db, pOld);
95112     }
95113     pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
95114   }
95115   pTerm = &pWC->a[idx = pWC->nTerm++];
95116   pTerm->pExpr = p;
95117   pTerm->wtFlags = wtFlags;
95118   pTerm->pWC = pWC;
95119   pTerm->iParent = -1;
95120   return idx;
95121 }
95122
95123 /*
95124 ** This routine identifies subexpressions in the WHERE clause where
95125 ** each subexpression is separated by the AND operator or some other
95126 ** operator specified in the op parameter.  The WhereClause structure
95127 ** is filled with pointers to subexpressions.  For example:
95128 **
95129 **    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
95130 **           \________/     \_______________/     \________________/
95131 **            slot[0]            slot[1]               slot[2]
95132 **
95133 ** The original WHERE clause in pExpr is unaltered.  All this routine
95134 ** does is make slot[] entries point to substructure within pExpr.
95135 **
95136 ** In the previous sentence and in the diagram, "slot[]" refers to
95137 ** the WhereClause.a[] array.  The slot[] array grows as needed to contain
95138 ** all terms of the WHERE clause.
95139 */
95140 static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
95141   pWC->op = (u8)op;
95142   if( pExpr==0 ) return;
95143   if( pExpr->op!=op ){
95144     whereClauseInsert(pWC, pExpr, 0);
95145   }else{
95146     whereSplit(pWC, pExpr->pLeft, op);
95147     whereSplit(pWC, pExpr->pRight, op);
95148   }
95149 }
95150
95151 /*
95152 ** Initialize an expression mask set (a WhereMaskSet object)
95153 */
95154 #define initMaskSet(P)  memset(P, 0, sizeof(*P))
95155
95156 /*
95157 ** Return the bitmask for the given cursor number.  Return 0 if
95158 ** iCursor is not in the set.
95159 */
95160 static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
95161   int i;
95162   assert( pMaskSet->n<=sizeof(Bitmask)*8 );
95163   for(i=0; i<pMaskSet->n; i++){
95164     if( pMaskSet->ix[i]==iCursor ){
95165       return ((Bitmask)1)<<i;
95166     }
95167   }
95168   return 0;
95169 }
95170
95171 /*
95172 ** Create a new mask for cursor iCursor.
95173 **
95174 ** There is one cursor per table in the FROM clause.  The number of
95175 ** tables in the FROM clause is limited by a test early in the
95176 ** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
95177 ** array will never overflow.
95178 */
95179 static void createMask(WhereMaskSet *pMaskSet, int iCursor){
95180   assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
95181   pMaskSet->ix[pMaskSet->n++] = iCursor;
95182 }
95183
95184 /*
95185 ** This routine walks (recursively) an expression tree and generates
95186 ** a bitmask indicating which tables are used in that expression
95187 ** tree.
95188 **
95189 ** In order for this routine to work, the calling function must have
95190 ** previously invoked sqlite3ResolveExprNames() on the expression.  See
95191 ** the header comment on that routine for additional information.
95192 ** The sqlite3ResolveExprNames() routines looks for column names and
95193 ** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
95194 ** the VDBE cursor number of the table.  This routine just has to
95195 ** translate the cursor numbers into bitmask values and OR all
95196 ** the bitmasks together.
95197 */
95198 static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
95199 static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
95200 static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
95201   Bitmask mask = 0;
95202   if( p==0 ) return 0;
95203   if( p->op==TK_COLUMN ){
95204     mask = getMask(pMaskSet, p->iTable);
95205     return mask;
95206   }
95207   mask = exprTableUsage(pMaskSet, p->pRight);
95208   mask |= exprTableUsage(pMaskSet, p->pLeft);
95209   if( ExprHasProperty(p, EP_xIsSelect) ){
95210     mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
95211   }else{
95212     mask |= exprListTableUsage(pMaskSet, p->x.pList);
95213   }
95214   return mask;
95215 }
95216 static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
95217   int i;
95218   Bitmask mask = 0;
95219   if( pList ){
95220     for(i=0; i<pList->nExpr; i++){
95221       mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
95222     }
95223   }
95224   return mask;
95225 }
95226 static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
95227   Bitmask mask = 0;
95228   while( pS ){
95229     mask |= exprListTableUsage(pMaskSet, pS->pEList);
95230     mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
95231     mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
95232     mask |= exprTableUsage(pMaskSet, pS->pWhere);
95233     mask |= exprTableUsage(pMaskSet, pS->pHaving);
95234     pS = pS->pPrior;
95235   }
95236   return mask;
95237 }
95238
95239 /*
95240 ** Return TRUE if the given operator is one of the operators that is
95241 ** allowed for an indexable WHERE clause term.  The allowed operators are
95242 ** "=", "<", ">", "<=", ">=", and "IN".
95243 **
95244 ** IMPLEMENTATION-OF: R-59926-26393 To be usable by an index a term must be
95245 ** of one of the following forms: column = expression column > expression
95246 ** column >= expression column < expression column <= expression
95247 ** expression = column expression > column expression >= column
95248 ** expression < column expression <= column column IN
95249 ** (expression-list) column IN (subquery) column IS NULL
95250 */
95251 static int allowedOp(int op){
95252   assert( TK_GT>TK_EQ && TK_GT<TK_GE );
95253   assert( TK_LT>TK_EQ && TK_LT<TK_GE );
95254   assert( TK_LE>TK_EQ && TK_LE<TK_GE );
95255   assert( TK_GE==TK_EQ+4 );
95256   return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
95257 }
95258
95259 /*
95260 ** Swap two objects of type TYPE.
95261 */
95262 #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
95263
95264 /*
95265 ** Commute a comparison operator.  Expressions of the form "X op Y"
95266 ** are converted into "Y op X".
95267 **
95268 ** If a collation sequence is associated with either the left or right
95269 ** side of the comparison, it remains associated with the same side after
95270 ** the commutation. So "Y collate NOCASE op X" becomes 
95271 ** "X collate NOCASE op Y". This is because any collation sequence on
95272 ** the left hand side of a comparison overrides any collation sequence 
95273 ** attached to the right. For the same reason the EP_ExpCollate flag
95274 ** is not commuted.
95275 */
95276 static void exprCommute(Parse *pParse, Expr *pExpr){
95277   u16 expRight = (pExpr->pRight->flags & EP_ExpCollate);
95278   u16 expLeft = (pExpr->pLeft->flags & EP_ExpCollate);
95279   assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
95280   pExpr->pRight->pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight);
95281   pExpr->pLeft->pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
95282   SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
95283   pExpr->pRight->flags = (pExpr->pRight->flags & ~EP_ExpCollate) | expLeft;
95284   pExpr->pLeft->flags = (pExpr->pLeft->flags & ~EP_ExpCollate) | expRight;
95285   SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
95286   if( pExpr->op>=TK_GT ){
95287     assert( TK_LT==TK_GT+2 );
95288     assert( TK_GE==TK_LE+2 );
95289     assert( TK_GT>TK_EQ );
95290     assert( TK_GT<TK_LE );
95291     assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
95292     pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
95293   }
95294 }
95295
95296 /*
95297 ** Translate from TK_xx operator to WO_xx bitmask.
95298 */
95299 static u16 operatorMask(int op){
95300   u16 c;
95301   assert( allowedOp(op) );
95302   if( op==TK_IN ){
95303     c = WO_IN;
95304   }else if( op==TK_ISNULL ){
95305     c = WO_ISNULL;
95306   }else{
95307     assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
95308     c = (u16)(WO_EQ<<(op-TK_EQ));
95309   }
95310   assert( op!=TK_ISNULL || c==WO_ISNULL );
95311   assert( op!=TK_IN || c==WO_IN );
95312   assert( op!=TK_EQ || c==WO_EQ );
95313   assert( op!=TK_LT || c==WO_LT );
95314   assert( op!=TK_LE || c==WO_LE );
95315   assert( op!=TK_GT || c==WO_GT );
95316   assert( op!=TK_GE || c==WO_GE );
95317   return c;
95318 }
95319
95320 /*
95321 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
95322 ** where X is a reference to the iColumn of table iCur and <op> is one of
95323 ** the WO_xx operator codes specified by the op parameter.
95324 ** Return a pointer to the term.  Return 0 if not found.
95325 */
95326 static WhereTerm *findTerm(
95327   WhereClause *pWC,     /* The WHERE clause to be searched */
95328   int iCur,             /* Cursor number of LHS */
95329   int iColumn,          /* Column number of LHS */
95330   Bitmask notReady,     /* RHS must not overlap with this mask */
95331   u32 op,               /* Mask of WO_xx values describing operator */
95332   Index *pIdx           /* Must be compatible with this index, if not NULL */
95333 ){
95334   WhereTerm *pTerm;
95335   int k;
95336   assert( iCur>=0 );
95337   op &= WO_ALL;
95338   for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
95339     if( pTerm->leftCursor==iCur
95340        && (pTerm->prereqRight & notReady)==0
95341        && pTerm->u.leftColumn==iColumn
95342        && (pTerm->eOperator & op)!=0
95343     ){
95344       if( pIdx && pTerm->eOperator!=WO_ISNULL ){
95345         Expr *pX = pTerm->pExpr;
95346         CollSeq *pColl;
95347         char idxaff;
95348         int j;
95349         Parse *pParse = pWC->pParse;
95350
95351         idxaff = pIdx->pTable->aCol[iColumn].affinity;
95352         if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
95353
95354         /* Figure out the collation sequence required from an index for
95355         ** it to be useful for optimising expression pX. Store this
95356         ** value in variable pColl.
95357         */
95358         assert(pX->pLeft);
95359         pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
95360         assert(pColl || pParse->nErr);
95361
95362         for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
95363           if( NEVER(j>=pIdx->nColumn) ) return 0;
95364         }
95365         if( pColl && sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ) continue;
95366       }
95367       return pTerm;
95368     }
95369   }
95370   return 0;
95371 }
95372
95373 /* Forward reference */
95374 static void exprAnalyze(SrcList*, WhereClause*, int);
95375
95376 /*
95377 ** Call exprAnalyze on all terms in a WHERE clause.  
95378 **
95379 **
95380 */
95381 static void exprAnalyzeAll(
95382   SrcList *pTabList,       /* the FROM clause */
95383   WhereClause *pWC         /* the WHERE clause to be analyzed */
95384 ){
95385   int i;
95386   for(i=pWC->nTerm-1; i>=0; i--){
95387     exprAnalyze(pTabList, pWC, i);
95388   }
95389 }
95390
95391 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
95392 /*
95393 ** Check to see if the given expression is a LIKE or GLOB operator that
95394 ** can be optimized using inequality constraints.  Return TRUE if it is
95395 ** so and false if not.
95396 **
95397 ** In order for the operator to be optimizible, the RHS must be a string
95398 ** literal that does not begin with a wildcard.  
95399 */
95400 static int isLikeOrGlob(
95401   Parse *pParse,    /* Parsing and code generating context */
95402   Expr *pExpr,      /* Test this expression */
95403   Expr **ppPrefix,  /* Pointer to TK_STRING expression with pattern prefix */
95404   int *pisComplete, /* True if the only wildcard is % in the last character */
95405   int *pnoCase      /* True if uppercase is equivalent to lowercase */
95406 ){
95407   const char *z = 0;         /* String on RHS of LIKE operator */
95408   Expr *pRight, *pLeft;      /* Right and left size of LIKE operator */
95409   ExprList *pList;           /* List of operands to the LIKE operator */
95410   int c;                     /* One character in z[] */
95411   int cnt;                   /* Number of non-wildcard prefix characters */
95412   char wc[3];                /* Wildcard characters */
95413   sqlite3 *db = pParse->db;  /* Database connection */
95414   sqlite3_value *pVal = 0;
95415   int op;                    /* Opcode of pRight */
95416
95417   if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
95418     return 0;
95419   }
95420 #ifdef SQLITE_EBCDIC
95421   if( *pnoCase ) return 0;
95422 #endif
95423   pList = pExpr->x.pList;
95424   pLeft = pList->a[1].pExpr;
95425   if( pLeft->op!=TK_COLUMN || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT ){
95426     /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
95427     ** be the name of an indexed column with TEXT affinity. */
95428     return 0;
95429   }
95430   assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
95431
95432   pRight = pList->a[0].pExpr;
95433   op = pRight->op;
95434   if( op==TK_REGISTER ){
95435     op = pRight->op2;
95436   }
95437   if( op==TK_VARIABLE ){
95438     Vdbe *pReprepare = pParse->pReprepare;
95439     int iCol = pRight->iColumn;
95440     pVal = sqlite3VdbeGetValue(pReprepare, iCol, SQLITE_AFF_NONE);
95441     if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
95442       z = (char *)sqlite3_value_text(pVal);
95443     }
95444     sqlite3VdbeSetVarmask(pParse->pVdbe, iCol); /* IMP: R-23257-02778 */
95445     assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
95446   }else if( op==TK_STRING ){
95447     z = pRight->u.zToken;
95448   }
95449   if( z ){
95450     cnt = 0;
95451     while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
95452       cnt++;
95453     }
95454     if( cnt!=0 && 255!=(u8)z[cnt-1] ){
95455       Expr *pPrefix;
95456       *pisComplete = c==wc[0] && z[cnt+1]==0;
95457       pPrefix = sqlite3Expr(db, TK_STRING, z);
95458       if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
95459       *ppPrefix = pPrefix;
95460       if( op==TK_VARIABLE ){
95461         Vdbe *v = pParse->pVdbe;
95462         sqlite3VdbeSetVarmask(v, pRight->iColumn); /* IMP: R-23257-02778 */
95463         if( *pisComplete && pRight->u.zToken[1] ){
95464           /* If the rhs of the LIKE expression is a variable, and the current
95465           ** value of the variable means there is no need to invoke the LIKE
95466           ** function, then no OP_Variable will be added to the program.
95467           ** This causes problems for the sqlite3_bind_parameter_name()
95468           ** API. To workaround them, add a dummy OP_Variable here.
95469           */ 
95470           int r1 = sqlite3GetTempReg(pParse);
95471           sqlite3ExprCodeTarget(pParse, pRight, r1);
95472           sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
95473           sqlite3ReleaseTempReg(pParse, r1);
95474         }
95475       }
95476     }else{
95477       z = 0;
95478     }
95479   }
95480
95481   sqlite3ValueFree(pVal);
95482   return (z!=0);
95483 }
95484 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
95485
95486
95487 #ifndef SQLITE_OMIT_VIRTUALTABLE
95488 /*
95489 ** Check to see if the given expression is of the form
95490 **
95491 **         column MATCH expr
95492 **
95493 ** If it is then return TRUE.  If not, return FALSE.
95494 */
95495 static int isMatchOfColumn(
95496   Expr *pExpr      /* Test this expression */
95497 ){
95498   ExprList *pList;
95499
95500   if( pExpr->op!=TK_FUNCTION ){
95501     return 0;
95502   }
95503   if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
95504     return 0;
95505   }
95506   pList = pExpr->x.pList;
95507   if( pList->nExpr!=2 ){
95508     return 0;
95509   }
95510   if( pList->a[1].pExpr->op != TK_COLUMN ){
95511     return 0;
95512   }
95513   return 1;
95514 }
95515 #endif /* SQLITE_OMIT_VIRTUALTABLE */
95516
95517 /*
95518 ** If the pBase expression originated in the ON or USING clause of
95519 ** a join, then transfer the appropriate markings over to derived.
95520 */
95521 static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
95522   pDerived->flags |= pBase->flags & EP_FromJoin;
95523   pDerived->iRightJoinTable = pBase->iRightJoinTable;
95524 }
95525
95526 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
95527 /*
95528 ** Analyze a term that consists of two or more OR-connected
95529 ** subterms.  So in:
95530 **
95531 **     ... WHERE  (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
95532 **                          ^^^^^^^^^^^^^^^^^^^^
95533 **
95534 ** This routine analyzes terms such as the middle term in the above example.
95535 ** A WhereOrTerm object is computed and attached to the term under
95536 ** analysis, regardless of the outcome of the analysis.  Hence:
95537 **
95538 **     WhereTerm.wtFlags   |=  TERM_ORINFO
95539 **     WhereTerm.u.pOrInfo  =  a dynamically allocated WhereOrTerm object
95540 **
95541 ** The term being analyzed must have two or more of OR-connected subterms.
95542 ** A single subterm might be a set of AND-connected sub-subterms.
95543 ** Examples of terms under analysis:
95544 **
95545 **     (A)     t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
95546 **     (B)     x=expr1 OR expr2=x OR x=expr3
95547 **     (C)     t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
95548 **     (D)     x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
95549 **     (E)     (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
95550 **
95551 ** CASE 1:
95552 **
95553 ** If all subterms are of the form T.C=expr for some single column of C
95554 ** a single table T (as shown in example B above) then create a new virtual
95555 ** term that is an equivalent IN expression.  In other words, if the term
95556 ** being analyzed is:
95557 **
95558 **      x = expr1  OR  expr2 = x  OR  x = expr3
95559 **
95560 ** then create a new virtual term like this:
95561 **
95562 **      x IN (expr1,expr2,expr3)
95563 **
95564 ** CASE 2:
95565 **
95566 ** If all subterms are indexable by a single table T, then set
95567 **
95568 **     WhereTerm.eOperator              =  WO_OR
95569 **     WhereTerm.u.pOrInfo->indexable  |=  the cursor number for table T
95570 **
95571 ** A subterm is "indexable" if it is of the form
95572 ** "T.C <op> <expr>" where C is any column of table T and 
95573 ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
95574 ** A subterm is also indexable if it is an AND of two or more
95575 ** subsubterms at least one of which is indexable.  Indexable AND 
95576 ** subterms have their eOperator set to WO_AND and they have
95577 ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
95578 **
95579 ** From another point of view, "indexable" means that the subterm could
95580 ** potentially be used with an index if an appropriate index exists.
95581 ** This analysis does not consider whether or not the index exists; that
95582 ** is something the bestIndex() routine will determine.  This analysis
95583 ** only looks at whether subterms appropriate for indexing exist.
95584 **
95585 ** All examples A through E above all satisfy case 2.  But if a term
95586 ** also statisfies case 1 (such as B) we know that the optimizer will
95587 ** always prefer case 1, so in that case we pretend that case 2 is not
95588 ** satisfied.
95589 **
95590 ** It might be the case that multiple tables are indexable.  For example,
95591 ** (E) above is indexable on tables P, Q, and R.
95592 **
95593 ** Terms that satisfy case 2 are candidates for lookup by using
95594 ** separate indices to find rowids for each subterm and composing
95595 ** the union of all rowids using a RowSet object.  This is similar
95596 ** to "bitmap indices" in other database engines.
95597 **
95598 ** OTHERWISE:
95599 **
95600 ** If neither case 1 nor case 2 apply, then leave the eOperator set to
95601 ** zero.  This term is not useful for search.
95602 */
95603 static void exprAnalyzeOrTerm(
95604   SrcList *pSrc,            /* the FROM clause */
95605   WhereClause *pWC,         /* the complete WHERE clause */
95606   int idxTerm               /* Index of the OR-term to be analyzed */
95607 ){
95608   Parse *pParse = pWC->pParse;            /* Parser context */
95609   sqlite3 *db = pParse->db;               /* Database connection */
95610   WhereTerm *pTerm = &pWC->a[idxTerm];    /* The term to be analyzed */
95611   Expr *pExpr = pTerm->pExpr;             /* The expression of the term */
95612   WhereMaskSet *pMaskSet = pWC->pMaskSet; /* Table use masks */
95613   int i;                                  /* Loop counters */
95614   WhereClause *pOrWc;       /* Breakup of pTerm into subterms */
95615   WhereTerm *pOrTerm;       /* A Sub-term within the pOrWc */
95616   WhereOrInfo *pOrInfo;     /* Additional information associated with pTerm */
95617   Bitmask chngToIN;         /* Tables that might satisfy case 1 */
95618   Bitmask indexable;        /* Tables that are indexable, satisfying case 2 */
95619
95620   /*
95621   ** Break the OR clause into its separate subterms.  The subterms are
95622   ** stored in a WhereClause structure containing within the WhereOrInfo
95623   ** object that is attached to the original OR clause term.
95624   */
95625   assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
95626   assert( pExpr->op==TK_OR );
95627   pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
95628   if( pOrInfo==0 ) return;
95629   pTerm->wtFlags |= TERM_ORINFO;
95630   pOrWc = &pOrInfo->wc;
95631   whereClauseInit(pOrWc, pWC->pParse, pMaskSet);
95632   whereSplit(pOrWc, pExpr, TK_OR);
95633   exprAnalyzeAll(pSrc, pOrWc);
95634   if( db->mallocFailed ) return;
95635   assert( pOrWc->nTerm>=2 );
95636
95637   /*
95638   ** Compute the set of tables that might satisfy cases 1 or 2.
95639   */
95640   indexable = ~(Bitmask)0;
95641   chngToIN = ~(pWC->vmask);
95642   for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
95643     if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
95644       WhereAndInfo *pAndInfo;
95645       assert( pOrTerm->eOperator==0 );
95646       assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
95647       chngToIN = 0;
95648       pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
95649       if( pAndInfo ){
95650         WhereClause *pAndWC;
95651         WhereTerm *pAndTerm;
95652         int j;
95653         Bitmask b = 0;
95654         pOrTerm->u.pAndInfo = pAndInfo;
95655         pOrTerm->wtFlags |= TERM_ANDINFO;
95656         pOrTerm->eOperator = WO_AND;
95657         pAndWC = &pAndInfo->wc;
95658         whereClauseInit(pAndWC, pWC->pParse, pMaskSet);
95659         whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
95660         exprAnalyzeAll(pSrc, pAndWC);
95661         testcase( db->mallocFailed );
95662         if( !db->mallocFailed ){
95663           for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
95664             assert( pAndTerm->pExpr );
95665             if( allowedOp(pAndTerm->pExpr->op) ){
95666               b |= getMask(pMaskSet, pAndTerm->leftCursor);
95667             }
95668           }
95669         }
95670         indexable &= b;
95671       }
95672     }else if( pOrTerm->wtFlags & TERM_COPIED ){
95673       /* Skip this term for now.  We revisit it when we process the
95674       ** corresponding TERM_VIRTUAL term */
95675     }else{
95676       Bitmask b;
95677       b = getMask(pMaskSet, pOrTerm->leftCursor);
95678       if( pOrTerm->wtFlags & TERM_VIRTUAL ){
95679         WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
95680         b |= getMask(pMaskSet, pOther->leftCursor);
95681       }
95682       indexable &= b;
95683       if( pOrTerm->eOperator!=WO_EQ ){
95684         chngToIN = 0;
95685       }else{
95686         chngToIN &= b;
95687       }
95688     }
95689   }
95690
95691   /*
95692   ** Record the set of tables that satisfy case 2.  The set might be
95693   ** empty.
95694   */
95695   pOrInfo->indexable = indexable;
95696   pTerm->eOperator = indexable==0 ? 0 : WO_OR;
95697
95698   /*
95699   ** chngToIN holds a set of tables that *might* satisfy case 1.  But
95700   ** we have to do some additional checking to see if case 1 really
95701   ** is satisfied.
95702   **
95703   ** chngToIN will hold either 0, 1, or 2 bits.  The 0-bit case means
95704   ** that there is no possibility of transforming the OR clause into an
95705   ** IN operator because one or more terms in the OR clause contain
95706   ** something other than == on a column in the single table.  The 1-bit
95707   ** case means that every term of the OR clause is of the form
95708   ** "table.column=expr" for some single table.  The one bit that is set
95709   ** will correspond to the common table.  We still need to check to make
95710   ** sure the same column is used on all terms.  The 2-bit case is when
95711   ** the all terms are of the form "table1.column=table2.column".  It
95712   ** might be possible to form an IN operator with either table1.column
95713   ** or table2.column as the LHS if either is common to every term of
95714   ** the OR clause.
95715   **
95716   ** Note that terms of the form "table.column1=table.column2" (the
95717   ** same table on both sizes of the ==) cannot be optimized.
95718   */
95719   if( chngToIN ){
95720     int okToChngToIN = 0;     /* True if the conversion to IN is valid */
95721     int iColumn = -1;         /* Column index on lhs of IN operator */
95722     int iCursor = -1;         /* Table cursor common to all terms */
95723     int j = 0;                /* Loop counter */
95724
95725     /* Search for a table and column that appears on one side or the
95726     ** other of the == operator in every subterm.  That table and column
95727     ** will be recorded in iCursor and iColumn.  There might not be any
95728     ** such table and column.  Set okToChngToIN if an appropriate table
95729     ** and column is found but leave okToChngToIN false if not found.
95730     */
95731     for(j=0; j<2 && !okToChngToIN; j++){
95732       pOrTerm = pOrWc->a;
95733       for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
95734         assert( pOrTerm->eOperator==WO_EQ );
95735         pOrTerm->wtFlags &= ~TERM_OR_OK;
95736         if( pOrTerm->leftCursor==iCursor ){
95737           /* This is the 2-bit case and we are on the second iteration and
95738           ** current term is from the first iteration.  So skip this term. */
95739           assert( j==1 );
95740           continue;
95741         }
95742         if( (chngToIN & getMask(pMaskSet, pOrTerm->leftCursor))==0 ){
95743           /* This term must be of the form t1.a==t2.b where t2 is in the
95744           ** chngToIN set but t1 is not.  This term will be either preceeded
95745           ** or follwed by an inverted copy (t2.b==t1.a).  Skip this term 
95746           ** and use its inversion. */
95747           testcase( pOrTerm->wtFlags & TERM_COPIED );
95748           testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
95749           assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
95750           continue;
95751         }
95752         iColumn = pOrTerm->u.leftColumn;
95753         iCursor = pOrTerm->leftCursor;
95754         break;
95755       }
95756       if( i<0 ){
95757         /* No candidate table+column was found.  This can only occur
95758         ** on the second iteration */
95759         assert( j==1 );
95760         assert( (chngToIN&(chngToIN-1))==0 );
95761         assert( chngToIN==getMask(pMaskSet, iCursor) );
95762         break;
95763       }
95764       testcase( j==1 );
95765
95766       /* We have found a candidate table and column.  Check to see if that
95767       ** table and column is common to every term in the OR clause */
95768       okToChngToIN = 1;
95769       for(; i>=0 && okToChngToIN; i--, pOrTerm++){
95770         assert( pOrTerm->eOperator==WO_EQ );
95771         if( pOrTerm->leftCursor!=iCursor ){
95772           pOrTerm->wtFlags &= ~TERM_OR_OK;
95773         }else if( pOrTerm->u.leftColumn!=iColumn ){
95774           okToChngToIN = 0;
95775         }else{
95776           int affLeft, affRight;
95777           /* If the right-hand side is also a column, then the affinities
95778           ** of both right and left sides must be such that no type
95779           ** conversions are required on the right.  (Ticket #2249)
95780           */
95781           affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
95782           affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
95783           if( affRight!=0 && affRight!=affLeft ){
95784             okToChngToIN = 0;
95785           }else{
95786             pOrTerm->wtFlags |= TERM_OR_OK;
95787           }
95788         }
95789       }
95790     }
95791
95792     /* At this point, okToChngToIN is true if original pTerm satisfies
95793     ** case 1.  In that case, construct a new virtual term that is 
95794     ** pTerm converted into an IN operator.
95795     **
95796     ** EV: R-00211-15100
95797     */
95798     if( okToChngToIN ){
95799       Expr *pDup;            /* A transient duplicate expression */
95800       ExprList *pList = 0;   /* The RHS of the IN operator */
95801       Expr *pLeft = 0;       /* The LHS of the IN operator */
95802       Expr *pNew;            /* The complete IN operator */
95803
95804       for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
95805         if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
95806         assert( pOrTerm->eOperator==WO_EQ );
95807         assert( pOrTerm->leftCursor==iCursor );
95808         assert( pOrTerm->u.leftColumn==iColumn );
95809         pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
95810         pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup);
95811         pLeft = pOrTerm->pExpr->pLeft;
95812       }
95813       assert( pLeft!=0 );
95814       pDup = sqlite3ExprDup(db, pLeft, 0);
95815       pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
95816       if( pNew ){
95817         int idxNew;
95818         transferJoinMarkings(pNew, pExpr);
95819         assert( !ExprHasProperty(pNew, EP_xIsSelect) );
95820         pNew->x.pList = pList;
95821         idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
95822         testcase( idxNew==0 );
95823         exprAnalyze(pSrc, pWC, idxNew);
95824         pTerm = &pWC->a[idxTerm];
95825         pWC->a[idxNew].iParent = idxTerm;
95826         pTerm->nChild = 1;
95827       }else{
95828         sqlite3ExprListDelete(db, pList);
95829       }
95830       pTerm->eOperator = 0;  /* case 1 trumps case 2 */
95831     }
95832   }
95833 }
95834 #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
95835
95836
95837 /*
95838 ** The input to this routine is an WhereTerm structure with only the
95839 ** "pExpr" field filled in.  The job of this routine is to analyze the
95840 ** subexpression and populate all the other fields of the WhereTerm
95841 ** structure.
95842 **
95843 ** If the expression is of the form "<expr> <op> X" it gets commuted
95844 ** to the standard form of "X <op> <expr>".
95845 **
95846 ** If the expression is of the form "X <op> Y" where both X and Y are
95847 ** columns, then the original expression is unchanged and a new virtual
95848 ** term of the form "Y <op> X" is added to the WHERE clause and
95849 ** analyzed separately.  The original term is marked with TERM_COPIED
95850 ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
95851 ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
95852 ** is a commuted copy of a prior term.)  The original term has nChild=1
95853 ** and the copy has idxParent set to the index of the original term.
95854 */
95855 static void exprAnalyze(
95856   SrcList *pSrc,            /* the FROM clause */
95857   WhereClause *pWC,         /* the WHERE clause */
95858   int idxTerm               /* Index of the term to be analyzed */
95859 ){
95860   WhereTerm *pTerm;                /* The term to be analyzed */
95861   WhereMaskSet *pMaskSet;          /* Set of table index masks */
95862   Expr *pExpr;                     /* The expression to be analyzed */
95863   Bitmask prereqLeft;              /* Prerequesites of the pExpr->pLeft */
95864   Bitmask prereqAll;               /* Prerequesites of pExpr */
95865   Bitmask extraRight = 0;          /* Extra dependencies on LEFT JOIN */
95866   Expr *pStr1 = 0;                 /* RHS of LIKE/GLOB operator */
95867   int isComplete = 0;              /* RHS of LIKE/GLOB ends with wildcard */
95868   int noCase = 0;                  /* LIKE/GLOB distinguishes case */
95869   int op;                          /* Top-level operator.  pExpr->op */
95870   Parse *pParse = pWC->pParse;     /* Parsing context */
95871   sqlite3 *db = pParse->db;        /* Database connection */
95872
95873   if( db->mallocFailed ){
95874     return;
95875   }
95876   pTerm = &pWC->a[idxTerm];
95877   pMaskSet = pWC->pMaskSet;
95878   pExpr = pTerm->pExpr;
95879   prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
95880   op = pExpr->op;
95881   if( op==TK_IN ){
95882     assert( pExpr->pRight==0 );
95883     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
95884       pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
95885     }else{
95886       pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
95887     }
95888   }else if( op==TK_ISNULL ){
95889     pTerm->prereqRight = 0;
95890   }else{
95891     pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
95892   }
95893   prereqAll = exprTableUsage(pMaskSet, pExpr);
95894   if( ExprHasProperty(pExpr, EP_FromJoin) ){
95895     Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
95896     prereqAll |= x;
95897     extraRight = x-1;  /* ON clause terms may not be used with an index
95898                        ** on left table of a LEFT JOIN.  Ticket #3015 */
95899   }
95900   pTerm->prereqAll = prereqAll;
95901   pTerm->leftCursor = -1;
95902   pTerm->iParent = -1;
95903   pTerm->eOperator = 0;
95904   if( allowedOp(op) && (pTerm->prereqRight & prereqLeft)==0 ){
95905     Expr *pLeft = pExpr->pLeft;
95906     Expr *pRight = pExpr->pRight;
95907     if( pLeft->op==TK_COLUMN ){
95908       pTerm->leftCursor = pLeft->iTable;
95909       pTerm->u.leftColumn = pLeft->iColumn;
95910       pTerm->eOperator = operatorMask(op);
95911     }
95912     if( pRight && pRight->op==TK_COLUMN ){
95913       WhereTerm *pNew;
95914       Expr *pDup;
95915       if( pTerm->leftCursor>=0 ){
95916         int idxNew;
95917         pDup = sqlite3ExprDup(db, pExpr, 0);
95918         if( db->mallocFailed ){
95919           sqlite3ExprDelete(db, pDup);
95920           return;
95921         }
95922         idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
95923         if( idxNew==0 ) return;
95924         pNew = &pWC->a[idxNew];
95925         pNew->iParent = idxTerm;
95926         pTerm = &pWC->a[idxTerm];
95927         pTerm->nChild = 1;
95928         pTerm->wtFlags |= TERM_COPIED;
95929       }else{
95930         pDup = pExpr;
95931         pNew = pTerm;
95932       }
95933       exprCommute(pParse, pDup);
95934       pLeft = pDup->pLeft;
95935       pNew->leftCursor = pLeft->iTable;
95936       pNew->u.leftColumn = pLeft->iColumn;
95937       testcase( (prereqLeft | extraRight) != prereqLeft );
95938       pNew->prereqRight = prereqLeft | extraRight;
95939       pNew->prereqAll = prereqAll;
95940       pNew->eOperator = operatorMask(pDup->op);
95941     }
95942   }
95943
95944 #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
95945   /* If a term is the BETWEEN operator, create two new virtual terms
95946   ** that define the range that the BETWEEN implements.  For example:
95947   **
95948   **      a BETWEEN b AND c
95949   **
95950   ** is converted into:
95951   **
95952   **      (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
95953   **
95954   ** The two new terms are added onto the end of the WhereClause object.
95955   ** The new terms are "dynamic" and are children of the original BETWEEN
95956   ** term.  That means that if the BETWEEN term is coded, the children are
95957   ** skipped.  Or, if the children are satisfied by an index, the original
95958   ** BETWEEN term is skipped.
95959   */
95960   else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
95961     ExprList *pList = pExpr->x.pList;
95962     int i;
95963     static const u8 ops[] = {TK_GE, TK_LE};
95964     assert( pList!=0 );
95965     assert( pList->nExpr==2 );
95966     for(i=0; i<2; i++){
95967       Expr *pNewExpr;
95968       int idxNew;
95969       pNewExpr = sqlite3PExpr(pParse, ops[i], 
95970                              sqlite3ExprDup(db, pExpr->pLeft, 0),
95971                              sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
95972       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
95973       testcase( idxNew==0 );
95974       exprAnalyze(pSrc, pWC, idxNew);
95975       pTerm = &pWC->a[idxTerm];
95976       pWC->a[idxNew].iParent = idxTerm;
95977     }
95978     pTerm->nChild = 2;
95979   }
95980 #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
95981
95982 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
95983   /* Analyze a term that is composed of two or more subterms connected by
95984   ** an OR operator.
95985   */
95986   else if( pExpr->op==TK_OR ){
95987     assert( pWC->op==TK_AND );
95988     exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
95989     pTerm = &pWC->a[idxTerm];
95990   }
95991 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
95992
95993 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
95994   /* Add constraints to reduce the search space on a LIKE or GLOB
95995   ** operator.
95996   **
95997   ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
95998   **
95999   **          x>='abc' AND x<'abd' AND x LIKE 'abc%'
96000   **
96001   ** The last character of the prefix "abc" is incremented to form the
96002   ** termination condition "abd".
96003   */
96004   if( pWC->op==TK_AND 
96005    && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
96006   ){
96007     Expr *pLeft;       /* LHS of LIKE/GLOB operator */
96008     Expr *pStr2;       /* Copy of pStr1 - RHS of LIKE/GLOB operator */
96009     Expr *pNewExpr1;
96010     Expr *pNewExpr2;
96011     int idxNew1;
96012     int idxNew2;
96013     CollSeq *pColl;    /* Collating sequence to use */
96014
96015     pLeft = pExpr->x.pList->a[1].pExpr;
96016     pStr2 = sqlite3ExprDup(db, pStr1, 0);
96017     if( !db->mallocFailed ){
96018       u8 c, *pC;       /* Last character before the first wildcard */
96019       pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
96020       c = *pC;
96021       if( noCase ){
96022         /* The point is to increment the last character before the first
96023         ** wildcard.  But if we increment '@', that will push it into the
96024         ** alphabetic range where case conversions will mess up the 
96025         ** inequality.  To avoid this, make sure to also run the full
96026         ** LIKE on all candidate expressions by clearing the isComplete flag
96027         */
96028         if( c=='A'-1 ) isComplete = 0;   /* EV: R-64339-08207 */
96029
96030
96031         c = sqlite3UpperToLower[c];
96032       }
96033       *pC = c + 1;
96034     }
96035     pColl = sqlite3FindCollSeq(db, SQLITE_UTF8, noCase ? "NOCASE" : "BINARY",0);
96036     pNewExpr1 = sqlite3PExpr(pParse, TK_GE, 
96037                      sqlite3ExprSetColl(sqlite3ExprDup(db,pLeft,0), pColl),
96038                      pStr1, 0);
96039     idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
96040     testcase( idxNew1==0 );
96041     exprAnalyze(pSrc, pWC, idxNew1);
96042     pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
96043                      sqlite3ExprSetColl(sqlite3ExprDup(db,pLeft,0), pColl),
96044                      pStr2, 0);
96045     idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
96046     testcase( idxNew2==0 );
96047     exprAnalyze(pSrc, pWC, idxNew2);
96048     pTerm = &pWC->a[idxTerm];
96049     if( isComplete ){
96050       pWC->a[idxNew1].iParent = idxTerm;
96051       pWC->a[idxNew2].iParent = idxTerm;
96052       pTerm->nChild = 2;
96053     }
96054   }
96055 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
96056
96057 #ifndef SQLITE_OMIT_VIRTUALTABLE
96058   /* Add a WO_MATCH auxiliary term to the constraint set if the
96059   ** current expression is of the form:  column MATCH expr.
96060   ** This information is used by the xBestIndex methods of
96061   ** virtual tables.  The native query optimizer does not attempt
96062   ** to do anything with MATCH functions.
96063   */
96064   if( isMatchOfColumn(pExpr) ){
96065     int idxNew;
96066     Expr *pRight, *pLeft;
96067     WhereTerm *pNewTerm;
96068     Bitmask prereqColumn, prereqExpr;
96069
96070     pRight = pExpr->x.pList->a[0].pExpr;
96071     pLeft = pExpr->x.pList->a[1].pExpr;
96072     prereqExpr = exprTableUsage(pMaskSet, pRight);
96073     prereqColumn = exprTableUsage(pMaskSet, pLeft);
96074     if( (prereqExpr & prereqColumn)==0 ){
96075       Expr *pNewExpr;
96076       pNewExpr = sqlite3PExpr(pParse, TK_MATCH, 
96077                               0, sqlite3ExprDup(db, pRight, 0), 0);
96078       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
96079       testcase( idxNew==0 );
96080       pNewTerm = &pWC->a[idxNew];
96081       pNewTerm->prereqRight = prereqExpr;
96082       pNewTerm->leftCursor = pLeft->iTable;
96083       pNewTerm->u.leftColumn = pLeft->iColumn;
96084       pNewTerm->eOperator = WO_MATCH;
96085       pNewTerm->iParent = idxTerm;
96086       pTerm = &pWC->a[idxTerm];
96087       pTerm->nChild = 1;
96088       pTerm->wtFlags |= TERM_COPIED;
96089       pNewTerm->prereqAll = pTerm->prereqAll;
96090     }
96091   }
96092 #endif /* SQLITE_OMIT_VIRTUALTABLE */
96093
96094   /* Prevent ON clause terms of a LEFT JOIN from being used to drive
96095   ** an index for tables to the left of the join.
96096   */
96097   pTerm->prereqRight |= extraRight;
96098 }
96099
96100 /*
96101 ** Return TRUE if any of the expressions in pList->a[iFirst...] contain
96102 ** a reference to any table other than the iBase table.
96103 */
96104 static int referencesOtherTables(
96105   ExprList *pList,          /* Search expressions in ths list */
96106   WhereMaskSet *pMaskSet,   /* Mapping from tables to bitmaps */
96107   int iFirst,               /* Be searching with the iFirst-th expression */
96108   int iBase                 /* Ignore references to this table */
96109 ){
96110   Bitmask allowed = ~getMask(pMaskSet, iBase);
96111   while( iFirst<pList->nExpr ){
96112     if( (exprTableUsage(pMaskSet, pList->a[iFirst++].pExpr)&allowed)!=0 ){
96113       return 1;
96114     }
96115   }
96116   return 0;
96117 }
96118
96119
96120 /*
96121 ** This routine decides if pIdx can be used to satisfy the ORDER BY
96122 ** clause.  If it can, it returns 1.  If pIdx cannot satisfy the
96123 ** ORDER BY clause, this routine returns 0.
96124 **
96125 ** pOrderBy is an ORDER BY clause from a SELECT statement.  pTab is the
96126 ** left-most table in the FROM clause of that same SELECT statement and
96127 ** the table has a cursor number of "base".  pIdx is an index on pTab.
96128 **
96129 ** nEqCol is the number of columns of pIdx that are used as equality
96130 ** constraints.  Any of these columns may be missing from the ORDER BY
96131 ** clause and the match can still be a success.
96132 **
96133 ** All terms of the ORDER BY that match against the index must be either
96134 ** ASC or DESC.  (Terms of the ORDER BY clause past the end of a UNIQUE
96135 ** index do not need to satisfy this constraint.)  The *pbRev value is
96136 ** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
96137 ** the ORDER BY clause is all ASC.
96138 */
96139 static int isSortingIndex(
96140   Parse *pParse,          /* Parsing context */
96141   WhereMaskSet *pMaskSet, /* Mapping from table cursor numbers to bitmaps */
96142   Index *pIdx,            /* The index we are testing */
96143   int base,               /* Cursor number for the table to be sorted */
96144   ExprList *pOrderBy,     /* The ORDER BY clause */
96145   int nEqCol,             /* Number of index columns with == constraints */
96146   int *pbRev              /* Set to 1 if ORDER BY is DESC */
96147 ){
96148   int i, j;                       /* Loop counters */
96149   int sortOrder = 0;              /* XOR of index and ORDER BY sort direction */
96150   int nTerm;                      /* Number of ORDER BY terms */
96151   struct ExprList_item *pTerm;    /* A term of the ORDER BY clause */
96152   sqlite3 *db = pParse->db;
96153
96154   assert( pOrderBy!=0 );
96155   nTerm = pOrderBy->nExpr;
96156   assert( nTerm>0 );
96157
96158   /* Argument pIdx must either point to a 'real' named index structure, 
96159   ** or an index structure allocated on the stack by bestBtreeIndex() to
96160   ** represent the rowid index that is part of every table.  */
96161   assert( pIdx->zName || (pIdx->nColumn==1 && pIdx->aiColumn[0]==-1) );
96162
96163   /* Match terms of the ORDER BY clause against columns of
96164   ** the index.
96165   **
96166   ** Note that indices have pIdx->nColumn regular columns plus
96167   ** one additional column containing the rowid.  The rowid column
96168   ** of the index is also allowed to match against the ORDER BY
96169   ** clause.
96170   */
96171   for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<=pIdx->nColumn; i++){
96172     Expr *pExpr;       /* The expression of the ORDER BY pTerm */
96173     CollSeq *pColl;    /* The collating sequence of pExpr */
96174     int termSortOrder; /* Sort order for this term */
96175     int iColumn;       /* The i-th column of the index.  -1 for rowid */
96176     int iSortOrder;    /* 1 for DESC, 0 for ASC on the i-th index term */
96177     const char *zColl; /* Name of the collating sequence for i-th index term */
96178
96179     pExpr = pTerm->pExpr;
96180     if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
96181       /* Can not use an index sort on anything that is not a column in the
96182       ** left-most table of the FROM clause */
96183       break;
96184     }
96185     pColl = sqlite3ExprCollSeq(pParse, pExpr);
96186     if( !pColl ){
96187       pColl = db->pDfltColl;
96188     }
96189     if( pIdx->zName && i<pIdx->nColumn ){
96190       iColumn = pIdx->aiColumn[i];
96191       if( iColumn==pIdx->pTable->iPKey ){
96192         iColumn = -1;
96193       }
96194       iSortOrder = pIdx->aSortOrder[i];
96195       zColl = pIdx->azColl[i];
96196     }else{
96197       iColumn = -1;
96198       iSortOrder = 0;
96199       zColl = pColl->zName;
96200     }
96201     if( pExpr->iColumn!=iColumn || sqlite3StrICmp(pColl->zName, zColl) ){
96202       /* Term j of the ORDER BY clause does not match column i of the index */
96203       if( i<nEqCol ){
96204         /* If an index column that is constrained by == fails to match an
96205         ** ORDER BY term, that is OK.  Just ignore that column of the index
96206         */
96207         continue;
96208       }else if( i==pIdx->nColumn ){
96209         /* Index column i is the rowid.  All other terms match. */
96210         break;
96211       }else{
96212         /* If an index column fails to match and is not constrained by ==
96213         ** then the index cannot satisfy the ORDER BY constraint.
96214         */
96215         return 0;
96216       }
96217     }
96218     assert( pIdx->aSortOrder!=0 || iColumn==-1 );
96219     assert( pTerm->sortOrder==0 || pTerm->sortOrder==1 );
96220     assert( iSortOrder==0 || iSortOrder==1 );
96221     termSortOrder = iSortOrder ^ pTerm->sortOrder;
96222     if( i>nEqCol ){
96223       if( termSortOrder!=sortOrder ){
96224         /* Indices can only be used if all ORDER BY terms past the
96225         ** equality constraints are all either DESC or ASC. */
96226         return 0;
96227       }
96228     }else{
96229       sortOrder = termSortOrder;
96230     }
96231     j++;
96232     pTerm++;
96233     if( iColumn<0 && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
96234       /* If the indexed column is the primary key and everything matches
96235       ** so far and none of the ORDER BY terms to the right reference other
96236       ** tables in the join, then we are assured that the index can be used 
96237       ** to sort because the primary key is unique and so none of the other
96238       ** columns will make any difference
96239       */
96240       j = nTerm;
96241     }
96242   }
96243
96244   *pbRev = sortOrder!=0;
96245   if( j>=nTerm ){
96246     /* All terms of the ORDER BY clause are covered by this index so
96247     ** this index can be used for sorting. */
96248     return 1;
96249   }
96250   if( pIdx->onError!=OE_None && i==pIdx->nColumn
96251       && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
96252     /* All terms of this index match some prefix of the ORDER BY clause
96253     ** and the index is UNIQUE and no terms on the tail of the ORDER BY
96254     ** clause reference other tables in a join.  If this is all true then
96255     ** the order by clause is superfluous. */
96256     return 1;
96257   }
96258   return 0;
96259 }
96260
96261 /*
96262 ** Prepare a crude estimate of the logarithm of the input value.
96263 ** The results need not be exact.  This is only used for estimating
96264 ** the total cost of performing operations with O(logN) or O(NlogN)
96265 ** complexity.  Because N is just a guess, it is no great tragedy if
96266 ** logN is a little off.
96267 */
96268 static double estLog(double N){
96269   double logN = 1;
96270   double x = 10;
96271   while( N>x ){
96272     logN += 1;
96273     x *= 10;
96274   }
96275   return logN;
96276 }
96277
96278 /*
96279 ** Two routines for printing the content of an sqlite3_index_info
96280 ** structure.  Used for testing and debugging only.  If neither
96281 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
96282 ** are no-ops.
96283 */
96284 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG)
96285 static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
96286   int i;
96287   if( !sqlite3WhereTrace ) return;
96288   for(i=0; i<p->nConstraint; i++){
96289     sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
96290        i,
96291        p->aConstraint[i].iColumn,
96292        p->aConstraint[i].iTermOffset,
96293        p->aConstraint[i].op,
96294        p->aConstraint[i].usable);
96295   }
96296   for(i=0; i<p->nOrderBy; i++){
96297     sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
96298        i,
96299        p->aOrderBy[i].iColumn,
96300        p->aOrderBy[i].desc);
96301   }
96302 }
96303 static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
96304   int i;
96305   if( !sqlite3WhereTrace ) return;
96306   for(i=0; i<p->nConstraint; i++){
96307     sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
96308        i,
96309        p->aConstraintUsage[i].argvIndex,
96310        p->aConstraintUsage[i].omit);
96311   }
96312   sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
96313   sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
96314   sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
96315   sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
96316 }
96317 #else
96318 #define TRACE_IDX_INPUTS(A)
96319 #define TRACE_IDX_OUTPUTS(A)
96320 #endif
96321
96322 /* 
96323 ** Required because bestIndex() is called by bestOrClauseIndex() 
96324 */
96325 static void bestIndex(
96326     Parse*, WhereClause*, struct SrcList_item*,
96327     Bitmask, Bitmask, ExprList*, WhereCost*);
96328
96329 /*
96330 ** This routine attempts to find an scanning strategy that can be used 
96331 ** to optimize an 'OR' expression that is part of a WHERE clause. 
96332 **
96333 ** The table associated with FROM clause term pSrc may be either a
96334 ** regular B-Tree table or a virtual table.
96335 */
96336 static void bestOrClauseIndex(
96337   Parse *pParse,              /* The parsing context */
96338   WhereClause *pWC,           /* The WHERE clause */
96339   struct SrcList_item *pSrc,  /* The FROM clause term to search */
96340   Bitmask notReady,           /* Mask of cursors not available for indexing */
96341   Bitmask notValid,           /* Cursors not available for any purpose */
96342   ExprList *pOrderBy,         /* The ORDER BY clause */
96343   WhereCost *pCost            /* Lowest cost query plan */
96344 ){
96345 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
96346   const int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
96347   const Bitmask maskSrc = getMask(pWC->pMaskSet, iCur);  /* Bitmask for pSrc */
96348   WhereTerm * const pWCEnd = &pWC->a[pWC->nTerm];        /* End of pWC->a[] */
96349   WhereTerm *pTerm;                 /* A single term of the WHERE clause */
96350
96351   /* No OR-clause optimization allowed if the NOT INDEXED clause is used */
96352   if( pSrc->notIndexed ){
96353     return;
96354   }
96355
96356   /* Search the WHERE clause terms for a usable WO_OR term. */
96357   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
96358     if( pTerm->eOperator==WO_OR 
96359      && ((pTerm->prereqAll & ~maskSrc) & notReady)==0
96360      && (pTerm->u.pOrInfo->indexable & maskSrc)!=0 
96361     ){
96362       WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
96363       WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
96364       WhereTerm *pOrTerm;
96365       int flags = WHERE_MULTI_OR;
96366       double rTotal = 0;
96367       double nRow = 0;
96368       Bitmask used = 0;
96369
96370       for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
96371         WhereCost sTermCost;
96372         WHERETRACE(("... Multi-index OR testing for term %d of %d....\n", 
96373           (pOrTerm - pOrWC->a), (pTerm - pWC->a)
96374         ));
96375         if( pOrTerm->eOperator==WO_AND ){
96376           WhereClause *pAndWC = &pOrTerm->u.pAndInfo->wc;
96377           bestIndex(pParse, pAndWC, pSrc, notReady, notValid, 0, &sTermCost);
96378         }else if( pOrTerm->leftCursor==iCur ){
96379           WhereClause tempWC;
96380           tempWC.pParse = pWC->pParse;
96381           tempWC.pMaskSet = pWC->pMaskSet;
96382           tempWC.op = TK_AND;
96383           tempWC.a = pOrTerm;
96384           tempWC.nTerm = 1;
96385           bestIndex(pParse, &tempWC, pSrc, notReady, notValid, 0, &sTermCost);
96386         }else{
96387           continue;
96388         }
96389         rTotal += sTermCost.rCost;
96390         nRow += sTermCost.nRow;
96391         used |= sTermCost.used;
96392         if( rTotal>=pCost->rCost ) break;
96393       }
96394
96395       /* If there is an ORDER BY clause, increase the scan cost to account 
96396       ** for the cost of the sort. */
96397       if( pOrderBy!=0 ){
96398         WHERETRACE(("... sorting increases OR cost %.9g to %.9g\n",
96399                     rTotal, rTotal+nRow*estLog(nRow)));
96400         rTotal += nRow*estLog(nRow);
96401       }
96402
96403       /* If the cost of scanning using this OR term for optimization is
96404       ** less than the current cost stored in pCost, replace the contents
96405       ** of pCost. */
96406       WHERETRACE(("... multi-index OR cost=%.9g nrow=%.9g\n", rTotal, nRow));
96407       if( rTotal<pCost->rCost ){
96408         pCost->rCost = rTotal;
96409         pCost->nRow = nRow;
96410         pCost->used = used;
96411         pCost->plan.wsFlags = flags;
96412         pCost->plan.u.pTerm = pTerm;
96413       }
96414     }
96415   }
96416 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
96417 }
96418
96419 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
96420 /*
96421 ** Return TRUE if the WHERE clause term pTerm is of a form where it
96422 ** could be used with an index to access pSrc, assuming an appropriate
96423 ** index existed.
96424 */
96425 static int termCanDriveIndex(
96426   WhereTerm *pTerm,              /* WHERE clause term to check */
96427   struct SrcList_item *pSrc,     /* Table we are trying to access */
96428   Bitmask notReady               /* Tables in outer loops of the join */
96429 ){
96430   char aff;
96431   if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
96432   if( pTerm->eOperator!=WO_EQ ) return 0;
96433   if( (pTerm->prereqRight & notReady)!=0 ) return 0;
96434   aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
96435   if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
96436   return 1;
96437 }
96438 #endif
96439
96440 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
96441 /*
96442 ** If the query plan for pSrc specified in pCost is a full table scan
96443 ** and indexing is allows (if there is no NOT INDEXED clause) and it
96444 ** possible to construct a transient index that would perform better
96445 ** than a full table scan even when the cost of constructing the index
96446 ** is taken into account, then alter the query plan to use the
96447 ** transient index.
96448 */
96449 static void bestAutomaticIndex(
96450   Parse *pParse,              /* The parsing context */
96451   WhereClause *pWC,           /* The WHERE clause */
96452   struct SrcList_item *pSrc,  /* The FROM clause term to search */
96453   Bitmask notReady,           /* Mask of cursors that are not available */
96454   WhereCost *pCost            /* Lowest cost query plan */
96455 ){
96456   double nTableRow;           /* Rows in the input table */
96457   double logN;                /* log(nTableRow) */
96458   double costTempIdx;         /* per-query cost of the transient index */
96459   WhereTerm *pTerm;           /* A single term of the WHERE clause */
96460   WhereTerm *pWCEnd;          /* End of pWC->a[] */
96461   Table *pTable;              /* Table tht might be indexed */
96462
96463   if( (pParse->db->flags & SQLITE_AutoIndex)==0 ){
96464     /* Automatic indices are disabled at run-time */
96465     return;
96466   }
96467   if( (pCost->plan.wsFlags & WHERE_NOT_FULLSCAN)!=0 ){
96468     /* We already have some kind of index in use for this query. */
96469     return;
96470   }
96471   if( pSrc->notIndexed ){
96472     /* The NOT INDEXED clause appears in the SQL. */
96473     return;
96474   }
96475
96476   assert( pParse->nQueryLoop >= (double)1 );
96477   pTable = pSrc->pTab;
96478   nTableRow = pTable->nRowEst;
96479   logN = estLog(nTableRow);
96480   costTempIdx = 2*logN*(nTableRow/pParse->nQueryLoop + 1);
96481   if( costTempIdx>=pCost->rCost ){
96482     /* The cost of creating the transient table would be greater than
96483     ** doing the full table scan */
96484     return;
96485   }
96486
96487   /* Search for any equality comparison term */
96488   pWCEnd = &pWC->a[pWC->nTerm];
96489   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
96490     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
96491       WHERETRACE(("auto-index reduces cost from %.2f to %.2f\n",
96492                     pCost->rCost, costTempIdx));
96493       pCost->rCost = costTempIdx;
96494       pCost->nRow = logN + 1;
96495       pCost->plan.wsFlags = WHERE_TEMP_INDEX;
96496       pCost->used = pTerm->prereqRight;
96497       break;
96498     }
96499   }
96500 }
96501 #else
96502 # define bestAutomaticIndex(A,B,C,D,E)  /* no-op */
96503 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
96504
96505
96506 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
96507 /*
96508 ** Generate code to construct the Index object for an automatic index
96509 ** and to set up the WhereLevel object pLevel so that the code generator
96510 ** makes use of the automatic index.
96511 */
96512 static void constructAutomaticIndex(
96513   Parse *pParse,              /* The parsing context */
96514   WhereClause *pWC,           /* The WHERE clause */
96515   struct SrcList_item *pSrc,  /* The FROM clause term to get the next index */
96516   Bitmask notReady,           /* Mask of cursors that are not available */
96517   WhereLevel *pLevel          /* Write new index here */
96518 ){
96519   int nColumn;                /* Number of columns in the constructed index */
96520   WhereTerm *pTerm;           /* A single term of the WHERE clause */
96521   WhereTerm *pWCEnd;          /* End of pWC->a[] */
96522   int nByte;                  /* Byte of memory needed for pIdx */
96523   Index *pIdx;                /* Object describing the transient index */
96524   Vdbe *v;                    /* Prepared statement under construction */
96525   int regIsInit;              /* Register set by initialization */
96526   int addrInit;               /* Address of the initialization bypass jump */
96527   Table *pTable;              /* The table being indexed */
96528   KeyInfo *pKeyinfo;          /* Key information for the index */   
96529   int addrTop;                /* Top of the index fill loop */
96530   int regRecord;              /* Register holding an index record */
96531   int n;                      /* Column counter */
96532   int i;                      /* Loop counter */
96533   int mxBitCol;               /* Maximum column in pSrc->colUsed */
96534   CollSeq *pColl;             /* Collating sequence to on a column */
96535   Bitmask idxCols;            /* Bitmap of columns used for indexing */
96536   Bitmask extraCols;          /* Bitmap of additional columns */
96537
96538   /* Generate code to skip over the creation and initialization of the
96539   ** transient index on 2nd and subsequent iterations of the loop. */
96540   v = pParse->pVdbe;
96541   assert( v!=0 );
96542   regIsInit = ++pParse->nMem;
96543   addrInit = sqlite3VdbeAddOp1(v, OP_If, regIsInit);
96544   sqlite3VdbeAddOp2(v, OP_Integer, 1, regIsInit);
96545
96546   /* Count the number of columns that will be added to the index
96547   ** and used to match WHERE clause constraints */
96548   nColumn = 0;
96549   pTable = pSrc->pTab;
96550   pWCEnd = &pWC->a[pWC->nTerm];
96551   idxCols = 0;
96552   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
96553     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
96554       int iCol = pTerm->u.leftColumn;
96555       Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
96556       testcase( iCol==BMS );
96557       testcase( iCol==BMS-1 );
96558       if( (idxCols & cMask)==0 ){
96559         nColumn++;
96560         idxCols |= cMask;
96561       }
96562     }
96563   }
96564   assert( nColumn>0 );
96565   pLevel->plan.nEq = nColumn;
96566
96567   /* Count the number of additional columns needed to create a
96568   ** covering index.  A "covering index" is an index that contains all
96569   ** columns that are needed by the query.  With a covering index, the
96570   ** original table never needs to be accessed.  Automatic indices must
96571   ** be a covering index because the index will not be updated if the
96572   ** original table changes and the index and table cannot both be used
96573   ** if they go out of sync.
96574   */
96575   extraCols = pSrc->colUsed & (~idxCols | (((Bitmask)1)<<(BMS-1)));
96576   mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
96577   testcase( pTable->nCol==BMS-1 );
96578   testcase( pTable->nCol==BMS-2 );
96579   for(i=0; i<mxBitCol; i++){
96580     if( extraCols & (((Bitmask)1)<<i) ) nColumn++;
96581   }
96582   if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
96583     nColumn += pTable->nCol - BMS + 1;
96584   }
96585   pLevel->plan.wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WO_EQ;
96586
96587   /* Construct the Index object to describe this index */
96588   nByte = sizeof(Index);
96589   nByte += nColumn*sizeof(int);     /* Index.aiColumn */
96590   nByte += nColumn*sizeof(char*);   /* Index.azColl */
96591   nByte += nColumn;                 /* Index.aSortOrder */
96592   pIdx = sqlite3DbMallocZero(pParse->db, nByte);
96593   if( pIdx==0 ) return;
96594   pLevel->plan.u.pIdx = pIdx;
96595   pIdx->azColl = (char**)&pIdx[1];
96596   pIdx->aiColumn = (int*)&pIdx->azColl[nColumn];
96597   pIdx->aSortOrder = (u8*)&pIdx->aiColumn[nColumn];
96598   pIdx->zName = "auto-index";
96599   pIdx->nColumn = nColumn;
96600   pIdx->pTable = pTable;
96601   n = 0;
96602   idxCols = 0;
96603   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
96604     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
96605       int iCol = pTerm->u.leftColumn;
96606       Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
96607       if( (idxCols & cMask)==0 ){
96608         Expr *pX = pTerm->pExpr;
96609         idxCols |= cMask;
96610         pIdx->aiColumn[n] = pTerm->u.leftColumn;
96611         pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
96612         pIdx->azColl[n] = pColl->zName;
96613         n++;
96614       }
96615     }
96616   }
96617   assert( (u32)n==pLevel->plan.nEq );
96618
96619   /* Add additional columns needed to make the automatic index into
96620   ** a covering index */
96621   for(i=0; i<mxBitCol; i++){
96622     if( extraCols & (((Bitmask)1)<<i) ){
96623       pIdx->aiColumn[n] = i;
96624       pIdx->azColl[n] = "BINARY";
96625       n++;
96626     }
96627   }
96628   if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
96629     for(i=BMS-1; i<pTable->nCol; i++){
96630       pIdx->aiColumn[n] = i;
96631       pIdx->azColl[n] = "BINARY";
96632       n++;
96633     }
96634   }
96635   assert( n==nColumn );
96636
96637   /* Create the automatic index */
96638   pKeyinfo = sqlite3IndexKeyinfo(pParse, pIdx);
96639   assert( pLevel->iIdxCur>=0 );
96640   sqlite3VdbeAddOp4(v, OP_OpenAutoindex, pLevel->iIdxCur, nColumn+1, 0,
96641                     (char*)pKeyinfo, P4_KEYINFO_HANDOFF);
96642   VdbeComment((v, "for %s", pTable->zName));
96643
96644   /* Fill the automatic index with content */
96645   addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur);
96646   regRecord = sqlite3GetTempReg(pParse);
96647   sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 1);
96648   sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
96649   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
96650   sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1);
96651   sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
96652   sqlite3VdbeJumpHere(v, addrTop);
96653   sqlite3ReleaseTempReg(pParse, regRecord);
96654   
96655   /* Jump here when skipping the initialization */
96656   sqlite3VdbeJumpHere(v, addrInit);
96657 }
96658 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
96659
96660 #ifndef SQLITE_OMIT_VIRTUALTABLE
96661 /*
96662 ** Allocate and populate an sqlite3_index_info structure. It is the 
96663 ** responsibility of the caller to eventually release the structure
96664 ** by passing the pointer returned by this function to sqlite3_free().
96665 */
96666 static sqlite3_index_info *allocateIndexInfo(
96667   Parse *pParse, 
96668   WhereClause *pWC,
96669   struct SrcList_item *pSrc,
96670   ExprList *pOrderBy
96671 ){
96672   int i, j;
96673   int nTerm;
96674   struct sqlite3_index_constraint *pIdxCons;
96675   struct sqlite3_index_orderby *pIdxOrderBy;
96676   struct sqlite3_index_constraint_usage *pUsage;
96677   WhereTerm *pTerm;
96678   int nOrderBy;
96679   sqlite3_index_info *pIdxInfo;
96680
96681   WHERETRACE(("Recomputing index info for %s...\n", pSrc->pTab->zName));
96682
96683   /* Count the number of possible WHERE clause constraints referring
96684   ** to this virtual table */
96685   for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
96686     if( pTerm->leftCursor != pSrc->iCursor ) continue;
96687     assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
96688     testcase( pTerm->eOperator==WO_IN );
96689     testcase( pTerm->eOperator==WO_ISNULL );
96690     if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
96691     nTerm++;
96692   }
96693
96694   /* If the ORDER BY clause contains only columns in the current 
96695   ** virtual table then allocate space for the aOrderBy part of
96696   ** the sqlite3_index_info structure.
96697   */
96698   nOrderBy = 0;
96699   if( pOrderBy ){
96700     for(i=0; i<pOrderBy->nExpr; i++){
96701       Expr *pExpr = pOrderBy->a[i].pExpr;
96702       if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
96703     }
96704     if( i==pOrderBy->nExpr ){
96705       nOrderBy = pOrderBy->nExpr;
96706     }
96707   }
96708
96709   /* Allocate the sqlite3_index_info structure
96710   */
96711   pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
96712                            + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
96713                            + sizeof(*pIdxOrderBy)*nOrderBy );
96714   if( pIdxInfo==0 ){
96715     sqlite3ErrorMsg(pParse, "out of memory");
96716     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
96717     return 0;
96718   }
96719
96720   /* Initialize the structure.  The sqlite3_index_info structure contains
96721   ** many fields that are declared "const" to prevent xBestIndex from
96722   ** changing them.  We have to do some funky casting in order to
96723   ** initialize those fields.
96724   */
96725   pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
96726   pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
96727   pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
96728   *(int*)&pIdxInfo->nConstraint = nTerm;
96729   *(int*)&pIdxInfo->nOrderBy = nOrderBy;
96730   *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
96731   *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
96732   *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
96733                                                                    pUsage;
96734
96735   for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
96736     if( pTerm->leftCursor != pSrc->iCursor ) continue;
96737     assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
96738     testcase( pTerm->eOperator==WO_IN );
96739     testcase( pTerm->eOperator==WO_ISNULL );
96740     if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
96741     pIdxCons[j].iColumn = pTerm->u.leftColumn;
96742     pIdxCons[j].iTermOffset = i;
96743     pIdxCons[j].op = (u8)pTerm->eOperator;
96744     /* The direct assignment in the previous line is possible only because
96745     ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
96746     ** following asserts verify this fact. */
96747     assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
96748     assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
96749     assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
96750     assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
96751     assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
96752     assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
96753     assert( pTerm->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
96754     j++;
96755   }
96756   for(i=0; i<nOrderBy; i++){
96757     Expr *pExpr = pOrderBy->a[i].pExpr;
96758     pIdxOrderBy[i].iColumn = pExpr->iColumn;
96759     pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
96760   }
96761
96762   return pIdxInfo;
96763 }
96764
96765 /*
96766 ** The table object reference passed as the second argument to this function
96767 ** must represent a virtual table. This function invokes the xBestIndex()
96768 ** method of the virtual table with the sqlite3_index_info pointer passed
96769 ** as the argument.
96770 **
96771 ** If an error occurs, pParse is populated with an error message and a
96772 ** non-zero value is returned. Otherwise, 0 is returned and the output
96773 ** part of the sqlite3_index_info structure is left populated.
96774 **
96775 ** Whether or not an error is returned, it is the responsibility of the
96776 ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
96777 ** that this is required.
96778 */
96779 static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
96780   sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
96781   int i;
96782   int rc;
96783
96784   WHERETRACE(("xBestIndex for %s\n", pTab->zName));
96785   TRACE_IDX_INPUTS(p);
96786   rc = pVtab->pModule->xBestIndex(pVtab, p);
96787   TRACE_IDX_OUTPUTS(p);
96788
96789   if( rc!=SQLITE_OK ){
96790     if( rc==SQLITE_NOMEM ){
96791       pParse->db->mallocFailed = 1;
96792     }else if( !pVtab->zErrMsg ){
96793       sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
96794     }else{
96795       sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
96796     }
96797   }
96798   sqlite3_free(pVtab->zErrMsg);
96799   pVtab->zErrMsg = 0;
96800
96801   for(i=0; i<p->nConstraint; i++){
96802     if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
96803       sqlite3ErrorMsg(pParse, 
96804           "table %s: xBestIndex returned an invalid plan", pTab->zName);
96805     }
96806   }
96807
96808   return pParse->nErr;
96809 }
96810
96811
96812 /*
96813 ** Compute the best index for a virtual table.
96814 **
96815 ** The best index is computed by the xBestIndex method of the virtual
96816 ** table module.  This routine is really just a wrapper that sets up
96817 ** the sqlite3_index_info structure that is used to communicate with
96818 ** xBestIndex.
96819 **
96820 ** In a join, this routine might be called multiple times for the
96821 ** same virtual table.  The sqlite3_index_info structure is created
96822 ** and initialized on the first invocation and reused on all subsequent
96823 ** invocations.  The sqlite3_index_info structure is also used when
96824 ** code is generated to access the virtual table.  The whereInfoDelete() 
96825 ** routine takes care of freeing the sqlite3_index_info structure after
96826 ** everybody has finished with it.
96827 */
96828 static void bestVirtualIndex(
96829   Parse *pParse,                  /* The parsing context */
96830   WhereClause *pWC,               /* The WHERE clause */
96831   struct SrcList_item *pSrc,      /* The FROM clause term to search */
96832   Bitmask notReady,               /* Mask of cursors not available for index */
96833   Bitmask notValid,               /* Cursors not valid for any purpose */
96834   ExprList *pOrderBy,             /* The order by clause */
96835   WhereCost *pCost,               /* Lowest cost query plan */
96836   sqlite3_index_info **ppIdxInfo  /* Index information passed to xBestIndex */
96837 ){
96838   Table *pTab = pSrc->pTab;
96839   sqlite3_index_info *pIdxInfo;
96840   struct sqlite3_index_constraint *pIdxCons;
96841   struct sqlite3_index_constraint_usage *pUsage;
96842   WhereTerm *pTerm;
96843   int i, j;
96844   int nOrderBy;
96845   double rCost;
96846
96847   /* Make sure wsFlags is initialized to some sane value. Otherwise, if the 
96848   ** malloc in allocateIndexInfo() fails and this function returns leaving
96849   ** wsFlags in an uninitialized state, the caller may behave unpredictably.
96850   */
96851   memset(pCost, 0, sizeof(*pCost));
96852   pCost->plan.wsFlags = WHERE_VIRTUALTABLE;
96853
96854   /* If the sqlite3_index_info structure has not been previously
96855   ** allocated and initialized, then allocate and initialize it now.
96856   */
96857   pIdxInfo = *ppIdxInfo;
96858   if( pIdxInfo==0 ){
96859     *ppIdxInfo = pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pOrderBy);
96860   }
96861   if( pIdxInfo==0 ){
96862     return;
96863   }
96864
96865   /* At this point, the sqlite3_index_info structure that pIdxInfo points
96866   ** to will have been initialized, either during the current invocation or
96867   ** during some prior invocation.  Now we just have to customize the
96868   ** details of pIdxInfo for the current invocation and pass it to
96869   ** xBestIndex.
96870   */
96871
96872   /* The module name must be defined. Also, by this point there must
96873   ** be a pointer to an sqlite3_vtab structure. Otherwise
96874   ** sqlite3ViewGetColumnNames() would have picked up the error. 
96875   */
96876   assert( pTab->azModuleArg && pTab->azModuleArg[0] );
96877   assert( sqlite3GetVTable(pParse->db, pTab) );
96878
96879   /* Set the aConstraint[].usable fields and initialize all 
96880   ** output variables to zero.
96881   **
96882   ** aConstraint[].usable is true for constraints where the right-hand
96883   ** side contains only references to tables to the left of the current
96884   ** table.  In other words, if the constraint is of the form:
96885   **
96886   **           column = expr
96887   **
96888   ** and we are evaluating a join, then the constraint on column is 
96889   ** only valid if all tables referenced in expr occur to the left
96890   ** of the table containing column.
96891   **
96892   ** The aConstraints[] array contains entries for all constraints
96893   ** on the current table.  That way we only have to compute it once
96894   ** even though we might try to pick the best index multiple times.
96895   ** For each attempt at picking an index, the order of tables in the
96896   ** join might be different so we have to recompute the usable flag
96897   ** each time.
96898   */
96899   pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
96900   pUsage = pIdxInfo->aConstraintUsage;
96901   for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
96902     j = pIdxCons->iTermOffset;
96903     pTerm = &pWC->a[j];
96904     pIdxCons->usable = (pTerm->prereqRight&notReady) ? 0 : 1;
96905   }
96906   memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
96907   if( pIdxInfo->needToFreeIdxStr ){
96908     sqlite3_free(pIdxInfo->idxStr);
96909   }
96910   pIdxInfo->idxStr = 0;
96911   pIdxInfo->idxNum = 0;
96912   pIdxInfo->needToFreeIdxStr = 0;
96913   pIdxInfo->orderByConsumed = 0;
96914   /* ((double)2) In case of SQLITE_OMIT_FLOATING_POINT... */
96915   pIdxInfo->estimatedCost = SQLITE_BIG_DBL / ((double)2);
96916   nOrderBy = pIdxInfo->nOrderBy;
96917   if( !pOrderBy ){
96918     pIdxInfo->nOrderBy = 0;
96919   }
96920
96921   if( vtabBestIndex(pParse, pTab, pIdxInfo) ){
96922     return;
96923   }
96924
96925   pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
96926   for(i=0; i<pIdxInfo->nConstraint; i++){
96927     if( pUsage[i].argvIndex>0 ){
96928       pCost->used |= pWC->a[pIdxCons[i].iTermOffset].prereqRight;
96929     }
96930   }
96931
96932   /* If there is an ORDER BY clause, and the selected virtual table index
96933   ** does not satisfy it, increase the cost of the scan accordingly. This
96934   ** matches the processing for non-virtual tables in bestBtreeIndex().
96935   */
96936   rCost = pIdxInfo->estimatedCost;
96937   if( pOrderBy && pIdxInfo->orderByConsumed==0 ){
96938     rCost += estLog(rCost)*rCost;
96939   }
96940
96941   /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
96942   ** inital value of lowestCost in this loop. If it is, then the
96943   ** (cost<lowestCost) test below will never be true.
96944   ** 
96945   ** Use "(double)2" instead of "2.0" in case OMIT_FLOATING_POINT 
96946   ** is defined.
96947   */
96948   if( (SQLITE_BIG_DBL/((double)2))<rCost ){
96949     pCost->rCost = (SQLITE_BIG_DBL/((double)2));
96950   }else{
96951     pCost->rCost = rCost;
96952   }
96953   pCost->plan.u.pVtabIdx = pIdxInfo;
96954   if( pIdxInfo->orderByConsumed ){
96955     pCost->plan.wsFlags |= WHERE_ORDERBY;
96956   }
96957   pCost->plan.nEq = 0;
96958   pIdxInfo->nOrderBy = nOrderBy;
96959
96960   /* Try to find a more efficient access pattern by using multiple indexes
96961   ** to optimize an OR expression within the WHERE clause. 
96962   */
96963   bestOrClauseIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost);
96964 }
96965 #endif /* SQLITE_OMIT_VIRTUALTABLE */
96966
96967 /*
96968 ** Argument pIdx is a pointer to an index structure that has an array of
96969 ** SQLITE_INDEX_SAMPLES evenly spaced samples of the first indexed column
96970 ** stored in Index.aSample. The domain of values stored in said column
96971 ** may be thought of as divided into (SQLITE_INDEX_SAMPLES+1) regions.
96972 ** Region 0 contains all values smaller than the first sample value. Region
96973 ** 1 contains values larger than or equal to the value of the first sample,
96974 ** but smaller than the value of the second. And so on.
96975 **
96976 ** If successful, this function determines which of the regions value 
96977 ** pVal lies in, sets *piRegion to the region index (a value between 0
96978 ** and SQLITE_INDEX_SAMPLES+1, inclusive) and returns SQLITE_OK.
96979 ** Or, if an OOM occurs while converting text values between encodings,
96980 ** SQLITE_NOMEM is returned and *piRegion is undefined.
96981 */
96982 #ifdef SQLITE_ENABLE_STAT2
96983 static int whereRangeRegion(
96984   Parse *pParse,              /* Database connection */
96985   Index *pIdx,                /* Index to consider domain of */
96986   sqlite3_value *pVal,        /* Value to consider */
96987   int *piRegion               /* OUT: Region of domain in which value lies */
96988 ){
96989   if( ALWAYS(pVal) ){
96990     IndexSample *aSample = pIdx->aSample;
96991     int i = 0;
96992     int eType = sqlite3_value_type(pVal);
96993
96994     if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
96995       double r = sqlite3_value_double(pVal);
96996       for(i=0; i<SQLITE_INDEX_SAMPLES; i++){
96997         if( aSample[i].eType==SQLITE_NULL ) continue;
96998         if( aSample[i].eType>=SQLITE_TEXT || aSample[i].u.r>r ) break;
96999       }
97000     }else{ 
97001       sqlite3 *db = pParse->db;
97002       CollSeq *pColl;
97003       const u8 *z;
97004       int n;
97005
97006       /* pVal comes from sqlite3ValueFromExpr() so the type cannot be NULL */
97007       assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
97008
97009       if( eType==SQLITE_BLOB ){
97010         z = (const u8 *)sqlite3_value_blob(pVal);
97011         pColl = db->pDfltColl;
97012         assert( pColl->enc==SQLITE_UTF8 );
97013       }else{
97014         pColl = sqlite3GetCollSeq(db, SQLITE_UTF8, 0, *pIdx->azColl);
97015         if( pColl==0 ){
97016           sqlite3ErrorMsg(pParse, "no such collation sequence: %s",
97017                           *pIdx->azColl);
97018           return SQLITE_ERROR;
97019         }
97020         z = (const u8 *)sqlite3ValueText(pVal, pColl->enc);
97021         if( !z ){
97022           return SQLITE_NOMEM;
97023         }
97024         assert( z && pColl && pColl->xCmp );
97025       }
97026       n = sqlite3ValueBytes(pVal, pColl->enc);
97027
97028       for(i=0; i<SQLITE_INDEX_SAMPLES; i++){
97029         int r;
97030         int eSampletype = aSample[i].eType;
97031         if( eSampletype==SQLITE_NULL || eSampletype<eType ) continue;
97032         if( (eSampletype!=eType) ) break;
97033 #ifndef SQLITE_OMIT_UTF16
97034         if( pColl->enc!=SQLITE_UTF8 ){
97035           int nSample;
97036           char *zSample = sqlite3Utf8to16(
97037               db, pColl->enc, aSample[i].u.z, aSample[i].nByte, &nSample
97038           );
97039           if( !zSample ){
97040             assert( db->mallocFailed );
97041             return SQLITE_NOMEM;
97042           }
97043           r = pColl->xCmp(pColl->pUser, nSample, zSample, n, z);
97044           sqlite3DbFree(db, zSample);
97045         }else
97046 #endif
97047         {
97048           r = pColl->xCmp(pColl->pUser, aSample[i].nByte, aSample[i].u.z, n, z);
97049         }
97050         if( r>0 ) break;
97051       }
97052     }
97053
97054     assert( i>=0 && i<=SQLITE_INDEX_SAMPLES );
97055     *piRegion = i;
97056   }
97057   return SQLITE_OK;
97058 }
97059 #endif   /* #ifdef SQLITE_ENABLE_STAT2 */
97060
97061 /*
97062 ** If expression pExpr represents a literal value, set *pp to point to
97063 ** an sqlite3_value structure containing the same value, with affinity
97064 ** aff applied to it, before returning. It is the responsibility of the 
97065 ** caller to eventually release this structure by passing it to 
97066 ** sqlite3ValueFree().
97067 **
97068 ** If the current parse is a recompile (sqlite3Reprepare()) and pExpr
97069 ** is an SQL variable that currently has a non-NULL value bound to it,
97070 ** create an sqlite3_value structure containing this value, again with
97071 ** affinity aff applied to it, instead.
97072 **
97073 ** If neither of the above apply, set *pp to NULL.
97074 **
97075 ** If an error occurs, return an error code. Otherwise, SQLITE_OK.
97076 */
97077 #ifdef SQLITE_ENABLE_STAT2
97078 static int valueFromExpr(
97079   Parse *pParse, 
97080   Expr *pExpr, 
97081   u8 aff, 
97082   sqlite3_value **pp
97083 ){
97084   /* The evalConstExpr() function will have already converted any TK_VARIABLE
97085   ** expression involved in an comparison into a TK_REGISTER. */
97086   assert( pExpr->op!=TK_VARIABLE );
97087   if( pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE ){
97088     int iVar = pExpr->iColumn;
97089     sqlite3VdbeSetVarmask(pParse->pVdbe, iVar); /* IMP: R-23257-02778 */
97090     *pp = sqlite3VdbeGetValue(pParse->pReprepare, iVar, aff);
97091     return SQLITE_OK;
97092   }
97093   return sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, aff, pp);
97094 }
97095 #endif
97096
97097 /*
97098 ** This function is used to estimate the number of rows that will be visited
97099 ** by scanning an index for a range of values. The range may have an upper
97100 ** bound, a lower bound, or both. The WHERE clause terms that set the upper
97101 ** and lower bounds are represented by pLower and pUpper respectively. For
97102 ** example, assuming that index p is on t1(a):
97103 **
97104 **   ... FROM t1 WHERE a > ? AND a < ? ...
97105 **                    |_____|   |_____|
97106 **                       |         |
97107 **                     pLower    pUpper
97108 **
97109 ** If either of the upper or lower bound is not present, then NULL is passed in
97110 ** place of the corresponding WhereTerm.
97111 **
97112 ** The nEq parameter is passed the index of the index column subject to the
97113 ** range constraint. Or, equivalently, the number of equality constraints
97114 ** optimized by the proposed index scan. For example, assuming index p is
97115 ** on t1(a, b), and the SQL query is:
97116 **
97117 **   ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
97118 **
97119 ** then nEq should be passed the value 1 (as the range restricted column,
97120 ** b, is the second left-most column of the index). Or, if the query is:
97121 **
97122 **   ... FROM t1 WHERE a > ? AND a < ? ...
97123 **
97124 ** then nEq should be passed 0.
97125 **
97126 ** The returned value is an integer between 1 and 100, inclusive. A return
97127 ** value of 1 indicates that the proposed range scan is expected to visit
97128 ** approximately 1/100th (1%) of the rows selected by the nEq equality
97129 ** constraints (if any). A return value of 100 indicates that it is expected
97130 ** that the range scan will visit every row (100%) selected by the equality
97131 ** constraints.
97132 **
97133 ** In the absence of sqlite_stat2 ANALYZE data, each range inequality
97134 ** reduces the search space by 2/3rds.  Hence a single constraint (x>?)
97135 ** results in a return of 33 and a range constraint (x>? AND x<?) results
97136 ** in a return of 11.
97137 */
97138 static int whereRangeScanEst(
97139   Parse *pParse,       /* Parsing & code generating context */
97140   Index *p,            /* The index containing the range-compared column; "x" */
97141   int nEq,             /* index into p->aCol[] of the range-compared column */
97142   WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
97143   WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
97144   int *piEst           /* OUT: Return value */
97145 ){
97146   int rc = SQLITE_OK;
97147
97148 #ifdef SQLITE_ENABLE_STAT2
97149
97150   if( nEq==0 && p->aSample ){
97151     sqlite3_value *pLowerVal = 0;
97152     sqlite3_value *pUpperVal = 0;
97153     int iEst;
97154     int iLower = 0;
97155     int iUpper = SQLITE_INDEX_SAMPLES;
97156     u8 aff = p->pTable->aCol[p->aiColumn[0]].affinity;
97157
97158     if( pLower ){
97159       Expr *pExpr = pLower->pExpr->pRight;
97160       rc = valueFromExpr(pParse, pExpr, aff, &pLowerVal);
97161     }
97162     if( rc==SQLITE_OK && pUpper ){
97163       Expr *pExpr = pUpper->pExpr->pRight;
97164       rc = valueFromExpr(pParse, pExpr, aff, &pUpperVal);
97165     }
97166
97167     if( rc!=SQLITE_OK || (pLowerVal==0 && pUpperVal==0) ){
97168       sqlite3ValueFree(pLowerVal);
97169       sqlite3ValueFree(pUpperVal);
97170       goto range_est_fallback;
97171     }else if( pLowerVal==0 ){
97172       rc = whereRangeRegion(pParse, p, pUpperVal, &iUpper);
97173       if( pLower ) iLower = iUpper/2;
97174     }else if( pUpperVal==0 ){
97175       rc = whereRangeRegion(pParse, p, pLowerVal, &iLower);
97176       if( pUpper ) iUpper = (iLower + SQLITE_INDEX_SAMPLES + 1)/2;
97177     }else{
97178       rc = whereRangeRegion(pParse, p, pUpperVal, &iUpper);
97179       if( rc==SQLITE_OK ){
97180         rc = whereRangeRegion(pParse, p, pLowerVal, &iLower);
97181       }
97182     }
97183
97184     iEst = iUpper - iLower;
97185     testcase( iEst==SQLITE_INDEX_SAMPLES );
97186     assert( iEst<=SQLITE_INDEX_SAMPLES );
97187     if( iEst<1 ){
97188       iEst = 1;
97189     }
97190
97191     sqlite3ValueFree(pLowerVal);
97192     sqlite3ValueFree(pUpperVal);
97193     *piEst = (iEst * 100)/SQLITE_INDEX_SAMPLES;
97194     return rc;
97195   }
97196 range_est_fallback:
97197 #else
97198   UNUSED_PARAMETER(pParse);
97199   UNUSED_PARAMETER(p);
97200   UNUSED_PARAMETER(nEq);
97201 #endif
97202   assert( pLower || pUpper );
97203   if( pLower && pUpper ){
97204     *piEst = 11;
97205   }else{
97206     *piEst = 33;
97207   }
97208   return rc;
97209 }
97210
97211
97212 /*
97213 ** Find the query plan for accessing a particular table.  Write the
97214 ** best query plan and its cost into the WhereCost object supplied as the
97215 ** last parameter.
97216 **
97217 ** The lowest cost plan wins.  The cost is an estimate of the amount of
97218 ** CPU and disk I/O need to process the request using the selected plan.
97219 ** Factors that influence cost include:
97220 **
97221 **    *  The estimated number of rows that will be retrieved.  (The
97222 **       fewer the better.)
97223 **
97224 **    *  Whether or not sorting must occur.
97225 **
97226 **    *  Whether or not there must be separate lookups in the
97227 **       index and in the main table.
97228 **
97229 ** If there was an INDEXED BY clause (pSrc->pIndex) attached to the table in
97230 ** the SQL statement, then this function only considers plans using the 
97231 ** named index. If no such plan is found, then the returned cost is
97232 ** SQLITE_BIG_DBL. If a plan is found that uses the named index, 
97233 ** then the cost is calculated in the usual way.
97234 **
97235 ** If a NOT INDEXED clause (pSrc->notIndexed!=0) was attached to the table 
97236 ** in the SELECT statement, then no indexes are considered. However, the 
97237 ** selected plan may still take advantage of the tables built-in rowid
97238 ** index.
97239 */
97240 static void bestBtreeIndex(
97241   Parse *pParse,              /* The parsing context */
97242   WhereClause *pWC,           /* The WHERE clause */
97243   struct SrcList_item *pSrc,  /* The FROM clause term to search */
97244   Bitmask notReady,           /* Mask of cursors not available for indexing */
97245   Bitmask notValid,           /* Cursors not available for any purpose */
97246   ExprList *pOrderBy,         /* The ORDER BY clause */
97247   WhereCost *pCost            /* Lowest cost query plan */
97248 ){
97249   int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
97250   Index *pProbe;              /* An index we are evaluating */
97251   Index *pIdx;                /* Copy of pProbe, or zero for IPK index */
97252   int eqTermMask;             /* Current mask of valid equality operators */
97253   int idxEqTermMask;          /* Index mask of valid equality operators */
97254   Index sPk;                  /* A fake index object for the primary key */
97255   unsigned int aiRowEstPk[2]; /* The aiRowEst[] value for the sPk index */
97256   int aiColumnPk = -1;        /* The aColumn[] value for the sPk index */
97257   int wsFlagMask;             /* Allowed flags in pCost->plan.wsFlag */
97258
97259   /* Initialize the cost to a worst-case value */
97260   memset(pCost, 0, sizeof(*pCost));
97261   pCost->rCost = SQLITE_BIG_DBL;
97262
97263   /* If the pSrc table is the right table of a LEFT JOIN then we may not
97264   ** use an index to satisfy IS NULL constraints on that table.  This is
97265   ** because columns might end up being NULL if the table does not match -
97266   ** a circumstance which the index cannot help us discover.  Ticket #2177.
97267   */
97268   if( pSrc->jointype & JT_LEFT ){
97269     idxEqTermMask = WO_EQ|WO_IN;
97270   }else{
97271     idxEqTermMask = WO_EQ|WO_IN|WO_ISNULL;
97272   }
97273
97274   if( pSrc->pIndex ){
97275     /* An INDEXED BY clause specifies a particular index to use */
97276     pIdx = pProbe = pSrc->pIndex;
97277     wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
97278     eqTermMask = idxEqTermMask;
97279   }else{
97280     /* There is no INDEXED BY clause.  Create a fake Index object to
97281     ** represent the primary key */
97282     Index *pFirst;                /* Any other index on the table */
97283     memset(&sPk, 0, sizeof(Index));
97284     sPk.nColumn = 1;
97285     sPk.aiColumn = &aiColumnPk;
97286     sPk.aiRowEst = aiRowEstPk;
97287     sPk.onError = OE_Replace;
97288     sPk.pTable = pSrc->pTab;
97289     aiRowEstPk[0] = pSrc->pTab->nRowEst;
97290     aiRowEstPk[1] = 1;
97291     pFirst = pSrc->pTab->pIndex;
97292     if( pSrc->notIndexed==0 ){
97293       sPk.pNext = pFirst;
97294     }
97295     pProbe = &sPk;
97296     wsFlagMask = ~(
97297         WHERE_COLUMN_IN|WHERE_COLUMN_EQ|WHERE_COLUMN_NULL|WHERE_COLUMN_RANGE
97298     );
97299     eqTermMask = WO_EQ|WO_IN;
97300     pIdx = 0;
97301   }
97302
97303   /* Loop over all indices looking for the best one to use
97304   */
97305   for(; pProbe; pIdx=pProbe=pProbe->pNext){
97306     const unsigned int * const aiRowEst = pProbe->aiRowEst;
97307     double cost;                /* Cost of using pProbe */
97308     double nRow;                /* Estimated number of rows in result set */
97309     int rev;                    /* True to scan in reverse order */
97310     int wsFlags = 0;
97311     Bitmask used = 0;
97312
97313     /* The following variables are populated based on the properties of
97314     ** scan being evaluated. They are then used to determine the expected
97315     ** cost and number of rows returned.
97316     **
97317     **  nEq: 
97318     **    Number of equality terms that can be implemented using the index.
97319     **
97320     **  nInMul:  
97321     **    The "in-multiplier". This is an estimate of how many seek operations 
97322     **    SQLite must perform on the index in question. For example, if the 
97323     **    WHERE clause is:
97324     **
97325     **      WHERE a IN (1, 2, 3) AND b IN (4, 5, 6)
97326     **
97327     **    SQLite must perform 9 lookups on an index on (a, b), so nInMul is 
97328     **    set to 9. Given the same schema and either of the following WHERE 
97329     **    clauses:
97330     **
97331     **      WHERE a =  1
97332     **      WHERE a >= 2
97333     **
97334     **    nInMul is set to 1.
97335     **
97336     **    If there exists a WHERE term of the form "x IN (SELECT ...)", then 
97337     **    the sub-select is assumed to return 25 rows for the purposes of 
97338     **    determining nInMul.
97339     **
97340     **  bInEst:  
97341     **    Set to true if there was at least one "x IN (SELECT ...)" term used 
97342     **    in determining the value of nInMul.
97343     **
97344     **  estBound:
97345     **    An estimate on the amount of the table that must be searched.  A
97346     **    value of 100 means the entire table is searched.  Range constraints
97347     **    might reduce this to a value less than 100 to indicate that only
97348     **    a fraction of the table needs searching.  In the absence of
97349     **    sqlite_stat2 ANALYZE data, a single inequality reduces the search
97350     **    space to 1/3rd its original size.  So an x>? constraint reduces
97351     **    estBound to 33.  Two constraints (x>? AND x<?) reduce estBound to 11.
97352     **
97353     **  bSort:   
97354     **    Boolean. True if there is an ORDER BY clause that will require an 
97355     **    external sort (i.e. scanning the index being evaluated will not 
97356     **    correctly order records).
97357     **
97358     **  bLookup: 
97359     **    Boolean. True if for each index entry visited a lookup on the 
97360     **    corresponding table b-tree is required. This is always false 
97361     **    for the rowid index. For other indexes, it is true unless all the 
97362     **    columns of the table used by the SELECT statement are present in 
97363     **    the index (such an index is sometimes described as a covering index).
97364     **    For example, given the index on (a, b), the second of the following 
97365     **    two queries requires table b-tree lookups, but the first does not.
97366     **
97367     **             SELECT a, b    FROM tbl WHERE a = 1;
97368     **             SELECT a, b, c FROM tbl WHERE a = 1;
97369     */
97370     int nEq;
97371     int bInEst = 0;
97372     int nInMul = 1;
97373     int estBound = 100;
97374     int nBound = 0;             /* Number of range constraints seen */
97375     int bSort = 0;
97376     int bLookup = 0;
97377     WhereTerm *pTerm;           /* A single term of the WHERE clause */
97378
97379     /* Determine the values of nEq and nInMul */
97380     for(nEq=0; nEq<pProbe->nColumn; nEq++){
97381       int j = pProbe->aiColumn[nEq];
97382       pTerm = findTerm(pWC, iCur, j, notReady, eqTermMask, pIdx);
97383       if( pTerm==0 ) break;
97384       wsFlags |= (WHERE_COLUMN_EQ|WHERE_ROWID_EQ);
97385       if( pTerm->eOperator & WO_IN ){
97386         Expr *pExpr = pTerm->pExpr;
97387         wsFlags |= WHERE_COLUMN_IN;
97388         if( ExprHasProperty(pExpr, EP_xIsSelect) ){
97389           nInMul *= 25;
97390           bInEst = 1;
97391         }else if( ALWAYS(pExpr->x.pList) ){
97392           nInMul *= pExpr->x.pList->nExpr + 1;
97393         }
97394       }else if( pTerm->eOperator & WO_ISNULL ){
97395         wsFlags |= WHERE_COLUMN_NULL;
97396       }
97397       used |= pTerm->prereqRight;
97398     }
97399
97400     /* Determine the value of estBound. */
97401     if( nEq<pProbe->nColumn ){
97402       int j = pProbe->aiColumn[nEq];
97403       if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pIdx) ){
97404         WhereTerm *pTop = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pIdx);
97405         WhereTerm *pBtm = findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pIdx);
97406         whereRangeScanEst(pParse, pProbe, nEq, pBtm, pTop, &estBound);
97407         if( pTop ){
97408           nBound = 1;
97409           wsFlags |= WHERE_TOP_LIMIT;
97410           used |= pTop->prereqRight;
97411         }
97412         if( pBtm ){
97413           nBound++;
97414           wsFlags |= WHERE_BTM_LIMIT;
97415           used |= pBtm->prereqRight;
97416         }
97417         wsFlags |= (WHERE_COLUMN_RANGE|WHERE_ROWID_RANGE);
97418       }
97419     }else if( pProbe->onError!=OE_None ){
97420       testcase( wsFlags & WHERE_COLUMN_IN );
97421       testcase( wsFlags & WHERE_COLUMN_NULL );
97422       if( (wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0 ){
97423         wsFlags |= WHERE_UNIQUE;
97424       }
97425     }
97426
97427     /* If there is an ORDER BY clause and the index being considered will
97428     ** naturally scan rows in the required order, set the appropriate flags
97429     ** in wsFlags. Otherwise, if there is an ORDER BY clause but the index
97430     ** will scan rows in a different order, set the bSort variable.  */
97431     if( pOrderBy ){
97432       if( (wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0
97433         && isSortingIndex(pParse,pWC->pMaskSet,pProbe,iCur,pOrderBy,nEq,&rev)
97434       ){
97435         wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE|WHERE_ORDERBY;
97436         wsFlags |= (rev ? WHERE_REVERSE : 0);
97437       }else{
97438         bSort = 1;
97439       }
97440     }
97441
97442     /* If currently calculating the cost of using an index (not the IPK
97443     ** index), determine if all required column data may be obtained without 
97444     ** using the main table (i.e. if the index is a covering
97445     ** index for this query). If it is, set the WHERE_IDX_ONLY flag in
97446     ** wsFlags. Otherwise, set the bLookup variable to true.  */
97447     if( pIdx && wsFlags ){
97448       Bitmask m = pSrc->colUsed;
97449       int j;
97450       for(j=0; j<pIdx->nColumn; j++){
97451         int x = pIdx->aiColumn[j];
97452         if( x<BMS-1 ){
97453           m &= ~(((Bitmask)1)<<x);
97454         }
97455       }
97456       if( m==0 ){
97457         wsFlags |= WHERE_IDX_ONLY;
97458       }else{
97459         bLookup = 1;
97460       }
97461     }
97462
97463     /*
97464     ** Estimate the number of rows of output.  For an IN operator,
97465     ** do not let the estimate exceed half the rows in the table.
97466     */
97467     nRow = (double)(aiRowEst[nEq] * nInMul);
97468     if( bInEst && nRow*2>aiRowEst[0] ){
97469       nRow = aiRowEst[0]/2;
97470       nInMul = (int)(nRow / aiRowEst[nEq]);
97471     }
97472
97473     /* Assume constant cost to access a row and logarithmic cost to
97474     ** do a binary search.  Hence, the initial cost is the number of output
97475     ** rows plus log2(table-size) times the number of binary searches.
97476     */
97477     cost = nRow + nInMul*estLog(aiRowEst[0]);
97478
97479     /* Adjust the number of rows and the cost downward to reflect rows
97480     ** that are excluded by range constraints.
97481     */
97482     nRow = (nRow * (double)estBound) / (double)100;
97483     cost = (cost * (double)estBound) / (double)100;
97484
97485     /* Add in the estimated cost of sorting the result
97486     */
97487     if( bSort ){
97488       cost += cost*estLog(cost);
97489     }
97490
97491     /* If all information can be taken directly from the index, we avoid
97492     ** doing table lookups.  This reduces the cost by half.  (Not really -
97493     ** this needs to be fixed.)
97494     */
97495     if( pIdx && bLookup==0 ){
97496       cost /= (double)2;
97497     }
97498     /**** Cost of using this index has now been computed ****/
97499
97500     /* If there are additional constraints on this table that cannot
97501     ** be used with the current index, but which might lower the number
97502     ** of output rows, adjust the nRow value accordingly.  This only 
97503     ** matters if the current index is the least costly, so do not bother
97504     ** with this step if we already know this index will not be chosen.
97505     ** Also, never reduce the output row count below 2 using this step.
97506     **
97507     ** It is critical that the notValid mask be used here instead of
97508     ** the notReady mask.  When computing an "optimal" index, the notReady
97509     ** mask will only have one bit set - the bit for the current table.
97510     ** The notValid mask, on the other hand, always has all bits set for
97511     ** tables that are not in outer loops.  If notReady is used here instead
97512     ** of notValid, then a optimal index that depends on inner joins loops
97513     ** might be selected even when there exists an optimal index that has
97514     ** no such dependency.
97515     */
97516     if( nRow>2 && cost<=pCost->rCost ){
97517       int k;                       /* Loop counter */
97518       int nSkipEq = nEq;           /* Number of == constraints to skip */
97519       int nSkipRange = nBound;     /* Number of < constraints to skip */
97520       Bitmask thisTab;             /* Bitmap for pSrc */
97521
97522       thisTab = getMask(pWC->pMaskSet, iCur);
97523       for(pTerm=pWC->a, k=pWC->nTerm; nRow>2 && k; k--, pTerm++){
97524         if( pTerm->wtFlags & TERM_VIRTUAL ) continue;
97525         if( (pTerm->prereqAll & notValid)!=thisTab ) continue;
97526         if( pTerm->eOperator & (WO_EQ|WO_IN|WO_ISNULL) ){
97527           if( nSkipEq ){
97528             /* Ignore the first nEq equality matches since the index
97529             ** has already accounted for these */
97530             nSkipEq--;
97531           }else{
97532             /* Assume each additional equality match reduces the result
97533             ** set size by a factor of 10 */
97534             nRow /= 10;
97535           }
97536         }else if( pTerm->eOperator & (WO_LT|WO_LE|WO_GT|WO_GE) ){
97537           if( nSkipRange ){
97538             /* Ignore the first nBound range constraints since the index
97539             ** has already accounted for these */
97540             nSkipRange--;
97541           }else{
97542             /* Assume each additional range constraint reduces the result
97543             ** set size by a factor of 3 */
97544             nRow /= 3;
97545           }
97546         }else{
97547           /* Any other expression lowers the output row count by half */
97548           nRow /= 2;
97549         }
97550       }
97551       if( nRow<2 ) nRow = 2;
97552     }
97553
97554
97555     WHERETRACE((
97556       "%s(%s): nEq=%d nInMul=%d estBound=%d bSort=%d bLookup=%d wsFlags=0x%x\n"
97557       "         notReady=0x%llx nRow=%.2f cost=%.2f used=0x%llx\n",
97558       pSrc->pTab->zName, (pIdx ? pIdx->zName : "ipk"), 
97559       nEq, nInMul, estBound, bSort, bLookup, wsFlags,
97560       notReady, nRow, cost, used
97561     ));
97562
97563     /* If this index is the best we have seen so far, then record this
97564     ** index and its cost in the pCost structure.
97565     */
97566     if( (!pIdx || wsFlags)
97567      && (cost<pCost->rCost || (cost<=pCost->rCost && nRow<pCost->nRow))
97568     ){
97569       pCost->rCost = cost;
97570       pCost->nRow = nRow;
97571       pCost->used = used;
97572       pCost->plan.wsFlags = (wsFlags&wsFlagMask);
97573       pCost->plan.nEq = nEq;
97574       pCost->plan.u.pIdx = pIdx;
97575     }
97576
97577     /* If there was an INDEXED BY clause, then only that one index is
97578     ** considered. */
97579     if( pSrc->pIndex ) break;
97580
97581     /* Reset masks for the next index in the loop */
97582     wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
97583     eqTermMask = idxEqTermMask;
97584   }
97585
97586   /* If there is no ORDER BY clause and the SQLITE_ReverseOrder flag
97587   ** is set, then reverse the order that the index will be scanned
97588   ** in. This is used for application testing, to help find cases
97589   ** where application behaviour depends on the (undefined) order that
97590   ** SQLite outputs rows in in the absence of an ORDER BY clause.  */
97591   if( !pOrderBy && pParse->db->flags & SQLITE_ReverseOrder ){
97592     pCost->plan.wsFlags |= WHERE_REVERSE;
97593   }
97594
97595   assert( pOrderBy || (pCost->plan.wsFlags&WHERE_ORDERBY)==0 );
97596   assert( pCost->plan.u.pIdx==0 || (pCost->plan.wsFlags&WHERE_ROWID_EQ)==0 );
97597   assert( pSrc->pIndex==0 
97598        || pCost->plan.u.pIdx==0 
97599        || pCost->plan.u.pIdx==pSrc->pIndex 
97600   );
97601
97602   WHERETRACE(("best index is: %s\n", 
97603     ((pCost->plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ? "none" : 
97604          pCost->plan.u.pIdx ? pCost->plan.u.pIdx->zName : "ipk")
97605   ));
97606   
97607   bestOrClauseIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost);
97608   bestAutomaticIndex(pParse, pWC, pSrc, notReady, pCost);
97609   pCost->plan.wsFlags |= eqTermMask;
97610 }
97611
97612 /*
97613 ** Find the query plan for accessing table pSrc->pTab. Write the
97614 ** best query plan and its cost into the WhereCost object supplied 
97615 ** as the last parameter. This function may calculate the cost of
97616 ** both real and virtual table scans.
97617 */
97618 static void bestIndex(
97619   Parse *pParse,              /* The parsing context */
97620   WhereClause *pWC,           /* The WHERE clause */
97621   struct SrcList_item *pSrc,  /* The FROM clause term to search */
97622   Bitmask notReady,           /* Mask of cursors not available for indexing */
97623   Bitmask notValid,           /* Cursors not available for any purpose */
97624   ExprList *pOrderBy,         /* The ORDER BY clause */
97625   WhereCost *pCost            /* Lowest cost query plan */
97626 ){
97627 #ifndef SQLITE_OMIT_VIRTUALTABLE
97628   if( IsVirtual(pSrc->pTab) ){
97629     sqlite3_index_info *p = 0;
97630     bestVirtualIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost,&p);
97631     if( p->needToFreeIdxStr ){
97632       sqlite3_free(p->idxStr);
97633     }
97634     sqlite3DbFree(pParse->db, p);
97635   }else
97636 #endif
97637   {
97638     bestBtreeIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost);
97639   }
97640 }
97641
97642 /*
97643 ** Disable a term in the WHERE clause.  Except, do not disable the term
97644 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
97645 ** or USING clause of that join.
97646 **
97647 ** Consider the term t2.z='ok' in the following queries:
97648 **
97649 **   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
97650 **   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
97651 **   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
97652 **
97653 ** The t2.z='ok' is disabled in the in (2) because it originates
97654 ** in the ON clause.  The term is disabled in (3) because it is not part
97655 ** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
97656 **
97657 ** IMPLEMENTATION-OF: R-24597-58655 No tests are done for terms that are
97658 ** completely satisfied by indices.
97659 **
97660 ** Disabling a term causes that term to not be tested in the inner loop
97661 ** of the join.  Disabling is an optimization.  When terms are satisfied
97662 ** by indices, we disable them to prevent redundant tests in the inner
97663 ** loop.  We would get the correct results if nothing were ever disabled,
97664 ** but joins might run a little slower.  The trick is to disable as much
97665 ** as we can without disabling too much.  If we disabled in (1), we'd get
97666 ** the wrong answer.  See ticket #813.
97667 */
97668 static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
97669   if( pTerm
97670       && (pTerm->wtFlags & TERM_CODED)==0
97671       && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
97672   ){
97673     pTerm->wtFlags |= TERM_CODED;
97674     if( pTerm->iParent>=0 ){
97675       WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
97676       if( (--pOther->nChild)==0 ){
97677         disableTerm(pLevel, pOther);
97678       }
97679     }
97680   }
97681 }
97682
97683 /*
97684 ** Code an OP_Affinity opcode to apply the column affinity string zAff
97685 ** to the n registers starting at base. 
97686 **
97687 ** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
97688 ** beginning and end of zAff are ignored.  If all entries in zAff are
97689 ** SQLITE_AFF_NONE, then no code gets generated.
97690 **
97691 ** This routine makes its own copy of zAff so that the caller is free
97692 ** to modify zAff after this routine returns.
97693 */
97694 static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
97695   Vdbe *v = pParse->pVdbe;
97696   if( zAff==0 ){
97697     assert( pParse->db->mallocFailed );
97698     return;
97699   }
97700   assert( v!=0 );
97701
97702   /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
97703   ** and end of the affinity string.
97704   */
97705   while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
97706     n--;
97707     base++;
97708     zAff++;
97709   }
97710   while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
97711     n--;
97712   }
97713
97714   /* Code the OP_Affinity opcode if there is anything left to do. */
97715   if( n>0 ){
97716     sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
97717     sqlite3VdbeChangeP4(v, -1, zAff, n);
97718     sqlite3ExprCacheAffinityChange(pParse, base, n);
97719   }
97720 }
97721
97722
97723 /*
97724 ** Generate code for a single equality term of the WHERE clause.  An equality
97725 ** term can be either X=expr or X IN (...).   pTerm is the term to be 
97726 ** coded.
97727 **
97728 ** The current value for the constraint is left in register iReg.
97729 **
97730 ** For a constraint of the form X=expr, the expression is evaluated and its
97731 ** result is left on the stack.  For constraints of the form X IN (...)
97732 ** this routine sets up a loop that will iterate over all values of X.
97733 */
97734 static int codeEqualityTerm(
97735   Parse *pParse,      /* The parsing context */
97736   WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
97737   WhereLevel *pLevel, /* When level of the FROM clause we are working on */
97738   int iTarget         /* Attempt to leave results in this register */
97739 ){
97740   Expr *pX = pTerm->pExpr;
97741   Vdbe *v = pParse->pVdbe;
97742   int iReg;                  /* Register holding results */
97743
97744   assert( iTarget>0 );
97745   if( pX->op==TK_EQ ){
97746     iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
97747   }else if( pX->op==TK_ISNULL ){
97748     iReg = iTarget;
97749     sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
97750 #ifndef SQLITE_OMIT_SUBQUERY
97751   }else{
97752     int eType;
97753     int iTab;
97754     struct InLoop *pIn;
97755
97756     assert( pX->op==TK_IN );
97757     iReg = iTarget;
97758     eType = sqlite3FindInIndex(pParse, pX, 0);
97759     iTab = pX->iTable;
97760     sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
97761     assert( pLevel->plan.wsFlags & WHERE_IN_ABLE );
97762     if( pLevel->u.in.nIn==0 ){
97763       pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
97764     }
97765     pLevel->u.in.nIn++;
97766     pLevel->u.in.aInLoop =
97767        sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
97768                               sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
97769     pIn = pLevel->u.in.aInLoop;
97770     if( pIn ){
97771       pIn += pLevel->u.in.nIn - 1;
97772       pIn->iCur = iTab;
97773       if( eType==IN_INDEX_ROWID ){
97774         pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
97775       }else{
97776         pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
97777       }
97778       sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
97779     }else{
97780       pLevel->u.in.nIn = 0;
97781     }
97782 #endif
97783   }
97784   disableTerm(pLevel, pTerm);
97785   return iReg;
97786 }
97787
97788 /*
97789 ** Generate code that will evaluate all == and IN constraints for an
97790 ** index.
97791 **
97792 ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
97793 ** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
97794 ** The index has as many as three equality constraints, but in this
97795 ** example, the third "c" value is an inequality.  So only two 
97796 ** constraints are coded.  This routine will generate code to evaluate
97797 ** a==5 and b IN (1,2,3).  The current values for a and b will be stored
97798 ** in consecutive registers and the index of the first register is returned.
97799 **
97800 ** In the example above nEq==2.  But this subroutine works for any value
97801 ** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
97802 ** The only thing it does is allocate the pLevel->iMem memory cell and
97803 ** compute the affinity string.
97804 **
97805 ** This routine always allocates at least one memory cell and returns
97806 ** the index of that memory cell. The code that
97807 ** calls this routine will use that memory cell to store the termination
97808 ** key value of the loop.  If one or more IN operators appear, then
97809 ** this routine allocates an additional nEq memory cells for internal
97810 ** use.
97811 **
97812 ** Before returning, *pzAff is set to point to a buffer containing a
97813 ** copy of the column affinity string of the index allocated using
97814 ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
97815 ** with equality constraints that use NONE affinity are set to
97816 ** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
97817 **
97818 **   CREATE TABLE t1(a TEXT PRIMARY KEY, b);
97819 **   SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
97820 **
97821 ** In the example above, the index on t1(a) has TEXT affinity. But since
97822 ** the right hand side of the equality constraint (t2.b) has NONE affinity,
97823 ** no conversion should be attempted before using a t2.b value as part of
97824 ** a key to search the index. Hence the first byte in the returned affinity
97825 ** string in this example would be set to SQLITE_AFF_NONE.
97826 */
97827 static int codeAllEqualityTerms(
97828   Parse *pParse,        /* Parsing context */
97829   WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
97830   WhereClause *pWC,     /* The WHERE clause */
97831   Bitmask notReady,     /* Which parts of FROM have not yet been coded */
97832   int nExtraReg,        /* Number of extra registers to allocate */
97833   char **pzAff          /* OUT: Set to point to affinity string */
97834 ){
97835   int nEq = pLevel->plan.nEq;   /* The number of == or IN constraints to code */
97836   Vdbe *v = pParse->pVdbe;      /* The vm under construction */
97837   Index *pIdx;                  /* The index being used for this loop */
97838   int iCur = pLevel->iTabCur;   /* The cursor of the table */
97839   WhereTerm *pTerm;             /* A single constraint term */
97840   int j;                        /* Loop counter */
97841   int regBase;                  /* Base register */
97842   int nReg;                     /* Number of registers to allocate */
97843   char *zAff;                   /* Affinity string to return */
97844
97845   /* This module is only called on query plans that use an index. */
97846   assert( pLevel->plan.wsFlags & WHERE_INDEXED );
97847   pIdx = pLevel->plan.u.pIdx;
97848
97849   /* Figure out how many memory cells we will need then allocate them.
97850   */
97851   regBase = pParse->nMem + 1;
97852   nReg = pLevel->plan.nEq + nExtraReg;
97853   pParse->nMem += nReg;
97854
97855   zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
97856   if( !zAff ){
97857     pParse->db->mallocFailed = 1;
97858   }
97859
97860   /* Evaluate the equality constraints
97861   */
97862   assert( pIdx->nColumn>=nEq );
97863   for(j=0; j<nEq; j++){
97864     int r1;
97865     int k = pIdx->aiColumn[j];
97866     pTerm = findTerm(pWC, iCur, k, notReady, pLevel->plan.wsFlags, pIdx);
97867     if( NEVER(pTerm==0) ) break;
97868     /* The following true for indices with redundant columns. 
97869     ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
97870     testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
97871     testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
97872     r1 = codeEqualityTerm(pParse, pTerm, pLevel, regBase+j);
97873     if( r1!=regBase+j ){
97874       if( nReg==1 ){
97875         sqlite3ReleaseTempReg(pParse, regBase);
97876         regBase = r1;
97877       }else{
97878         sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
97879       }
97880     }
97881     testcase( pTerm->eOperator & WO_ISNULL );
97882     testcase( pTerm->eOperator & WO_IN );
97883     if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
97884       Expr *pRight = pTerm->pExpr->pRight;
97885       sqlite3ExprCodeIsNullJump(v, pRight, regBase+j, pLevel->addrBrk);
97886       if( zAff ){
97887         if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
97888           zAff[j] = SQLITE_AFF_NONE;
97889         }
97890         if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
97891           zAff[j] = SQLITE_AFF_NONE;
97892         }
97893       }
97894     }
97895   }
97896   *pzAff = zAff;
97897   return regBase;
97898 }
97899
97900 /*
97901 ** Generate code for the start of the iLevel-th loop in the WHERE clause
97902 ** implementation described by pWInfo.
97903 */
97904 static Bitmask codeOneLoopStart(
97905   WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
97906   int iLevel,          /* Which level of pWInfo->a[] should be coded */
97907   u16 wctrlFlags,      /* One of the WHERE_* flags defined in sqliteInt.h */
97908   Bitmask notReady     /* Which tables are currently available */
97909 ){
97910   int j, k;            /* Loop counters */
97911   int iCur;            /* The VDBE cursor for the table */
97912   int addrNxt;         /* Where to jump to continue with the next IN case */
97913   int omitTable;       /* True if we use the index only */
97914   int bRev;            /* True if we need to scan in reverse order */
97915   WhereLevel *pLevel;  /* The where level to be coded */
97916   WhereClause *pWC;    /* Decomposition of the entire WHERE clause */
97917   WhereTerm *pTerm;               /* A WHERE clause term */
97918   Parse *pParse;                  /* Parsing context */
97919   Vdbe *v;                        /* The prepared stmt under constructions */
97920   struct SrcList_item *pTabItem;  /* FROM clause term being coded */
97921   int addrBrk;                    /* Jump here to break out of the loop */
97922   int addrCont;                   /* Jump here to continue with next cycle */
97923   int iRowidReg = 0;        /* Rowid is stored in this register, if not zero */
97924   int iReleaseReg = 0;      /* Temp register to free before returning */
97925
97926   pParse = pWInfo->pParse;
97927   v = pParse->pVdbe;
97928   pWC = pWInfo->pWC;
97929   pLevel = &pWInfo->a[iLevel];
97930   pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
97931   iCur = pTabItem->iCursor;
97932   bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0;
97933   omitTable = (pLevel->plan.wsFlags & WHERE_IDX_ONLY)!=0 
97934            && (wctrlFlags & WHERE_FORCE_TABLE)==0;
97935
97936   /* Create labels for the "break" and "continue" instructions
97937   ** for the current loop.  Jump to addrBrk to break out of a loop.
97938   ** Jump to cont to go immediately to the next iteration of the
97939   ** loop.
97940   **
97941   ** When there is an IN operator, we also have a "addrNxt" label that
97942   ** means to continue with the next IN value combination.  When
97943   ** there are no IN operators in the constraints, the "addrNxt" label
97944   ** is the same as "addrBrk".
97945   */
97946   addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
97947   addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
97948
97949   /* If this is the right table of a LEFT OUTER JOIN, allocate and
97950   ** initialize a memory cell that records if this table matches any
97951   ** row of the left table of the join.
97952   */
97953   if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
97954     pLevel->iLeftJoin = ++pParse->nMem;
97955     sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
97956     VdbeComment((v, "init LEFT JOIN no-match flag"));
97957   }
97958
97959 #ifndef SQLITE_OMIT_VIRTUALTABLE
97960   if(  (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
97961     /* Case 0:  The table is a virtual-table.  Use the VFilter and VNext
97962     **          to access the data.
97963     */
97964     int iReg;   /* P3 Value for OP_VFilter */
97965     sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
97966     int nConstraint = pVtabIdx->nConstraint;
97967     struct sqlite3_index_constraint_usage *aUsage =
97968                                                 pVtabIdx->aConstraintUsage;
97969     const struct sqlite3_index_constraint *aConstraint =
97970                                                 pVtabIdx->aConstraint;
97971
97972     sqlite3ExprCachePush(pParse);
97973     iReg = sqlite3GetTempRange(pParse, nConstraint+2);
97974     for(j=1; j<=nConstraint; j++){
97975       for(k=0; k<nConstraint; k++){
97976         if( aUsage[k].argvIndex==j ){
97977           int iTerm = aConstraint[k].iTermOffset;
97978           sqlite3ExprCode(pParse, pWC->a[iTerm].pExpr->pRight, iReg+j+1);
97979           break;
97980         }
97981       }
97982       if( k==nConstraint ) break;
97983     }
97984     sqlite3VdbeAddOp2(v, OP_Integer, pVtabIdx->idxNum, iReg);
97985     sqlite3VdbeAddOp2(v, OP_Integer, j-1, iReg+1);
97986     sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrBrk, iReg, pVtabIdx->idxStr,
97987                       pVtabIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC);
97988     pVtabIdx->needToFreeIdxStr = 0;
97989     for(j=0; j<nConstraint; j++){
97990       if( aUsage[j].omit ){
97991         int iTerm = aConstraint[j].iTermOffset;
97992         disableTerm(pLevel, &pWC->a[iTerm]);
97993       }
97994     }
97995     pLevel->op = OP_VNext;
97996     pLevel->p1 = iCur;
97997     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
97998     sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
97999     sqlite3ExprCachePop(pParse, 1);
98000   }else
98001 #endif /* SQLITE_OMIT_VIRTUALTABLE */
98002
98003   if( pLevel->plan.wsFlags & WHERE_ROWID_EQ ){
98004     /* Case 1:  We can directly reference a single row using an
98005     **          equality comparison against the ROWID field.  Or
98006     **          we reference multiple rows using a "rowid IN (...)"
98007     **          construct.
98008     */
98009     iReleaseReg = sqlite3GetTempReg(pParse);
98010     pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
98011     assert( pTerm!=0 );
98012     assert( pTerm->pExpr!=0 );
98013     assert( pTerm->leftCursor==iCur );
98014     assert( omitTable==0 );
98015     testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
98016     iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, iReleaseReg);
98017     addrNxt = pLevel->addrNxt;
98018     sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
98019     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
98020     sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
98021     VdbeComment((v, "pk"));
98022     pLevel->op = OP_Noop;
98023   }else if( pLevel->plan.wsFlags & WHERE_ROWID_RANGE ){
98024     /* Case 2:  We have an inequality comparison against the ROWID field.
98025     */
98026     int testOp = OP_Noop;
98027     int start;
98028     int memEndValue = 0;
98029     WhereTerm *pStart, *pEnd;
98030
98031     assert( omitTable==0 );
98032     pStart = findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0);
98033     pEnd = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0);
98034     if( bRev ){
98035       pTerm = pStart;
98036       pStart = pEnd;
98037       pEnd = pTerm;
98038     }
98039     if( pStart ){
98040       Expr *pX;             /* The expression that defines the start bound */
98041       int r1, rTemp;        /* Registers for holding the start boundary */
98042
98043       /* The following constant maps TK_xx codes into corresponding 
98044       ** seek opcodes.  It depends on a particular ordering of TK_xx
98045       */
98046       const u8 aMoveOp[] = {
98047            /* TK_GT */  OP_SeekGt,
98048            /* TK_LE */  OP_SeekLe,
98049            /* TK_LT */  OP_SeekLt,
98050            /* TK_GE */  OP_SeekGe
98051       };
98052       assert( TK_LE==TK_GT+1 );      /* Make sure the ordering.. */
98053       assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */
98054       assert( TK_GE==TK_GT+3 );      /*  ... is correcct. */
98055
98056       testcase( pStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
98057       pX = pStart->pExpr;
98058       assert( pX!=0 );
98059       assert( pStart->leftCursor==iCur );
98060       r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
98061       sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
98062       VdbeComment((v, "pk"));
98063       sqlite3ExprCacheAffinityChange(pParse, r1, 1);
98064       sqlite3ReleaseTempReg(pParse, rTemp);
98065       disableTerm(pLevel, pStart);
98066     }else{
98067       sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
98068     }
98069     if( pEnd ){
98070       Expr *pX;
98071       pX = pEnd->pExpr;
98072       assert( pX!=0 );
98073       assert( pEnd->leftCursor==iCur );
98074       testcase( pEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
98075       memEndValue = ++pParse->nMem;
98076       sqlite3ExprCode(pParse, pX->pRight, memEndValue);
98077       if( pX->op==TK_LT || pX->op==TK_GT ){
98078         testOp = bRev ? OP_Le : OP_Ge;
98079       }else{
98080         testOp = bRev ? OP_Lt : OP_Gt;
98081       }
98082       disableTerm(pLevel, pEnd);
98083     }
98084     start = sqlite3VdbeCurrentAddr(v);
98085     pLevel->op = bRev ? OP_Prev : OP_Next;
98086     pLevel->p1 = iCur;
98087     pLevel->p2 = start;
98088     if( pStart==0 && pEnd==0 ){
98089       pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
98090     }else{
98091       assert( pLevel->p5==0 );
98092     }
98093     if( testOp!=OP_Noop ){
98094       iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
98095       sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
98096       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
98097       sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
98098       sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
98099     }
98100   }else if( pLevel->plan.wsFlags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){
98101     /* Case 3: A scan using an index.
98102     **
98103     **         The WHERE clause may contain zero or more equality 
98104     **         terms ("==" or "IN" operators) that refer to the N
98105     **         left-most columns of the index. It may also contain
98106     **         inequality constraints (>, <, >= or <=) on the indexed
98107     **         column that immediately follows the N equalities. Only 
98108     **         the right-most column can be an inequality - the rest must
98109     **         use the "==" and "IN" operators. For example, if the 
98110     **         index is on (x,y,z), then the following clauses are all 
98111     **         optimized:
98112     **
98113     **            x=5
98114     **            x=5 AND y=10
98115     **            x=5 AND y<10
98116     **            x=5 AND y>5 AND y<10
98117     **            x=5 AND y=5 AND z<=10
98118     **
98119     **         The z<10 term of the following cannot be used, only
98120     **         the x=5 term:
98121     **
98122     **            x=5 AND z<10
98123     **
98124     **         N may be zero if there are inequality constraints.
98125     **         If there are no inequality constraints, then N is at
98126     **         least one.
98127     **
98128     **         This case is also used when there are no WHERE clause
98129     **         constraints but an index is selected anyway, in order
98130     **         to force the output order to conform to an ORDER BY.
98131     */  
98132     static const u8 aStartOp[] = {
98133       0,
98134       0,
98135       OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
98136       OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
98137       OP_SeekGt,           /* 4: (start_constraints  && !startEq && !bRev) */
98138       OP_SeekLt,           /* 5: (start_constraints  && !startEq &&  bRev) */
98139       OP_SeekGe,           /* 6: (start_constraints  &&  startEq && !bRev) */
98140       OP_SeekLe            /* 7: (start_constraints  &&  startEq &&  bRev) */
98141     };
98142     static const u8 aEndOp[] = {
98143       OP_Noop,             /* 0: (!end_constraints) */
98144       OP_IdxGE,            /* 1: (end_constraints && !bRev) */
98145       OP_IdxLT             /* 2: (end_constraints && bRev) */
98146     };
98147     int nEq = pLevel->plan.nEq;  /* Number of == or IN terms */
98148     int isMinQuery = 0;          /* If this is an optimized SELECT min(x).. */
98149     int regBase;                 /* Base register holding constraint values */
98150     int r1;                      /* Temp register */
98151     WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
98152     WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
98153     int startEq;                 /* True if range start uses ==, >= or <= */
98154     int endEq;                   /* True if range end uses ==, >= or <= */
98155     int start_constraints;       /* Start of range is constrained */
98156     int nConstraint;             /* Number of constraint terms */
98157     Index *pIdx;                 /* The index we will be using */
98158     int iIdxCur;                 /* The VDBE cursor for the index */
98159     int nExtraReg = 0;           /* Number of extra registers needed */
98160     int op;                      /* Instruction opcode */
98161     char *zStartAff;             /* Affinity for start of range constraint */
98162     char *zEndAff;               /* Affinity for end of range constraint */
98163
98164     pIdx = pLevel->plan.u.pIdx;
98165     iIdxCur = pLevel->iIdxCur;
98166     k = pIdx->aiColumn[nEq];     /* Column for inequality constraints */
98167
98168     /* If this loop satisfies a sort order (pOrderBy) request that 
98169     ** was passed to this function to implement a "SELECT min(x) ..." 
98170     ** query, then the caller will only allow the loop to run for
98171     ** a single iteration. This means that the first row returned
98172     ** should not have a NULL value stored in 'x'. If column 'x' is
98173     ** the first one after the nEq equality constraints in the index,
98174     ** this requires some special handling.
98175     */
98176     if( (wctrlFlags&WHERE_ORDERBY_MIN)!=0
98177      && (pLevel->plan.wsFlags&WHERE_ORDERBY)
98178      && (pIdx->nColumn>nEq)
98179     ){
98180       /* assert( pOrderBy->nExpr==1 ); */
98181       /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
98182       isMinQuery = 1;
98183       nExtraReg = 1;
98184     }
98185
98186     /* Find any inequality constraint terms for the start and end 
98187     ** of the range. 
98188     */
98189     if( pLevel->plan.wsFlags & WHERE_TOP_LIMIT ){
98190       pRangeEnd = findTerm(pWC, iCur, k, notReady, (WO_LT|WO_LE), pIdx);
98191       nExtraReg = 1;
98192     }
98193     if( pLevel->plan.wsFlags & WHERE_BTM_LIMIT ){
98194       pRangeStart = findTerm(pWC, iCur, k, notReady, (WO_GT|WO_GE), pIdx);
98195       nExtraReg = 1;
98196     }
98197
98198     /* Generate code to evaluate all constraint terms using == or IN
98199     ** and store the values of those terms in an array of registers
98200     ** starting at regBase.
98201     */
98202     regBase = codeAllEqualityTerms(
98203         pParse, pLevel, pWC, notReady, nExtraReg, &zStartAff
98204     );
98205     zEndAff = sqlite3DbStrDup(pParse->db, zStartAff);
98206     addrNxt = pLevel->addrNxt;
98207
98208     /* If we are doing a reverse order scan on an ascending index, or
98209     ** a forward order scan on a descending index, interchange the 
98210     ** start and end terms (pRangeStart and pRangeEnd).
98211     */
98212     if( nEq<pIdx->nColumn && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC) ){
98213       SWAP(WhereTerm *, pRangeEnd, pRangeStart);
98214     }
98215
98216     testcase( pRangeStart && pRangeStart->eOperator & WO_LE );
98217     testcase( pRangeStart && pRangeStart->eOperator & WO_GE );
98218     testcase( pRangeEnd && pRangeEnd->eOperator & WO_LE );
98219     testcase( pRangeEnd && pRangeEnd->eOperator & WO_GE );
98220     startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
98221     endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
98222     start_constraints = pRangeStart || nEq>0;
98223
98224     /* Seek the index cursor to the start of the range. */
98225     nConstraint = nEq;
98226     if( pRangeStart ){
98227       Expr *pRight = pRangeStart->pExpr->pRight;
98228       sqlite3ExprCode(pParse, pRight, regBase+nEq);
98229       sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
98230       if( zStartAff ){
98231         if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
98232           /* Since the comparison is to be performed with no conversions
98233           ** applied to the operands, set the affinity to apply to pRight to 
98234           ** SQLITE_AFF_NONE.  */
98235           zStartAff[nEq] = SQLITE_AFF_NONE;
98236         }
98237         if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
98238           zStartAff[nEq] = SQLITE_AFF_NONE;
98239         }
98240       }  
98241       nConstraint++;
98242       testcase( pRangeStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
98243     }else if( isMinQuery ){
98244       sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
98245       nConstraint++;
98246       startEq = 0;
98247       start_constraints = 1;
98248     }
98249     codeApplyAffinity(pParse, regBase, nConstraint, zStartAff);
98250     op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
98251     assert( op!=0 );
98252     testcase( op==OP_Rewind );
98253     testcase( op==OP_Last );
98254     testcase( op==OP_SeekGt );
98255     testcase( op==OP_SeekGe );
98256     testcase( op==OP_SeekLe );
98257     testcase( op==OP_SeekLt );
98258     sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
98259
98260     /* Load the value for the inequality constraint at the end of the
98261     ** range (if any).
98262     */
98263     nConstraint = nEq;
98264     if( pRangeEnd ){
98265       Expr *pRight = pRangeEnd->pExpr->pRight;
98266       sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
98267       sqlite3ExprCode(pParse, pRight, regBase+nEq);
98268       sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
98269       if( zEndAff ){
98270         if( sqlite3CompareAffinity(pRight, zEndAff[nEq])==SQLITE_AFF_NONE){
98271           /* Since the comparison is to be performed with no conversions
98272           ** applied to the operands, set the affinity to apply to pRight to 
98273           ** SQLITE_AFF_NONE.  */
98274           zEndAff[nEq] = SQLITE_AFF_NONE;
98275         }
98276         if( sqlite3ExprNeedsNoAffinityChange(pRight, zEndAff[nEq]) ){
98277           zEndAff[nEq] = SQLITE_AFF_NONE;
98278         }
98279       }  
98280       codeApplyAffinity(pParse, regBase, nEq+1, zEndAff);
98281       nConstraint++;
98282       testcase( pRangeEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
98283     }
98284     sqlite3DbFree(pParse->db, zStartAff);
98285     sqlite3DbFree(pParse->db, zEndAff);
98286
98287     /* Top of the loop body */
98288     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
98289
98290     /* Check if the index cursor is past the end of the range. */
98291     op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
98292     testcase( op==OP_Noop );
98293     testcase( op==OP_IdxGE );
98294     testcase( op==OP_IdxLT );
98295     if( op!=OP_Noop ){
98296       sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
98297       sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0);
98298     }
98299
98300     /* If there are inequality constraints, check that the value
98301     ** of the table column that the inequality contrains is not NULL.
98302     ** If it is, jump to the next iteration of the loop.
98303     */
98304     r1 = sqlite3GetTempReg(pParse);
98305     testcase( pLevel->plan.wsFlags & WHERE_BTM_LIMIT );
98306     testcase( pLevel->plan.wsFlags & WHERE_TOP_LIMIT );
98307     if( pLevel->plan.wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT) ){
98308       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
98309       sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
98310     }
98311     sqlite3ReleaseTempReg(pParse, r1);
98312
98313     /* Seek the table cursor, if required */
98314     disableTerm(pLevel, pRangeStart);
98315     disableTerm(pLevel, pRangeEnd);
98316     if( !omitTable ){
98317       iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
98318       sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
98319       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
98320       sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg);  /* Deferred seek */
98321     }
98322
98323     /* Record the instruction used to terminate the loop. Disable 
98324     ** WHERE clause terms made redundant by the index range scan.
98325     */
98326     pLevel->op = bRev ? OP_Prev : OP_Next;
98327     pLevel->p1 = iIdxCur;
98328   }else
98329
98330 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
98331   if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
98332     /* Case 4:  Two or more separately indexed terms connected by OR
98333     **
98334     ** Example:
98335     **
98336     **   CREATE TABLE t1(a,b,c,d);
98337     **   CREATE INDEX i1 ON t1(a);
98338     **   CREATE INDEX i2 ON t1(b);
98339     **   CREATE INDEX i3 ON t1(c);
98340     **
98341     **   SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
98342     **
98343     ** In the example, there are three indexed terms connected by OR.
98344     ** The top of the loop looks like this:
98345     **
98346     **          Null       1                # Zero the rowset in reg 1
98347     **
98348     ** Then, for each indexed term, the following. The arguments to
98349     ** RowSetTest are such that the rowid of the current row is inserted
98350     ** into the RowSet. If it is already present, control skips the
98351     ** Gosub opcode and jumps straight to the code generated by WhereEnd().
98352     **
98353     **        sqlite3WhereBegin(<term>)
98354     **          RowSetTest                  # Insert rowid into rowset
98355     **          Gosub      2 A
98356     **        sqlite3WhereEnd()
98357     **
98358     ** Following the above, code to terminate the loop. Label A, the target
98359     ** of the Gosub above, jumps to the instruction right after the Goto.
98360     **
98361     **          Null       1                # Zero the rowset in reg 1
98362     **          Goto       B                # The loop is finished.
98363     **
98364     **       A: <loop body>                 # Return data, whatever.
98365     **
98366     **          Return     2                # Jump back to the Gosub
98367     **
98368     **       B: <after the loop>
98369     **
98370     */
98371     WhereClause *pOrWc;    /* The OR-clause broken out into subterms */
98372     WhereTerm *pFinal;     /* Final subterm within the OR-clause. */
98373     SrcList *pOrTab;       /* Shortened table list or OR-clause generation */
98374
98375     int regReturn = ++pParse->nMem;           /* Register used with OP_Gosub */
98376     int regRowset = 0;                        /* Register for RowSet object */
98377     int regRowid = 0;                         /* Register holding rowid */
98378     int iLoopBody = sqlite3VdbeMakeLabel(v);  /* Start of loop body */
98379     int iRetInit;                             /* Address of regReturn init */
98380     int untestedTerms = 0;             /* Some terms not completely tested */
98381     int ii;
98382    
98383     pTerm = pLevel->plan.u.pTerm;
98384     assert( pTerm!=0 );
98385     assert( pTerm->eOperator==WO_OR );
98386     assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
98387     pOrWc = &pTerm->u.pOrInfo->wc;
98388     pFinal = &pOrWc->a[pOrWc->nTerm-1];
98389     pLevel->op = OP_Return;
98390     pLevel->p1 = regReturn;
98391
98392     /* Set up a new SrcList ni pOrTab containing the table being scanned
98393     ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
98394     ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
98395     */
98396     if( pWInfo->nLevel>1 ){
98397       int nNotReady;                 /* The number of notReady tables */
98398       struct SrcList_item *origSrc;     /* Original list of tables */
98399       nNotReady = pWInfo->nLevel - iLevel - 1;
98400       pOrTab = sqlite3StackAllocRaw(pParse->db,
98401                             sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
98402       if( pOrTab==0 ) return notReady;
98403       pOrTab->nAlloc = (i16)(nNotReady + 1);
98404       pOrTab->nSrc = pOrTab->nAlloc;
98405       memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
98406       origSrc = pWInfo->pTabList->a;
98407       for(k=1; k<=nNotReady; k++){
98408         memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
98409       }
98410     }else{
98411       pOrTab = pWInfo->pTabList;
98412     }
98413
98414     /* Initialize the rowset register to contain NULL. An SQL NULL is 
98415     ** equivalent to an empty rowset.
98416     **
98417     ** Also initialize regReturn to contain the address of the instruction 
98418     ** immediately following the OP_Return at the bottom of the loop. This
98419     ** is required in a few obscure LEFT JOIN cases where control jumps
98420     ** over the top of the loop into the body of it. In this case the 
98421     ** correct response for the end-of-loop code (the OP_Return) is to 
98422     ** fall through to the next instruction, just as an OP_Next does if
98423     ** called on an uninitialized cursor.
98424     */
98425     if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
98426       regRowset = ++pParse->nMem;
98427       regRowid = ++pParse->nMem;
98428       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
98429     }
98430     iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
98431
98432     for(ii=0; ii<pOrWc->nTerm; ii++){
98433       WhereTerm *pOrTerm = &pOrWc->a[ii];
98434       if( pOrTerm->leftCursor==iCur || pOrTerm->eOperator==WO_AND ){
98435         WhereInfo *pSubWInfo;          /* Info for single OR-term scan */
98436         /* Loop through table entries that match term pOrTerm. */
98437         pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrTerm->pExpr, 0,
98438                         WHERE_OMIT_OPEN | WHERE_OMIT_CLOSE |
98439                         WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY);
98440         if( pSubWInfo ){
98441           if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
98442             int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
98443             int r;
98444             r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur, 
98445                                          regRowid);
98446             sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
98447                                  sqlite3VdbeCurrentAddr(v)+2, r, iSet);
98448           }
98449           sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
98450
98451           /* The pSubWInfo->untestedTerms flag means that this OR term
98452           ** contained one or more AND term from a notReady table.  The
98453           ** terms from the notReady table could not be tested and will
98454           ** need to be tested later.
98455           */
98456           if( pSubWInfo->untestedTerms ) untestedTerms = 1;
98457
98458           /* Finish the loop through table entries that match term pOrTerm. */
98459           sqlite3WhereEnd(pSubWInfo);
98460         }
98461       }
98462     }
98463     sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
98464     sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
98465     sqlite3VdbeResolveLabel(v, iLoopBody);
98466
98467     if( pWInfo->nLevel>1 ) sqlite3StackFree(pParse->db, pOrTab);
98468     if( !untestedTerms ) disableTerm(pLevel, pTerm);
98469   }else
98470 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
98471
98472   {
98473     /* Case 5:  There is no usable index.  We must do a complete
98474     **          scan of the entire table.
98475     */
98476     static const u8 aStep[] = { OP_Next, OP_Prev };
98477     static const u8 aStart[] = { OP_Rewind, OP_Last };
98478     assert( bRev==0 || bRev==1 );
98479     assert( omitTable==0 );
98480     pLevel->op = aStep[bRev];
98481     pLevel->p1 = iCur;
98482     pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
98483     pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
98484   }
98485   notReady &= ~getMask(pWC->pMaskSet, iCur);
98486
98487   /* Insert code to test every subexpression that can be completely
98488   ** computed using the current set of tables.
98489   **
98490   ** IMPLEMENTATION-OF: R-49525-50935 Terms that cannot be satisfied through
98491   ** the use of indices become tests that are evaluated against each row of
98492   ** the relevant input tables.
98493   */
98494   k = 0;
98495   for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
98496     Expr *pE;
98497     testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* IMP: R-30575-11662 */
98498     testcase( pTerm->wtFlags & TERM_CODED );
98499     if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
98500     if( (pTerm->prereqAll & notReady)!=0 ){
98501       testcase( pWInfo->untestedTerms==0
98502                && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
98503       pWInfo->untestedTerms = 1;
98504       continue;
98505     }
98506     pE = pTerm->pExpr;
98507     assert( pE!=0 );
98508     if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
98509       continue;
98510     }
98511     sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
98512     k = 1;
98513     pTerm->wtFlags |= TERM_CODED;
98514   }
98515
98516   /* For a LEFT OUTER JOIN, generate code that will record the fact that
98517   ** at least one row of the right table has matched the left table.  
98518   */
98519   if( pLevel->iLeftJoin ){
98520     pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
98521     sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
98522     VdbeComment((v, "record LEFT JOIN hit"));
98523     sqlite3ExprCacheClear(pParse);
98524     for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
98525       testcase( pTerm->wtFlags & TERM_VIRTUAL );  /* IMP: R-30575-11662 */
98526       testcase( pTerm->wtFlags & TERM_CODED );
98527       if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
98528       if( (pTerm->prereqAll & notReady)!=0 ){
98529         assert( pWInfo->untestedTerms );
98530         continue;
98531       }
98532       assert( pTerm->pExpr );
98533       sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
98534       pTerm->wtFlags |= TERM_CODED;
98535     }
98536   }
98537   sqlite3ReleaseTempReg(pParse, iReleaseReg);
98538
98539   return notReady;
98540 }
98541
98542 #if defined(SQLITE_TEST)
98543 /*
98544 ** The following variable holds a text description of query plan generated
98545 ** by the most recent call to sqlite3WhereBegin().  Each call to WhereBegin
98546 ** overwrites the previous.  This information is used for testing and
98547 ** analysis only.
98548 */
98549 SQLITE_API char sqlite3_query_plan[BMS*2*40];  /* Text of the join */
98550 static int nQPlan = 0;              /* Next free slow in _query_plan[] */
98551
98552 #endif /* SQLITE_TEST */
98553
98554
98555 /*
98556 ** Free a WhereInfo structure
98557 */
98558 static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
98559   if( ALWAYS(pWInfo) ){
98560     int i;
98561     for(i=0; i<pWInfo->nLevel; i++){
98562       sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
98563       if( pInfo ){
98564         /* assert( pInfo->needToFreeIdxStr==0 || db->mallocFailed ); */
98565         if( pInfo->needToFreeIdxStr ){
98566           sqlite3_free(pInfo->idxStr);
98567         }
98568         sqlite3DbFree(db, pInfo);
98569       }
98570       if( pWInfo->a[i].plan.wsFlags & WHERE_TEMP_INDEX ){
98571         Index *pIdx = pWInfo->a[i].plan.u.pIdx;
98572         if( pIdx ){
98573           sqlite3DbFree(db, pIdx->zColAff);
98574           sqlite3DbFree(db, pIdx);
98575         }
98576       }
98577     }
98578     whereClauseClear(pWInfo->pWC);
98579     sqlite3DbFree(db, pWInfo);
98580   }
98581 }
98582
98583
98584 /*
98585 ** Generate the beginning of the loop used for WHERE clause processing.
98586 ** The return value is a pointer to an opaque structure that contains
98587 ** information needed to terminate the loop.  Later, the calling routine
98588 ** should invoke sqlite3WhereEnd() with the return value of this function
98589 ** in order to complete the WHERE clause processing.
98590 **
98591 ** If an error occurs, this routine returns NULL.
98592 **
98593 ** The basic idea is to do a nested loop, one loop for each table in
98594 ** the FROM clause of a select.  (INSERT and UPDATE statements are the
98595 ** same as a SELECT with only a single table in the FROM clause.)  For
98596 ** example, if the SQL is this:
98597 **
98598 **       SELECT * FROM t1, t2, t3 WHERE ...;
98599 **
98600 ** Then the code generated is conceptually like the following:
98601 **
98602 **      foreach row1 in t1 do       \    Code generated
98603 **        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
98604 **          foreach row3 in t3 do   /
98605 **            ...
98606 **          end                     \    Code generated
98607 **        end                        |-- by sqlite3WhereEnd()
98608 **      end                         /
98609 **
98610 ** Note that the loops might not be nested in the order in which they
98611 ** appear in the FROM clause if a different order is better able to make
98612 ** use of indices.  Note also that when the IN operator appears in
98613 ** the WHERE clause, it might result in additional nested loops for
98614 ** scanning through all values on the right-hand side of the IN.
98615 **
98616 ** There are Btree cursors associated with each table.  t1 uses cursor
98617 ** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
98618 ** And so forth.  This routine generates code to open those VDBE cursors
98619 ** and sqlite3WhereEnd() generates the code to close them.
98620 **
98621 ** The code that sqlite3WhereBegin() generates leaves the cursors named
98622 ** in pTabList pointing at their appropriate entries.  The [...] code
98623 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
98624 ** data from the various tables of the loop.
98625 **
98626 ** If the WHERE clause is empty, the foreach loops must each scan their
98627 ** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
98628 ** the tables have indices and there are terms in the WHERE clause that
98629 ** refer to those indices, a complete table scan can be avoided and the
98630 ** code will run much faster.  Most of the work of this routine is checking
98631 ** to see if there are indices that can be used to speed up the loop.
98632 **
98633 ** Terms of the WHERE clause are also used to limit which rows actually
98634 ** make it to the "..." in the middle of the loop.  After each "foreach",
98635 ** terms of the WHERE clause that use only terms in that loop and outer
98636 ** loops are evaluated and if false a jump is made around all subsequent
98637 ** inner loops (or around the "..." if the test occurs within the inner-
98638 ** most loop)
98639 **
98640 ** OUTER JOINS
98641 **
98642 ** An outer join of tables t1 and t2 is conceptally coded as follows:
98643 **
98644 **    foreach row1 in t1 do
98645 **      flag = 0
98646 **      foreach row2 in t2 do
98647 **        start:
98648 **          ...
98649 **          flag = 1
98650 **      end
98651 **      if flag==0 then
98652 **        move the row2 cursor to a null row
98653 **        goto start
98654 **      fi
98655 **    end
98656 **
98657 ** ORDER BY CLAUSE PROCESSING
98658 **
98659 ** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
98660 ** if there is one.  If there is no ORDER BY clause or if this routine
98661 ** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
98662 **
98663 ** If an index can be used so that the natural output order of the table
98664 ** scan is correct for the ORDER BY clause, then that index is used and
98665 ** *ppOrderBy is set to NULL.  This is an optimization that prevents an
98666 ** unnecessary sort of the result set if an index appropriate for the
98667 ** ORDER BY clause already exists.
98668 **
98669 ** If the where clause loops cannot be arranged to provide the correct
98670 ** output order, then the *ppOrderBy is unchanged.
98671 */
98672 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
98673   Parse *pParse,        /* The parser context */
98674   SrcList *pTabList,    /* A list of all tables to be scanned */
98675   Expr *pWhere,         /* The WHERE clause */
98676   ExprList **ppOrderBy, /* An ORDER BY clause, or NULL */
98677   u16 wctrlFlags        /* One of the WHERE_* flags defined in sqliteInt.h */
98678 ){
98679   int i;                     /* Loop counter */
98680   int nByteWInfo;            /* Num. bytes allocated for WhereInfo struct */
98681   int nTabList;              /* Number of elements in pTabList */
98682   WhereInfo *pWInfo;         /* Will become the return value of this function */
98683   Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
98684   Bitmask notReady;          /* Cursors that are not yet positioned */
98685   WhereMaskSet *pMaskSet;    /* The expression mask set */
98686   WhereClause *pWC;               /* Decomposition of the WHERE clause */
98687   struct SrcList_item *pTabItem;  /* A single entry from pTabList */
98688   WhereLevel *pLevel;             /* A single level in the pWInfo list */
98689   int iFrom;                      /* First unused FROM clause element */
98690   int andFlags;              /* AND-ed combination of all pWC->a[].wtFlags */
98691   sqlite3 *db;               /* Database connection */
98692
98693   /* The number of tables in the FROM clause is limited by the number of
98694   ** bits in a Bitmask 
98695   */
98696   testcase( pTabList->nSrc==BMS );
98697   if( pTabList->nSrc>BMS ){
98698     sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
98699     return 0;
98700   }
98701
98702   /* This function normally generates a nested loop for all tables in 
98703   ** pTabList.  But if the WHERE_ONETABLE_ONLY flag is set, then we should
98704   ** only generate code for the first table in pTabList and assume that
98705   ** any cursors associated with subsequent tables are uninitialized.
98706   */
98707   nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
98708
98709   /* Allocate and initialize the WhereInfo structure that will become the
98710   ** return value. A single allocation is used to store the WhereInfo
98711   ** struct, the contents of WhereInfo.a[], the WhereClause structure
98712   ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
98713   ** field (type Bitmask) it must be aligned on an 8-byte boundary on
98714   ** some architectures. Hence the ROUND8() below.
98715   */
98716   db = pParse->db;
98717   nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
98718   pWInfo = sqlite3DbMallocZero(db, 
98719       nByteWInfo + 
98720       sizeof(WhereClause) +
98721       sizeof(WhereMaskSet)
98722   );
98723   if( db->mallocFailed ){
98724     sqlite3DbFree(db, pWInfo);
98725     pWInfo = 0;
98726     goto whereBeginError;
98727   }
98728   pWInfo->nLevel = nTabList;
98729   pWInfo->pParse = pParse;
98730   pWInfo->pTabList = pTabList;
98731   pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
98732   pWInfo->pWC = pWC = (WhereClause *)&((u8 *)pWInfo)[nByteWInfo];
98733   pWInfo->wctrlFlags = wctrlFlags;
98734   pWInfo->savedNQueryLoop = pParse->nQueryLoop;
98735   pMaskSet = (WhereMaskSet*)&pWC[1];
98736
98737   /* Split the WHERE clause into separate subexpressions where each
98738   ** subexpression is separated by an AND operator.
98739   */
98740   initMaskSet(pMaskSet);
98741   whereClauseInit(pWC, pParse, pMaskSet);
98742   sqlite3ExprCodeConstants(pParse, pWhere);
98743   whereSplit(pWC, pWhere, TK_AND);   /* IMP: R-15842-53296 */
98744     
98745   /* Special case: a WHERE clause that is constant.  Evaluate the
98746   ** expression and either jump over all of the code or fall thru.
98747   */
98748   if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
98749     sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
98750     pWhere = 0;
98751   }
98752
98753   /* Assign a bit from the bitmask to every term in the FROM clause.
98754   **
98755   ** When assigning bitmask values to FROM clause cursors, it must be
98756   ** the case that if X is the bitmask for the N-th FROM clause term then
98757   ** the bitmask for all FROM clause terms to the left of the N-th term
98758   ** is (X-1).   An expression from the ON clause of a LEFT JOIN can use
98759   ** its Expr.iRightJoinTable value to find the bitmask of the right table
98760   ** of the join.  Subtracting one from the right table bitmask gives a
98761   ** bitmask for all tables to the left of the join.  Knowing the bitmask
98762   ** for all tables to the left of a left join is important.  Ticket #3015.
98763   **
98764   ** Configure the WhereClause.vmask variable so that bits that correspond
98765   ** to virtual table cursors are set. This is used to selectively disable 
98766   ** the OR-to-IN transformation in exprAnalyzeOrTerm(). It is not helpful 
98767   ** with virtual tables.
98768   **
98769   ** Note that bitmasks are created for all pTabList->nSrc tables in
98770   ** pTabList, not just the first nTabList tables.  nTabList is normally
98771   ** equal to pTabList->nSrc but might be shortened to 1 if the
98772   ** WHERE_ONETABLE_ONLY flag is set.
98773   */
98774   assert( pWC->vmask==0 && pMaskSet->n==0 );
98775   for(i=0; i<pTabList->nSrc; i++){
98776     createMask(pMaskSet, pTabList->a[i].iCursor);
98777 #ifndef SQLITE_OMIT_VIRTUALTABLE
98778     if( ALWAYS(pTabList->a[i].pTab) && IsVirtual(pTabList->a[i].pTab) ){
98779       pWC->vmask |= ((Bitmask)1 << i);
98780     }
98781 #endif
98782   }
98783 #ifndef NDEBUG
98784   {
98785     Bitmask toTheLeft = 0;
98786     for(i=0; i<pTabList->nSrc; i++){
98787       Bitmask m = getMask(pMaskSet, pTabList->a[i].iCursor);
98788       assert( (m-1)==toTheLeft );
98789       toTheLeft |= m;
98790     }
98791   }
98792 #endif
98793
98794   /* Analyze all of the subexpressions.  Note that exprAnalyze() might
98795   ** add new virtual terms onto the end of the WHERE clause.  We do not
98796   ** want to analyze these virtual terms, so start analyzing at the end
98797   ** and work forward so that the added virtual terms are never processed.
98798   */
98799   exprAnalyzeAll(pTabList, pWC);
98800   if( db->mallocFailed ){
98801     goto whereBeginError;
98802   }
98803
98804   /* Chose the best index to use for each table in the FROM clause.
98805   **
98806   ** This loop fills in the following fields:
98807   **
98808   **   pWInfo->a[].pIdx      The index to use for this level of the loop.
98809   **   pWInfo->a[].wsFlags   WHERE_xxx flags associated with pIdx
98810   **   pWInfo->a[].nEq       The number of == and IN constraints
98811   **   pWInfo->a[].iFrom     Which term of the FROM clause is being coded
98812   **   pWInfo->a[].iTabCur   The VDBE cursor for the database table
98813   **   pWInfo->a[].iIdxCur   The VDBE cursor for the index
98814   **   pWInfo->a[].pTerm     When wsFlags==WO_OR, the OR-clause term
98815   **
98816   ** This loop also figures out the nesting order of tables in the FROM
98817   ** clause.
98818   */
98819   notReady = ~(Bitmask)0;
98820   pTabItem = pTabList->a;
98821   pLevel = pWInfo->a;
98822   andFlags = ~0;
98823   WHERETRACE(("*** Optimizer Start ***\n"));
98824   for(i=iFrom=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
98825     WhereCost bestPlan;         /* Most efficient plan seen so far */
98826     Index *pIdx;                /* Index for FROM table at pTabItem */
98827     int j;                      /* For looping over FROM tables */
98828     int bestJ = -1;             /* The value of j */
98829     Bitmask m;                  /* Bitmask value for j or bestJ */
98830     int isOptimal;              /* Iterator for optimal/non-optimal search */
98831     int nUnconstrained;         /* Number tables without INDEXED BY */
98832     Bitmask notIndexed;         /* Mask of tables that cannot use an index */
98833
98834     memset(&bestPlan, 0, sizeof(bestPlan));
98835     bestPlan.rCost = SQLITE_BIG_DBL;
98836
98837     /* Loop through the remaining entries in the FROM clause to find the
98838     ** next nested loop. The loop tests all FROM clause entries
98839     ** either once or twice. 
98840     **
98841     ** The first test is always performed if there are two or more entries
98842     ** remaining and never performed if there is only one FROM clause entry
98843     ** to choose from.  The first test looks for an "optimal" scan.  In
98844     ** this context an optimal scan is one that uses the same strategy
98845     ** for the given FROM clause entry as would be selected if the entry
98846     ** were used as the innermost nested loop.  In other words, a table
98847     ** is chosen such that the cost of running that table cannot be reduced
98848     ** by waiting for other tables to run first.  This "optimal" test works
98849     ** by first assuming that the FROM clause is on the inner loop and finding
98850     ** its query plan, then checking to see if that query plan uses any
98851     ** other FROM clause terms that are notReady.  If no notReady terms are
98852     ** used then the "optimal" query plan works.
98853     **
98854     ** Note that the WhereCost.nRow parameter for an optimal scan might
98855     ** not be as small as it would be if the table really were the innermost
98856     ** join.  The nRow value can be reduced by WHERE clause constraints
98857     ** that do not use indices.  But this nRow reduction only happens if the
98858     ** table really is the innermost join.  
98859     **
98860     ** The second loop iteration is only performed if no optimal scan
98861     ** strategies were found by the first iteration. This second iteration
98862     ** is used to search for the lowest cost scan overall.
98863     **
98864     ** Previous versions of SQLite performed only the second iteration -
98865     ** the next outermost loop was always that with the lowest overall
98866     ** cost. However, this meant that SQLite could select the wrong plan
98867     ** for scripts such as the following:
98868     **   
98869     **   CREATE TABLE t1(a, b); 
98870     **   CREATE TABLE t2(c, d);
98871     **   SELECT * FROM t2, t1 WHERE t2.rowid = t1.a;
98872     **
98873     ** The best strategy is to iterate through table t1 first. However it
98874     ** is not possible to determine this with a simple greedy algorithm.
98875     ** Since the cost of a linear scan through table t2 is the same 
98876     ** as the cost of a linear scan through table t1, a simple greedy 
98877     ** algorithm may choose to use t2 for the outer loop, which is a much
98878     ** costlier approach.
98879     */
98880     nUnconstrained = 0;
98881     notIndexed = 0;
98882     for(isOptimal=(iFrom<nTabList-1); isOptimal>=0 && bestJ<0; isOptimal--){
98883       Bitmask mask;             /* Mask of tables not yet ready */
98884       for(j=iFrom, pTabItem=&pTabList->a[j]; j<nTabList; j++, pTabItem++){
98885         int doNotReorder;    /* True if this table should not be reordered */
98886         WhereCost sCost;     /* Cost information from best[Virtual]Index() */
98887         ExprList *pOrderBy;  /* ORDER BY clause for index to optimize */
98888   
98889         doNotReorder =  (pTabItem->jointype & (JT_LEFT|JT_CROSS))!=0;
98890         if( j!=iFrom && doNotReorder ) break;
98891         m = getMask(pMaskSet, pTabItem->iCursor);
98892         if( (m & notReady)==0 ){
98893           if( j==iFrom ) iFrom++;
98894           continue;
98895         }
98896         mask = (isOptimal ? m : notReady);
98897         pOrderBy = ((i==0 && ppOrderBy )?*ppOrderBy:0);
98898         if( pTabItem->pIndex==0 ) nUnconstrained++;
98899   
98900         assert( pTabItem->pTab );
98901 #ifndef SQLITE_OMIT_VIRTUALTABLE
98902         if( IsVirtual(pTabItem->pTab) ){
98903           sqlite3_index_info **pp = &pWInfo->a[j].pIdxInfo;
98904           bestVirtualIndex(pParse, pWC, pTabItem, mask, notReady, pOrderBy,
98905                            &sCost, pp);
98906         }else 
98907 #endif
98908         {
98909           bestBtreeIndex(pParse, pWC, pTabItem, mask, notReady, pOrderBy,
98910                          &sCost);
98911         }
98912         assert( isOptimal || (sCost.used&notReady)==0 );
98913
98914         /* If an INDEXED BY clause is present, then the plan must use that
98915         ** index if it uses any index at all */
98916         assert( pTabItem->pIndex==0 
98917                   || (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0
98918                   || sCost.plan.u.pIdx==pTabItem->pIndex );
98919
98920         if( isOptimal && (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ){
98921           notIndexed |= m;
98922         }
98923
98924         /* Conditions under which this table becomes the best so far:
98925         **
98926         **   (1) The table must not depend on other tables that have not
98927         **       yet run.
98928         **
98929         **   (2) A full-table-scan plan cannot supercede another plan unless
98930         **       it is an "optimal" plan as defined above.
98931         **
98932         **   (3) All tables have an INDEXED BY clause or this table lacks an
98933         **       INDEXED BY clause or this table uses the specific
98934         **       index specified by its INDEXED BY clause.  This rule ensures
98935         **       that a best-so-far is always selected even if an impossible
98936         **       combination of INDEXED BY clauses are given.  The error
98937         **       will be detected and relayed back to the application later.
98938         **       The NEVER() comes about because rule (2) above prevents
98939         **       An indexable full-table-scan from reaching rule (3).
98940         **
98941         **   (4) The plan cost must be lower than prior plans or else the
98942         **       cost must be the same and the number of rows must be lower.
98943         */
98944         if( (sCost.used&notReady)==0                       /* (1) */
98945             && (bestJ<0 || (notIndexed&m)!=0               /* (2) */
98946                 || (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0)
98947             && (nUnconstrained==0 || pTabItem->pIndex==0   /* (3) */
98948                 || NEVER((sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0))
98949             && (bestJ<0 || sCost.rCost<bestPlan.rCost      /* (4) */
98950                 || (sCost.rCost<=bestPlan.rCost && sCost.nRow<bestPlan.nRow))
98951         ){
98952           WHERETRACE(("... best so far with cost=%g and nRow=%g\n",
98953                       sCost.rCost, sCost.nRow));
98954           bestPlan = sCost;
98955           bestJ = j;
98956         }
98957         if( doNotReorder ) break;
98958       }
98959     }
98960     assert( bestJ>=0 );
98961     assert( notReady & getMask(pMaskSet, pTabList->a[bestJ].iCursor) );
98962     WHERETRACE(("*** Optimizer selects table %d for loop %d\n", bestJ,
98963            pLevel-pWInfo->a));
98964     if( (bestPlan.plan.wsFlags & WHERE_ORDERBY)!=0 ){
98965       *ppOrderBy = 0;
98966     }
98967     andFlags &= bestPlan.plan.wsFlags;
98968     pLevel->plan = bestPlan.plan;
98969     testcase( bestPlan.plan.wsFlags & WHERE_INDEXED );
98970     testcase( bestPlan.plan.wsFlags & WHERE_TEMP_INDEX );
98971     if( bestPlan.plan.wsFlags & (WHERE_INDEXED|WHERE_TEMP_INDEX) ){
98972       pLevel->iIdxCur = pParse->nTab++;
98973     }else{
98974       pLevel->iIdxCur = -1;
98975     }
98976     notReady &= ~getMask(pMaskSet, pTabList->a[bestJ].iCursor);
98977     pLevel->iFrom = (u8)bestJ;
98978     if( bestPlan.nRow>=(double)1 ) pParse->nQueryLoop *= bestPlan.nRow;
98979
98980     /* Check that if the table scanned by this loop iteration had an
98981     ** INDEXED BY clause attached to it, that the named index is being
98982     ** used for the scan. If not, then query compilation has failed.
98983     ** Return an error.
98984     */
98985     pIdx = pTabList->a[bestJ].pIndex;
98986     if( pIdx ){
98987       if( (bestPlan.plan.wsFlags & WHERE_INDEXED)==0 ){
98988         sqlite3ErrorMsg(pParse, "cannot use index: %s", pIdx->zName);
98989         goto whereBeginError;
98990       }else{
98991         /* If an INDEXED BY clause is used, the bestIndex() function is
98992         ** guaranteed to find the index specified in the INDEXED BY clause
98993         ** if it find an index at all. */
98994         assert( bestPlan.plan.u.pIdx==pIdx );
98995       }
98996     }
98997   }
98998   WHERETRACE(("*** Optimizer Finished ***\n"));
98999   if( pParse->nErr || db->mallocFailed ){
99000     goto whereBeginError;
99001   }
99002
99003   /* If the total query only selects a single row, then the ORDER BY
99004   ** clause is irrelevant.
99005   */
99006   if( (andFlags & WHERE_UNIQUE)!=0 && ppOrderBy ){
99007     *ppOrderBy = 0;
99008   }
99009
99010   /* If the caller is an UPDATE or DELETE statement that is requesting
99011   ** to use a one-pass algorithm, determine if this is appropriate.
99012   ** The one-pass algorithm only works if the WHERE clause constraints
99013   ** the statement to update a single row.
99014   */
99015   assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
99016   if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 && (andFlags & WHERE_UNIQUE)!=0 ){
99017     pWInfo->okOnePass = 1;
99018     pWInfo->a[0].plan.wsFlags &= ~WHERE_IDX_ONLY;
99019   }
99020
99021   /* Open all tables in the pTabList and any indices selected for
99022   ** searching those tables.
99023   */
99024   sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
99025   notReady = ~(Bitmask)0;
99026   for(i=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
99027     Table *pTab;     /* Table to open */
99028     int iDb;         /* Index of database containing table/index */
99029
99030 #ifndef SQLITE_OMIT_EXPLAIN
99031     if( pParse->explain==2 ){
99032       char *zMsg;
99033       struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
99034       zMsg = sqlite3MPrintf(db, "TABLE %s", pItem->zName);
99035       if( pItem->zAlias ){
99036         zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
99037       }
99038       if( (pLevel->plan.wsFlags & WHERE_TEMP_INDEX)!=0 ){
99039         zMsg = sqlite3MAppendf(db, zMsg, "%s WITH AUTOMATIC INDEX", zMsg);
99040       }else if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
99041         zMsg = sqlite3MAppendf(db, zMsg, "%s WITH INDEX %s",
99042            zMsg, pLevel->plan.u.pIdx->zName);
99043       }else if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
99044         zMsg = sqlite3MAppendf(db, zMsg, "%s VIA MULTI-INDEX UNION", zMsg);
99045       }else if( pLevel->plan.wsFlags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
99046         zMsg = sqlite3MAppendf(db, zMsg, "%s USING PRIMARY KEY", zMsg);
99047       }
99048 #ifndef SQLITE_OMIT_VIRTUALTABLE
99049       else if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
99050         sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
99051         zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
99052                     pVtabIdx->idxNum, pVtabIdx->idxStr);
99053       }
99054 #endif
99055       if( pLevel->plan.wsFlags & WHERE_ORDERBY ){
99056         zMsg = sqlite3MAppendf(db, zMsg, "%s ORDER BY", zMsg);
99057       }
99058       sqlite3VdbeAddOp4(v, OP_Explain, i, pLevel->iFrom, 0, zMsg, P4_DYNAMIC);
99059     }
99060 #endif /* SQLITE_OMIT_EXPLAIN */
99061     pTabItem = &pTabList->a[pLevel->iFrom];
99062     pTab = pTabItem->pTab;
99063     pLevel->iTabCur = pTabItem->iCursor;
99064     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
99065     if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
99066       /* Do nothing */
99067     }else
99068 #ifndef SQLITE_OMIT_VIRTUALTABLE
99069     if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
99070       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
99071       int iCur = pTabItem->iCursor;
99072       sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
99073     }else
99074 #endif
99075     if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
99076          && (wctrlFlags & WHERE_OMIT_OPEN)==0 ){
99077       int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
99078       sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
99079       testcase( pTab->nCol==BMS-1 );
99080       testcase( pTab->nCol==BMS );
99081       if( !pWInfo->okOnePass && pTab->nCol<BMS ){
99082         Bitmask b = pTabItem->colUsed;
99083         int n = 0;
99084         for(; b; b=b>>1, n++){}
99085         sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1, 
99086                             SQLITE_INT_TO_PTR(n), P4_INT32);
99087         assert( n<=pTab->nCol );
99088       }
99089     }else{
99090       sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
99091     }
99092 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
99093     if( (pLevel->plan.wsFlags & WHERE_TEMP_INDEX)!=0 ){
99094       constructAutomaticIndex(pParse, pWC, pTabItem, notReady, pLevel);
99095     }else
99096 #endif
99097     if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
99098       Index *pIx = pLevel->plan.u.pIdx;
99099       KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
99100       int iIdxCur = pLevel->iIdxCur;
99101       assert( pIx->pSchema==pTab->pSchema );
99102       assert( iIdxCur>=0 );
99103       sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIx->tnum, iDb,
99104                         (char*)pKey, P4_KEYINFO_HANDOFF);
99105       VdbeComment((v, "%s", pIx->zName));
99106     }
99107     sqlite3CodeVerifySchema(pParse, iDb);
99108     notReady &= ~getMask(pWC->pMaskSet, pTabItem->iCursor);
99109   }
99110   pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
99111   if( db->mallocFailed ) goto whereBeginError;
99112
99113   /* Generate the code to do the search.  Each iteration of the for
99114   ** loop below generates code for a single nested loop of the VM
99115   ** program.
99116   */
99117   notReady = ~(Bitmask)0;
99118   for(i=0; i<nTabList; i++){
99119     notReady = codeOneLoopStart(pWInfo, i, wctrlFlags, notReady);
99120     pWInfo->iContinue = pWInfo->a[i].addrCont;
99121   }
99122
99123 #ifdef SQLITE_TEST  /* For testing and debugging use only */
99124   /* Record in the query plan information about the current table
99125   ** and the index used to access it (if any).  If the table itself
99126   ** is not used, its name is just '{}'.  If no index is used
99127   ** the index is listed as "{}".  If the primary key is used the
99128   ** index name is '*'.
99129   */
99130   for(i=0; i<nTabList; i++){
99131     char *z;
99132     int n;
99133     pLevel = &pWInfo->a[i];
99134     pTabItem = &pTabList->a[pLevel->iFrom];
99135     z = pTabItem->zAlias;
99136     if( z==0 ) z = pTabItem->pTab->zName;
99137     n = sqlite3Strlen30(z);
99138     if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
99139       if( pLevel->plan.wsFlags & WHERE_IDX_ONLY ){
99140         memcpy(&sqlite3_query_plan[nQPlan], "{}", 2);
99141         nQPlan += 2;
99142       }else{
99143         memcpy(&sqlite3_query_plan[nQPlan], z, n);
99144         nQPlan += n;
99145       }
99146       sqlite3_query_plan[nQPlan++] = ' ';
99147     }
99148     testcase( pLevel->plan.wsFlags & WHERE_ROWID_EQ );
99149     testcase( pLevel->plan.wsFlags & WHERE_ROWID_RANGE );
99150     if( pLevel->plan.wsFlags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
99151       memcpy(&sqlite3_query_plan[nQPlan], "* ", 2);
99152       nQPlan += 2;
99153     }else if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
99154       n = sqlite3Strlen30(pLevel->plan.u.pIdx->zName);
99155       if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
99156         memcpy(&sqlite3_query_plan[nQPlan], pLevel->plan.u.pIdx->zName, n);
99157         nQPlan += n;
99158         sqlite3_query_plan[nQPlan++] = ' ';
99159       }
99160     }else{
99161       memcpy(&sqlite3_query_plan[nQPlan], "{} ", 3);
99162       nQPlan += 3;
99163     }
99164   }
99165   while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
99166     sqlite3_query_plan[--nQPlan] = 0;
99167   }
99168   sqlite3_query_plan[nQPlan] = 0;
99169   nQPlan = 0;
99170 #endif /* SQLITE_TEST // Testing and debugging use only */
99171
99172   /* Record the continuation address in the WhereInfo structure.  Then
99173   ** clean up and return.
99174   */
99175   return pWInfo;
99176
99177   /* Jump here if malloc fails */
99178 whereBeginError:
99179   if( pWInfo ){
99180     pParse->nQueryLoop = pWInfo->savedNQueryLoop;
99181     whereInfoFree(db, pWInfo);
99182   }
99183   return 0;
99184 }
99185
99186 /*
99187 ** Generate the end of the WHERE loop.  See comments on 
99188 ** sqlite3WhereBegin() for additional information.
99189 */
99190 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
99191   Parse *pParse = pWInfo->pParse;
99192   Vdbe *v = pParse->pVdbe;
99193   int i;
99194   WhereLevel *pLevel;
99195   SrcList *pTabList = pWInfo->pTabList;
99196   sqlite3 *db = pParse->db;
99197
99198   /* Generate loop termination code.
99199   */
99200   sqlite3ExprCacheClear(pParse);
99201   for(i=pWInfo->nLevel-1; i>=0; i--){
99202     pLevel = &pWInfo->a[i];
99203     sqlite3VdbeResolveLabel(v, pLevel->addrCont);
99204     if( pLevel->op!=OP_Noop ){
99205       sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
99206       sqlite3VdbeChangeP5(v, pLevel->p5);
99207     }
99208     if( pLevel->plan.wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
99209       struct InLoop *pIn;
99210       int j;
99211       sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
99212       for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
99213         sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
99214         sqlite3VdbeAddOp2(v, OP_Next, pIn->iCur, pIn->addrInTop);
99215         sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
99216       }
99217       sqlite3DbFree(db, pLevel->u.in.aInLoop);
99218     }
99219     sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
99220     if( pLevel->iLeftJoin ){
99221       int addr;
99222       addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
99223       assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
99224            || (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 );
99225       if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0 ){
99226         sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
99227       }
99228       if( pLevel->iIdxCur>=0 ){
99229         sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
99230       }
99231       if( pLevel->op==OP_Return ){
99232         sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
99233       }else{
99234         sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
99235       }
99236       sqlite3VdbeJumpHere(v, addr);
99237     }
99238   }
99239
99240   /* The "break" point is here, just past the end of the outer loop.
99241   ** Set it.
99242   */
99243   sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
99244
99245   /* Close all of the cursors that were opened by sqlite3WhereBegin.
99246   */
99247   assert( pWInfo->nLevel==1 || pWInfo->nLevel==pTabList->nSrc );
99248   for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
99249     struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
99250     Table *pTab = pTabItem->pTab;
99251     assert( pTab!=0 );
99252     if( (pTab->tabFlags & TF_Ephemeral)==0
99253      && pTab->pSelect==0
99254      && (pWInfo->wctrlFlags & WHERE_OMIT_CLOSE)==0
99255     ){
99256       int ws = pLevel->plan.wsFlags;
99257       if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
99258         sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
99259       }
99260       if( (ws & WHERE_INDEXED)!=0 && (ws & WHERE_TEMP_INDEX)==0 ){
99261         sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
99262       }
99263     }
99264
99265     /* If this scan uses an index, make code substitutions to read data
99266     ** from the index in preference to the table. Sometimes, this means
99267     ** the table need never be read from. This is a performance boost,
99268     ** as the vdbe level waits until the table is read before actually
99269     ** seeking the table cursor to the record corresponding to the current
99270     ** position in the index.
99271     ** 
99272     ** Calls to the code generator in between sqlite3WhereBegin and
99273     ** sqlite3WhereEnd will have created code that references the table
99274     ** directly.  This loop scans all that code looking for opcodes
99275     ** that reference the table and converts them into opcodes that
99276     ** reference the index.
99277     */
99278     if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 && !db->mallocFailed){
99279       int k, j, last;
99280       VdbeOp *pOp;
99281       Index *pIdx = pLevel->plan.u.pIdx;
99282
99283       assert( pIdx!=0 );
99284       pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
99285       last = sqlite3VdbeCurrentAddr(v);
99286       for(k=pWInfo->iTop; k<last; k++, pOp++){
99287         if( pOp->p1!=pLevel->iTabCur ) continue;
99288         if( pOp->opcode==OP_Column ){
99289           for(j=0; j<pIdx->nColumn; j++){
99290             if( pOp->p2==pIdx->aiColumn[j] ){
99291               pOp->p2 = j;
99292               pOp->p1 = pLevel->iIdxCur;
99293               break;
99294             }
99295           }
99296           assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
99297                || j<pIdx->nColumn );
99298         }else if( pOp->opcode==OP_Rowid ){
99299           pOp->p1 = pLevel->iIdxCur;
99300           pOp->opcode = OP_IdxRowid;
99301         }
99302       }
99303     }
99304   }
99305
99306   /* Final cleanup
99307   */
99308   pParse->nQueryLoop = pWInfo->savedNQueryLoop;
99309   whereInfoFree(db, pWInfo);
99310   return;
99311 }
99312
99313 /************** End of where.c ***********************************************/
99314 /************** Begin file parse.c *******************************************/
99315 /* Driver template for the LEMON parser generator.
99316 ** The author disclaims copyright to this source code.
99317 **
99318 ** This version of "lempar.c" is modified, slightly, for use by SQLite.
99319 ** The only modifications are the addition of a couple of NEVER()
99320 ** macros to disable tests that are needed in the case of a general
99321 ** LALR(1) grammar but which are always false in the
99322 ** specific grammar used by SQLite.
99323 */
99324 /* First off, code is included that follows the "include" declaration
99325 ** in the input grammar file. */
99326
99327
99328 /*
99329 ** Disable all error recovery processing in the parser push-down
99330 ** automaton.
99331 */
99332 #define YYNOERRORRECOVERY 1
99333
99334 /*
99335 ** Make yytestcase() the same as testcase()
99336 */
99337 #define yytestcase(X) testcase(X)
99338
99339 /*
99340 ** An instance of this structure holds information about the
99341 ** LIMIT clause of a SELECT statement.
99342 */
99343 struct LimitVal {
99344   Expr *pLimit;    /* The LIMIT expression.  NULL if there is no limit */
99345   Expr *pOffset;   /* The OFFSET expression.  NULL if there is none */
99346 };
99347
99348 /*
99349 ** An instance of this structure is used to store the LIKE,
99350 ** GLOB, NOT LIKE, and NOT GLOB operators.
99351 */
99352 struct LikeOp {
99353   Token eOperator;  /* "like" or "glob" or "regexp" */
99354   int not;         /* True if the NOT keyword is present */
99355 };
99356
99357 /*
99358 ** An instance of the following structure describes the event of a
99359 ** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
99360 ** TK_DELETE, or TK_INSTEAD.  If the event is of the form
99361 **
99362 **      UPDATE ON (a,b,c)
99363 **
99364 ** Then the "b" IdList records the list "a,b,c".
99365 */
99366 struct TrigEvent { int a; IdList * b; };
99367
99368 /*
99369 ** An instance of this structure holds the ATTACH key and the key type.
99370 */
99371 struct AttachKey { int type;  Token key; };
99372
99373
99374   /* This is a utility routine used to set the ExprSpan.zStart and
99375   ** ExprSpan.zEnd values of pOut so that the span covers the complete
99376   ** range of text beginning with pStart and going to the end of pEnd.
99377   */
99378   static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
99379     pOut->zStart = pStart->z;
99380     pOut->zEnd = &pEnd->z[pEnd->n];
99381   }
99382
99383   /* Construct a new Expr object from a single identifier.  Use the
99384   ** new Expr to populate pOut.  Set the span of pOut to be the identifier
99385   ** that created the expression.
99386   */
99387   static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
99388     pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
99389     pOut->zStart = pValue->z;
99390     pOut->zEnd = &pValue->z[pValue->n];
99391   }
99392
99393   /* This routine constructs a binary expression node out of two ExprSpan
99394   ** objects and uses the result to populate a new ExprSpan object.
99395   */
99396   static void spanBinaryExpr(
99397     ExprSpan *pOut,     /* Write the result here */
99398     Parse *pParse,      /* The parsing context.  Errors accumulate here */
99399     int op,             /* The binary operation */
99400     ExprSpan *pLeft,    /* The left operand */
99401     ExprSpan *pRight    /* The right operand */
99402   ){
99403     pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
99404     pOut->zStart = pLeft->zStart;
99405     pOut->zEnd = pRight->zEnd;
99406   }
99407
99408   /* Construct an expression node for a unary postfix operator
99409   */
99410   static void spanUnaryPostfix(
99411     ExprSpan *pOut,        /* Write the new expression node here */
99412     Parse *pParse,         /* Parsing context to record errors */
99413     int op,                /* The operator */
99414     ExprSpan *pOperand,    /* The operand */
99415     Token *pPostOp         /* The operand token for setting the span */
99416   ){
99417     pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
99418     pOut->zStart = pOperand->zStart;
99419     pOut->zEnd = &pPostOp->z[pPostOp->n];
99420   }                           
99421
99422   /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
99423   ** unary TK_ISNULL or TK_NOTNULL expression. */
99424   static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
99425     sqlite3 *db = pParse->db;
99426     if( db->mallocFailed==0 && pY->op==TK_NULL ){
99427       pA->op = (u8)op;
99428       sqlite3ExprDelete(db, pA->pRight);
99429       pA->pRight = 0;
99430     }
99431   }
99432
99433   /* Construct an expression node for a unary prefix operator
99434   */
99435   static void spanUnaryPrefix(
99436     ExprSpan *pOut,        /* Write the new expression node here */
99437     Parse *pParse,         /* Parsing context to record errors */
99438     int op,                /* The operator */
99439     ExprSpan *pOperand,    /* The operand */
99440     Token *pPreOp         /* The operand token for setting the span */
99441   ){
99442     pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
99443     pOut->zStart = pPreOp->z;
99444     pOut->zEnd = pOperand->zEnd;
99445   }
99446 /* Next is all token values, in a form suitable for use by makeheaders.
99447 ** This section will be null unless lemon is run with the -m switch.
99448 */
99449 /* 
99450 ** These constants (all generated automatically by the parser generator)
99451 ** specify the various kinds of tokens (terminals) that the parser
99452 ** understands. 
99453 **
99454 ** Each symbol here is a terminal symbol in the grammar.
99455 */
99456 /* Make sure the INTERFACE macro is defined.
99457 */
99458 #ifndef INTERFACE
99459 # define INTERFACE 1
99460 #endif
99461 /* The next thing included is series of defines which control
99462 ** various aspects of the generated parser.
99463 **    YYCODETYPE         is the data type used for storing terminal
99464 **                       and nonterminal numbers.  "unsigned char" is
99465 **                       used if there are fewer than 250 terminals
99466 **                       and nonterminals.  "int" is used otherwise.
99467 **    YYNOCODE           is a number of type YYCODETYPE which corresponds
99468 **                       to no legal terminal or nonterminal number.  This
99469 **                       number is used to fill in empty slots of the hash 
99470 **                       table.
99471 **    YYFALLBACK         If defined, this indicates that one or more tokens
99472 **                       have fall-back values which should be used if the
99473 **                       original value of the token will not parse.
99474 **    YYACTIONTYPE       is the data type used for storing terminal
99475 **                       and nonterminal numbers.  "unsigned char" is
99476 **                       used if there are fewer than 250 rules and
99477 **                       states combined.  "int" is used otherwise.
99478 **    sqlite3ParserTOKENTYPE     is the data type used for minor tokens given 
99479 **                       directly to the parser from the tokenizer.
99480 **    YYMINORTYPE        is the data type used for all minor tokens.
99481 **                       This is typically a union of many types, one of
99482 **                       which is sqlite3ParserTOKENTYPE.  The entry in the union
99483 **                       for base tokens is called "yy0".
99484 **    YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
99485 **                       zero the stack is dynamically sized using realloc()
99486 **    sqlite3ParserARG_SDECL     A static variable declaration for the %extra_argument
99487 **    sqlite3ParserARG_PDECL     A parameter declaration for the %extra_argument
99488 **    sqlite3ParserARG_STORE     Code to store %extra_argument into yypParser
99489 **    sqlite3ParserARG_FETCH     Code to extract %extra_argument from yypParser
99490 **    YYNSTATE           the combined number of states.
99491 **    YYNRULE            the number of rules in the grammar
99492 **    YYERRORSYMBOL      is the code number of the error symbol.  If not
99493 **                       defined, then do no error processing.
99494 */
99495 #define YYCODETYPE unsigned char
99496 #define YYNOCODE 253
99497 #define YYACTIONTYPE unsigned short int
99498 #define YYWILDCARD 67
99499 #define sqlite3ParserTOKENTYPE Token
99500 typedef union {
99501   int yyinit;
99502   sqlite3ParserTOKENTYPE yy0;
99503   int yy4;
99504   struct TrigEvent yy90;
99505   ExprSpan yy118;
99506   TriggerStep* yy203;
99507   u8 yy210;
99508   struct {int value; int mask;} yy215;
99509   SrcList* yy259;
99510   struct LimitVal yy292;
99511   Expr* yy314;
99512   ExprList* yy322;
99513   struct LikeOp yy342;
99514   IdList* yy384;
99515   Select* yy387;
99516 } YYMINORTYPE;
99517 #ifndef YYSTACKDEPTH
99518 #define YYSTACKDEPTH 100
99519 #endif
99520 #define sqlite3ParserARG_SDECL Parse *pParse;
99521 #define sqlite3ParserARG_PDECL ,Parse *pParse
99522 #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
99523 #define sqlite3ParserARG_STORE yypParser->pParse = pParse
99524 #define YYNSTATE 630
99525 #define YYNRULE 329
99526 #define YYFALLBACK 1
99527 #define YY_NO_ACTION      (YYNSTATE+YYNRULE+2)
99528 #define YY_ACCEPT_ACTION  (YYNSTATE+YYNRULE+1)
99529 #define YY_ERROR_ACTION   (YYNSTATE+YYNRULE)
99530
99531 /* The yyzerominor constant is used to initialize instances of
99532 ** YYMINORTYPE objects to zero. */
99533 static const YYMINORTYPE yyzerominor = { 0 };
99534
99535 /* Define the yytestcase() macro to be a no-op if is not already defined
99536 ** otherwise.
99537 **
99538 ** Applications can choose to define yytestcase() in the %include section
99539 ** to a macro that can assist in verifying code coverage.  For production
99540 ** code the yytestcase() macro should be turned off.  But it is useful
99541 ** for testing.
99542 */
99543 #ifndef yytestcase
99544 # define yytestcase(X)
99545 #endif
99546
99547
99548 /* Next are the tables used to determine what action to take based on the
99549 ** current state and lookahead token.  These tables are used to implement
99550 ** functions that take a state number and lookahead value and return an
99551 ** action integer.  
99552 **
99553 ** Suppose the action integer is N.  Then the action is determined as
99554 ** follows
99555 **
99556 **   0 <= N < YYNSTATE                  Shift N.  That is, push the lookahead
99557 **                                      token onto the stack and goto state N.
99558 **
99559 **   YYNSTATE <= N < YYNSTATE+YYNRULE   Reduce by rule N-YYNSTATE.
99560 **
99561 **   N == YYNSTATE+YYNRULE              A syntax error has occurred.
99562 **
99563 **   N == YYNSTATE+YYNRULE+1            The parser accepts its input.
99564 **
99565 **   N == YYNSTATE+YYNRULE+2            No such action.  Denotes unused
99566 **                                      slots in the yy_action[] table.
99567 **
99568 ** The action table is constructed as a single large table named yy_action[].
99569 ** Given state S and lookahead X, the action is computed as
99570 **
99571 **      yy_action[ yy_shift_ofst[S] + X ]
99572 **
99573 ** If the index value yy_shift_ofst[S]+X is out of range or if the value
99574 ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
99575 ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
99576 ** and that yy_default[S] should be used instead.  
99577 **
99578 ** The formula above is for computing the action when the lookahead is
99579 ** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
99580 ** a reduce action) then the yy_reduce_ofst[] array is used in place of
99581 ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
99582 ** YY_SHIFT_USE_DFLT.
99583 **
99584 ** The following are the tables generated in this section:
99585 **
99586 **  yy_action[]        A single table containing all actions.
99587 **  yy_lookahead[]     A table containing the lookahead for each entry in
99588 **                     yy_action.  Used to detect hash collisions.
99589 **  yy_shift_ofst[]    For each state, the offset into yy_action for
99590 **                     shifting terminals.
99591 **  yy_reduce_ofst[]   For each state, the offset into yy_action for
99592 **                     shifting non-terminals after a reduce.
99593 **  yy_default[]       Default action for each state.
99594 */
99595 #define YY_ACTTAB_COUNT (1557)
99596 static const YYACTIONTYPE yy_action[] = {
99597  /*     0 */   313,  960,  186,  419,    2,  172,  627,  597,   55,   55,
99598  /*    10 */    55,   55,   48,   53,   53,   53,   53,   52,   52,   51,
99599  /*    20 */    51,   51,   50,  238,  302,  283,  623,  622,  516,  515,
99600  /*    30 */   590,  584,   55,   55,   55,   55,  282,   53,   53,   53,
99601  /*    40 */    53,   52,   52,   51,   51,   51,   50,  238,    6,   56,
99602  /*    50 */    57,   47,  582,  581,  583,  583,   54,   54,   55,   55,
99603  /*    60 */    55,   55,  608,   53,   53,   53,   53,   52,   52,   51,
99604  /*    70 */    51,   51,   50,  238,  313,  597,  409,  330,  579,  579,
99605  /*    80 */    32,   53,   53,   53,   53,   52,   52,   51,   51,   51,
99606  /*    90 */    50,  238,  330,  217,  620,  619,  166,  411,  624,  382,
99607  /*   100 */   379,  378,    7,  491,  590,  584,  200,  199,  198,   58,
99608  /*   110 */   377,  300,  414,  621,  481,   66,  623,  622,  621,  580,
99609  /*   120 */   254,  601,   94,   56,   57,   47,  582,  581,  583,  583,
99610  /*   130 */    54,   54,   55,   55,   55,   55,  671,   53,   53,   53,
99611  /*   140 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  532,
99612  /*   150 */   226,  506,  507,  133,  177,  139,  284,  385,  279,  384,
99613  /*   160 */   169,  197,  342,  398,  251,  226,  253,  275,  388,  167,
99614  /*   170 */   139,  284,  385,  279,  384,  169,  570,  236,  590,  584,
99615  /*   180 */   672,  240,  275,  157,  620,  619,  554,  437,   51,   51,
99616  /*   190 */    51,   50,  238,  343,  439,  553,  438,   56,   57,   47,
99617  /*   200 */   582,  581,  583,  583,   54,   54,   55,   55,   55,   55,
99618  /*   210 */   465,   53,   53,   53,   53,   52,   52,   51,   51,   51,
99619  /*   220 */    50,  238,  313,  390,   52,   52,   51,   51,   51,   50,
99620  /*   230 */   238,  391,  166,  491,  566,  382,  379,  378,  409,  440,
99621  /*   240 */   579,  579,  252,  440,  607,   66,  377,  513,  621,   49,
99622  /*   250 */    46,  147,  590,  584,  621,   16,  466,  189,  621,  441,
99623  /*   260 */   442,  673,  526,  441,  340,  577,  595,   64,  194,  482,
99624  /*   270 */   434,   56,   57,   47,  582,  581,  583,  583,   54,   54,
99625  /*   280 */    55,   55,   55,   55,   30,   53,   53,   53,   53,   52,
99626  /*   290 */    52,   51,   51,   51,   50,  238,  313,  593,  593,  593,
99627  /*   300 */   387,  578,  606,  493,  259,  351,  258,  411,    1,  623,
99628  /*   310 */   622,  496,  623,  622,   65,  240,  623,  622,  597,  443,
99629  /*   320 */   237,  239,  414,  341,  237,  602,  590,  584,   18,  603,
99630  /*   330 */   166,  601,   87,  382,  379,  378,   67,  623,  622,   38,
99631  /*   340 */   623,  622,  176,  270,  377,   56,   57,   47,  582,  581,
99632  /*   350 */   583,  583,   54,   54,   55,   55,   55,   55,  175,   53,
99633  /*   360 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
99634  /*   370 */   313,  396,  233,  411,  531,  565,  317,  620,  619,   44,
99635  /*   380 */   620,  619,  240,  206,  620,  619,  597,  266,  414,  268,
99636  /*   390 */   409,  597,  579,  579,  352,  184,  505,  601,   73,  533,
99637  /*   400 */   590,  584,  466,  548,  190,  620,  619,  576,  620,  619,
99638  /*   410 */   547,  383,  551,   35,  332,  575,  574,  600,  504,   56,
99639  /*   420 */    57,   47,  582,  581,  583,  583,   54,   54,   55,   55,
99640  /*   430 */    55,   55,  567,   53,   53,   53,   53,   52,   52,   51,
99641  /*   440 */    51,   51,   50,  238,  313,  411,  561,  561,  528,  364,
99642  /*   450 */   259,  351,  258,  183,  361,  549,  524,  374,  411,  597,
99643  /*   460 */   414,  240,  560,  560,  409,  604,  579,  579,  328,  601,
99644  /*   470 */    93,  623,  622,  414,  590,  584,  237,  564,  559,  559,
99645  /*   480 */   520,  402,  601,   87,  409,  210,  579,  579,  168,  421,
99646  /*   490 */   950,  519,  950,   56,   57,   47,  582,  581,  583,  583,
99647  /*   500 */    54,   54,   55,   55,   55,   55,  192,   53,   53,   53,
99648  /*   510 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  600,
99649  /*   520 */   293,  563,  511,  234,  357,  146,  475,  475,  367,  411,
99650  /*   530 */   562,  411,  358,  542,  425,  171,  411,  215,  144,  620,
99651  /*   540 */   619,  544,  318,  353,  414,  203,  414,  275,  590,  584,
99652  /*   550 */   549,  414,  174,  601,   94,  601,   79,  558,  471,   61,
99653  /*   560 */   601,   79,  421,  949,  350,  949,   34,   56,   57,   47,
99654  /*   570 */   582,  581,  583,  583,   54,   54,   55,   55,   55,   55,
99655  /*   580 */   535,   53,   53,   53,   53,   52,   52,   51,   51,   51,
99656  /*   590 */    50,  238,  313,  307,  424,  394,  272,   49,   46,  147,
99657  /*   600 */   349,  322,    4,  411,  491,  312,  321,  425,  568,  492,
99658  /*   610 */   216,  264,  407,  575,  574,  429,   66,  549,  414,  621,
99659  /*   620 */   540,  602,  590,  584,   13,  603,  621,  601,   72,   12,
99660  /*   630 */   618,  617,  616,  202,  210,  621,  546,  469,  422,  319,
99661  /*   640 */   148,   56,   57,   47,  582,  581,  583,  583,   54,   54,
99662  /*   650 */    55,   55,   55,   55,  338,   53,   53,   53,   53,   52,
99663  /*   660 */    52,   51,   51,   51,   50,  238,  313,  600,  600,  411,
99664  /*   670 */    39,   21,   37,  170,  237,  875,  411,  572,  572,  201,
99665  /*   680 */   144,  473,  538,  331,  414,  474,  143,  146,  630,  628,
99666  /*   690 */   334,  414,  353,  601,   68,  168,  590,  584,  132,  365,
99667  /*   700 */   601,   96,  307,  423,  530,  336,   49,   46,  147,  568,
99668  /*   710 */   406,  216,  549,  360,  529,   56,   57,   47,  582,  581,
99669  /*   720 */   583,  583,   54,   54,   55,   55,   55,   55,  411,   53,
99670  /*   730 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
99671  /*   740 */   313,  411,  605,  414,  484,  510,  172,  422,  597,  318,
99672  /*   750 */   496,  485,  601,   99,  411,  142,  414,  411,  231,  411,
99673  /*   760 */   540,  411,  359,  629,    2,  601,   97,  426,  308,  414,
99674  /*   770 */   590,  584,  414,   20,  414,  621,  414,  621,  601,  106,
99675  /*   780 */   503,  601,  105,  601,  108,  601,  109,  204,   28,   56,
99676  /*   790 */    57,   47,  582,  581,  583,  583,   54,   54,   55,   55,
99677  /*   800 */    55,   55,  411,   53,   53,   53,   53,   52,   52,   51,
99678  /*   810 */    51,   51,   50,  238,  313,  411,  597,  414,  411,  276,
99679  /*   820 */   214,  600,  411,  366,  213,  381,  601,  134,  274,  500,
99680  /*   830 */   414,  167,  130,  414,  621,  411,  354,  414,  376,  601,
99681  /*   840 */   135,  129,  601,  100,  590,  584,  601,  104,  522,  521,
99682  /*   850 */   414,  621,  224,  273,  600,  167,  327,  282,  600,  601,
99683  /*   860 */   103,  468,  521,   56,   57,   47,  582,  581,  583,  583,
99684  /*   870 */    54,   54,   55,   55,   55,   55,  411,   53,   53,   53,
99685  /*   880 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  411,
99686  /*   890 */    27,  414,  411,  375,  276,  167,  359,  544,   50,  238,
99687  /*   900 */   601,   95,  128,  223,  414,  411,  165,  414,  411,  621,
99688  /*   910 */   411,  621,  612,  601,  102,  372,  601,   76,  590,  584,
99689  /*   920 */   414,  570,  236,  414,  470,  414,  167,  621,  188,  601,
99690  /*   930 */    98,  225,  601,  138,  601,  137,  232,   56,   45,   47,
99691  /*   940 */   582,  581,  583,  583,   54,   54,   55,   55,   55,   55,
99692  /*   950 */   411,   53,   53,   53,   53,   52,   52,   51,   51,   51,
99693  /*   960 */    50,  238,  313,  276,  276,  414,  411,  276,  544,  459,
99694  /*   970 */   359,  171,  209,  479,  601,  136,  628,  334,  621,  621,
99695  /*   980 */   125,  414,  621,  368,  411,  621,  257,  540,  589,  588,
99696  /*   990 */   601,   75,  590,  584,  458,  446,   23,   23,  124,  414,
99697  /*  1000 */   326,  325,  621,  427,  324,  309,  600,  288,  601,   92,
99698  /*  1010 */   586,  585,   57,   47,  582,  581,  583,  583,   54,   54,
99699  /*  1020 */    55,   55,   55,   55,  411,   53,   53,   53,   53,   52,
99700  /*  1030 */    52,   51,   51,   51,   50,  238,  313,  587,  411,  414,
99701  /*  1040 */   411,  207,  611,  476,  171,  472,  160,  123,  601,   91,
99702  /*  1050 */   323,  261,   15,  414,  464,  414,  411,  621,  411,  354,
99703  /*  1060 */   222,  411,  601,   74,  601,   90,  590,  584,  159,  264,
99704  /*  1070 */   158,  414,  461,  414,  621,  600,  414,  121,  120,   25,
99705  /*  1080 */   601,   89,  601,  101,  621,  601,   88,   47,  582,  581,
99706  /*  1090 */   583,  583,   54,   54,   55,   55,   55,   55,  544,   53,
99707  /*  1100 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
99708  /*  1110 */    43,  405,  263,    3,  610,  264,  140,  415,  622,   24,
99709  /*  1120 */   410,   11,  456,  594,  118,  155,  219,  452,  408,  621,
99710  /*  1130 */   621,  621,  156,   43,  405,  621,    3,  286,  621,  113,
99711  /*  1140 */   415,  622,  111,  445,  411,  400,  557,  403,  545,   10,
99712  /*  1150 */   411,  408,  264,  110,  205,  436,  541,  566,  453,  414,
99713  /*  1160 */   621,  621,   63,  621,  435,  414,  411,  621,  601,   94,
99714  /*  1170 */   403,  621,  411,  337,  601,   86,  150,   40,   41,  534,
99715  /*  1180 */   566,  414,  242,  264,   42,  413,  412,  414,  600,  595,
99716  /*  1190 */   601,   85,  191,  333,  107,  451,  601,   84,  621,  539,
99717  /*  1200 */    40,   41,  420,  230,  411,  149,  316,   42,  413,  412,
99718  /*  1210 */   398,  127,  595,  315,  621,  399,  278,  625,  181,  414,
99719  /*  1220 */   593,  593,  593,  592,  591,   14,  450,  411,  601,   71,
99720  /*  1230 */   240,  621,   43,  405,  264,    3,  615,  180,  264,  415,
99721  /*  1240 */   622,  614,  414,  593,  593,  593,  592,  591,   14,  621,
99722  /*  1250 */   408,  601,   70,  621,  417,   33,  405,  613,    3,  411,
99723  /*  1260 */   264,  411,  415,  622,  418,  626,  178,  509,    8,  403,
99724  /*  1270 */   241,  416,  126,  408,  414,  621,  414,  449,  208,  566,
99725  /*  1280 */   240,  221,  621,  601,   83,  601,   82,  599,  297,  277,
99726  /*  1290 */   296,   30,  403,   31,  395,  264,  295,  397,  489,   40,
99727  /*  1300 */    41,  411,  566,  220,  621,  294,   42,  413,  412,  271,
99728  /*  1310 */   621,  595,  600,  621,   59,   60,  414,  269,  267,  623,
99729  /*  1320 */   622,   36,   40,   41,  621,  601,   81,  598,  235,   42,
99730  /*  1330 */   413,  412,  621,  621,  595,  265,  344,  411,  248,  556,
99731  /*  1340 */   173,  185,  593,  593,  593,  592,  591,   14,  218,   29,
99732  /*  1350 */   621,  543,  414,  305,  304,  303,  179,  301,  411,  566,
99733  /*  1360 */   454,  601,   80,  289,  335,  593,  593,  593,  592,  591,
99734  /*  1370 */    14,  411,  287,  414,  151,  392,  246,  260,  411,  196,
99735  /*  1380 */   195,  523,  601,   69,  411,  245,  414,  526,  537,  285,
99736  /*  1390 */   389,  595,  621,  414,  536,  601,   17,  362,  153,  414,
99737  /*  1400 */   466,  463,  601,   78,  154,  414,  462,  152,  601,   77,
99738  /*  1410 */   355,  255,  621,  455,  601,    9,  621,  386,  444,  517,
99739  /*  1420 */   247,  621,  593,  593,  593,  621,  621,  244,  621,  243,
99740  /*  1430 */   430,  518,  292,  621,  329,  621,  145,  393,  280,  513,
99741  /*  1440 */   291,  131,  621,  514,  621,  621,  311,  621,  259,  346,
99742  /*  1450 */   249,  621,  621,  229,  314,  621,  228,  512,  227,  240,
99743  /*  1460 */   494,  488,  310,  164,  487,  486,  373,  480,  163,  262,
99744  /*  1470 */   369,  371,  162,   26,  212,  478,  477,  161,  141,  363,
99745  /*  1480 */   467,  122,  339,  187,  119,  348,  347,  117,  116,  115,
99746  /*  1490 */   114,  112,  182,  457,  320,   22,  433,  432,  448,   19,
99747  /*  1500 */   609,  431,  428,   62,  193,  596,  573,  298,  555,  552,
99748  /*  1510 */   571,  404,  290,  380,  498,  510,  495,  306,  281,  499,
99749  /*  1520 */   250,    5,  497,  460,  345,  447,  569,  550,  238,  299,
99750  /*  1530 */   527,  525,  508,  961,  502,  501,  961,  401,  961,  211,
99751  /*  1540 */   490,  356,  256,  961,  483,  961,  961,  961,  961,  961,
99752  /*  1550 */   961,  961,  961,  961,  961,  961,  370,
99753 };
99754 static const YYCODETYPE yy_lookahead[] = {
99755  /*     0 */    19,  142,  143,  144,  145,   24,    1,   26,   77,   78,
99756  /*    10 */    79,   80,   81,   82,   83,   84,   85,   86,   87,   88,
99757  /*    20 */    89,   90,   91,   92,   15,   98,   26,   27,    7,    8,
99758  /*    30 */    49,   50,   77,   78,   79,   80,  109,   82,   83,   84,
99759  /*    40 */    85,   86,   87,   88,   89,   90,   91,   92,   22,   68,
99760  /*    50 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
99761  /*    60 */    79,   80,   23,   82,   83,   84,   85,   86,   87,   88,
99762  /*    70 */    89,   90,   91,   92,   19,   94,  112,   19,  114,  115,
99763  /*    80 */    25,   82,   83,   84,   85,   86,   87,   88,   89,   90,
99764  /*    90 */    91,   92,   19,   22,   94,   95,   96,  150,  150,   99,
99765  /*   100 */   100,  101,   76,  150,   49,   50,  105,  106,  107,   54,
99766  /*   110 */   110,  158,  165,  165,  161,  162,   26,   27,  165,  113,
99767  /*   120 */    16,  174,  175,   68,   69,   70,   71,   72,   73,   74,
99768  /*   130 */    75,   76,   77,   78,   79,   80,  118,   82,   83,   84,
99769  /*   140 */    85,   86,   87,   88,   89,   90,   91,   92,   19,   23,
99770  /*   150 */    92,   97,   98,   24,   96,   97,   98,   99,  100,  101,
99771  /*   160 */   102,   25,   97,  216,   60,   92,   62,  109,  221,   25,
99772  /*   170 */    97,   98,   99,  100,  101,  102,   86,   87,   49,   50,
99773  /*   180 */   118,  116,  109,   25,   94,   95,   32,   97,   88,   89,
99774  /*   190 */    90,   91,   92,  128,  104,   41,  106,   68,   69,   70,
99775  /*   200 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
99776  /*   210 */    11,   82,   83,   84,   85,   86,   87,   88,   89,   90,
99777  /*   220 */    91,   92,   19,   19,   86,   87,   88,   89,   90,   91,
99778  /*   230 */    92,   27,   96,  150,   66,   99,  100,  101,  112,  150,
99779  /*   240 */   114,  115,  138,  150,  161,  162,  110,  103,  165,  222,
99780  /*   250 */   223,  224,   49,   50,  165,   22,   57,   24,  165,  170,
99781  /*   260 */   171,  118,   94,  170,  171,   23,   98,   25,  185,  186,
99782  /*   270 */   243,   68,   69,   70,   71,   72,   73,   74,   75,   76,
99783  /*   280 */    77,   78,   79,   80,  126,   82,   83,   84,   85,   86,
99784  /*   290 */    87,   88,   89,   90,   91,   92,   19,  129,  130,  131,
99785  /*   300 */    88,   23,  172,  173,  105,  106,  107,  150,   22,   26,
99786  /*   310 */    27,  181,   26,   27,   22,  116,   26,   27,   26,  230,
99787  /*   320 */   231,  197,  165,  230,  231,  113,   49,   50,  204,  117,
99788  /*   330 */    96,  174,  175,   99,  100,  101,   22,   26,   27,  136,
99789  /*   340 */    26,   27,  118,   16,  110,   68,   69,   70,   71,   72,
99790  /*   350 */    73,   74,   75,   76,   77,   78,   79,   80,  118,   82,
99791  /*   360 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
99792  /*   370 */    19,  214,  215,  150,   23,   23,  155,   94,   95,   22,
99793  /*   380 */    94,   95,  116,  160,   94,   95,   94,   60,  165,   62,
99794  /*   390 */   112,   26,  114,  115,  128,   23,   36,  174,  175,   88,
99795  /*   400 */    49,   50,   57,  120,   22,   94,   95,   23,   94,   95,
99796  /*   410 */   120,   51,   25,  136,  169,  170,  171,  194,   58,   68,
99797  /*   420 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
99798  /*   430 */    79,   80,   23,   82,   83,   84,   85,   86,   87,   88,
99799  /*   440 */    89,   90,   91,   92,   19,  150,   12,   12,   23,  228,
99800  /*   450 */   105,  106,  107,   23,  233,   25,  165,   19,  150,   94,
99801  /*   460 */   165,  116,   28,   28,  112,  174,  114,  115,  108,  174,
99802  /*   470 */   175,   26,   27,  165,   49,   50,  231,   11,   44,   44,
99803  /*   480 */    46,   46,  174,  175,  112,  160,  114,  115,   50,   22,
99804  /*   490 */    23,   57,   25,   68,   69,   70,   71,   72,   73,   74,
99805  /*   500 */    75,   76,   77,   78,   79,   80,  119,   82,   83,   84,
99806  /*   510 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  194,
99807  /*   520 */   225,   23,   23,  215,   19,   95,  105,  106,  107,  150,
99808  /*   530 */    23,  150,   27,   23,   67,   25,  150,  206,  207,   94,
99809  /*   540 */    95,  166,  104,  218,  165,   22,  165,  109,   49,   50,
99810  /*   550 */   120,  165,   25,  174,  175,  174,  175,   23,   21,  234,
99811  /*   560 */   174,  175,   22,   23,  239,   25,   25,   68,   69,   70,
99812  /*   570 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
99813  /*   580 */   205,   82,   83,   84,   85,   86,   87,   88,   89,   90,
99814  /*   590 */    91,   92,   19,   22,   23,  216,   23,  222,  223,  224,
99815  /*   600 */    63,  220,   35,  150,  150,  163,  220,   67,  166,  167,
99816  /*   610 */   168,  150,  169,  170,  171,  161,  162,   25,  165,  165,
99817  /*   620 */   150,  113,   49,   50,   25,  117,  165,  174,  175,   35,
99818  /*   630 */     7,    8,    9,  160,  160,  165,  120,  100,   67,  247,
99819  /*   640 */   248,   68,   69,   70,   71,   72,   73,   74,   75,   76,
99820  /*   650 */    77,   78,   79,   80,  193,   82,   83,   84,   85,   86,
99821  /*   660 */    87,   88,   89,   90,   91,   92,   19,  194,  194,  150,
99822  /*   670 */   135,   24,  137,   35,  231,  138,  150,  129,  130,  206,
99823  /*   680 */   207,   30,   27,  213,  165,   34,  118,   95,    0,    1,
99824  /*   690 */     2,  165,  218,  174,  175,   50,   49,   50,   22,   48,
99825  /*   700 */   174,  175,   22,   23,   23,  244,  222,  223,  224,  166,
99826  /*   710 */   167,  168,  120,  239,   23,   68,   69,   70,   71,   72,
99827  /*   720 */    73,   74,   75,   76,   77,   78,   79,   80,  150,   82,
99828  /*   730 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
99829  /*   740 */    19,  150,  173,  165,  181,  182,   24,   67,   26,  104,
99830  /*   750 */   181,  188,  174,  175,  150,   39,  165,  150,   52,  150,
99831  /*   760 */   150,  150,  150,  144,  145,  174,  175,  249,  250,  165,
99832  /*   770 */    49,   50,  165,   52,  165,  165,  165,  165,  174,  175,
99833  /*   780 */    29,  174,  175,  174,  175,  174,  175,  160,   22,   68,
99834  /*   790 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
99835  /*   800 */    79,   80,  150,   82,   83,   84,   85,   86,   87,   88,
99836  /*   810 */    89,   90,   91,   92,   19,  150,   94,  165,  150,  150,
99837  /*   820 */   160,  194,  150,  213,  160,   52,  174,  175,   23,   23,
99838  /*   830 */   165,   25,   22,  165,  165,  150,  150,  165,   52,  174,
99839  /*   840 */   175,   22,  174,  175,   49,   50,  174,  175,  190,  191,
99840  /*   850 */   165,  165,  240,   23,  194,   25,  187,  109,  194,  174,
99841  /*   860 */   175,  190,  191,   68,   69,   70,   71,   72,   73,   74,
99842  /*   870 */    75,   76,   77,   78,   79,   80,  150,   82,   83,   84,
99843  /*   880 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  150,
99844  /*   890 */    22,  165,  150,   23,  150,   25,  150,  166,   91,   92,
99845  /*   900 */   174,  175,   22,  217,  165,  150,  102,  165,  150,  165,
99846  /*   910 */   150,  165,  150,  174,  175,   19,  174,  175,   49,   50,
99847  /*   920 */   165,   86,   87,  165,   23,  165,   25,  165,   24,  174,
99848  /*   930 */   175,  187,  174,  175,  174,  175,  205,   68,   69,   70,
99849  /*   940 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
99850  /*   950 */   150,   82,   83,   84,   85,   86,   87,   88,   89,   90,
99851  /*   960 */    91,   92,   19,  150,  150,  165,  150,  150,  166,   23,
99852  /*   970 */   150,   25,  160,   20,  174,  175,    1,    2,  165,  165,
99853  /*   980 */   104,  165,  165,   43,  150,  165,  240,  150,   49,   50,
99854  /*   990 */   174,  175,   49,   50,   23,   23,   25,   25,   53,  165,
99855  /*  1000 */   187,  187,  165,   23,  187,   25,  194,  205,  174,  175,
99856  /*  1010 */    71,   72,   69,   70,   71,   72,   73,   74,   75,   76,
99857  /*  1020 */    77,   78,   79,   80,  150,   82,   83,   84,   85,   86,
99858  /*  1030 */    87,   88,   89,   90,   91,   92,   19,   98,  150,  165,
99859  /*  1040 */   150,  160,  150,   59,   25,   53,  104,   22,  174,  175,
99860  /*  1050 */   213,  138,    5,  165,    1,  165,  150,  165,  150,  150,
99861  /*  1060 */   240,  150,  174,  175,  174,  175,   49,   50,  118,  150,
99862  /*  1070 */    35,  165,   27,  165,  165,  194,  165,  108,  127,   76,
99863  /*  1080 */   174,  175,  174,  175,  165,  174,  175,   70,   71,   72,
99864  /*  1090 */    73,   74,   75,   76,   77,   78,   79,   80,  166,   82,
99865  /*  1100 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
99866  /*  1110 */    19,   20,  193,   22,  150,  150,  150,   26,   27,   76,
99867  /*  1120 */   150,   22,    1,  150,  119,  121,  217,   20,   37,  165,
99868  /*  1130 */   165,  165,   16,   19,   20,  165,   22,  205,  165,  119,
99869  /*  1140 */    26,   27,  108,  128,  150,  150,  150,   56,  150,   22,
99870  /*  1150 */   150,   37,  150,  127,  160,   23,  150,   66,  193,  165,
99871  /*  1160 */   165,  165,   16,  165,   23,  165,  150,  165,  174,  175,
99872  /*  1170 */    56,  165,  150,   65,  174,  175,   15,   86,   87,   88,
99873  /*  1180 */    66,  165,  140,  150,   93,   94,   95,  165,  194,   98,
99874  /*  1190 */   174,  175,   22,    3,  164,  193,  174,  175,  165,  150,
99875  /*  1200 */    86,   87,    4,  180,  150,  248,  251,   93,   94,   95,
99876  /*  1210 */   216,  180,   98,  251,  165,  221,  150,  149,    6,  165,
99877  /*  1220 */   129,  130,  131,  132,  133,  134,  193,  150,  174,  175,
99878  /*  1230 */   116,  165,   19,   20,  150,   22,  149,  151,  150,   26,
99879  /*  1240 */    27,  149,  165,  129,  130,  131,  132,  133,  134,  165,
99880  /*  1250 */    37,  174,  175,  165,  149,   19,   20,   13,   22,  150,
99881  /*  1260 */   150,  150,   26,   27,  146,  147,  151,  150,   25,   56,
99882  /*  1270 */   152,  159,  154,   37,  165,  165,  165,  193,  160,   66,
99883  /*  1280 */   116,  193,  165,  174,  175,  174,  175,  194,  199,  150,
99884  /*  1290 */   200,  126,   56,  124,  123,  150,  201,  122,  150,   86,
99885  /*  1300 */    87,  150,   66,  193,  165,  202,   93,   94,   95,  150,
99886  /*  1310 */   165,   98,  194,  165,  125,   22,  165,  150,  150,   26,
99887  /*  1320 */    27,  135,   86,   87,  165,  174,  175,  203,  226,   93,
99888  /*  1330 */    94,   95,  165,  165,   98,  150,  218,  150,  193,  157,
99889  /*  1340 */   118,  157,  129,  130,  131,  132,  133,  134,    5,  104,
99890  /*  1350 */   165,  211,  165,   10,   11,   12,   13,   14,  150,   66,
99891  /*  1360 */    17,  174,  175,  210,  246,  129,  130,  131,  132,  133,
99892  /*  1370 */   134,  150,  210,  165,   31,  121,   33,  150,  150,   86,
99893  /*  1380 */    87,  176,  174,  175,  150,   42,  165,   94,  211,  210,
99894  /*  1390 */   150,   98,  165,  165,  211,  174,  175,  150,   55,  165,
99895  /*  1400 */    57,  150,  174,  175,   61,  165,  150,   64,  174,  175,
99896  /*  1410 */   150,  150,  165,  150,  174,  175,  165,  104,  150,  184,
99897  /*  1420 */   150,  165,  129,  130,  131,  165,  165,  150,  165,  150,
99898  /*  1430 */   150,  176,  150,  165,   47,  165,  150,  150,  176,  103,
99899  /*  1440 */   150,   22,  165,  178,  165,  165,  179,  165,  105,  106,
99900  /*  1450 */   107,  165,  165,  229,  111,  165,   92,  176,  229,  116,
99901  /*  1460 */   184,  176,  179,  156,  176,  176,   18,  157,  156,  237,
99902  /*  1470 */    45,  157,  156,  135,  157,  157,  238,  156,   68,  157,
99903  /*  1480 */   189,  189,  139,  219,   22,  157,   18,  192,  192,  192,
99904  /*  1490 */   192,  189,  219,  199,  157,  242,   40,  157,  199,  242,
99905  /*  1500 */   153,  157,   38,  245,  196,  166,  232,  198,  177,  177,
99906  /*  1510 */   232,  227,  209,  178,  166,  182,  166,  148,  177,  177,
99907  /*  1520 */   209,  196,  177,  199,  209,  199,  166,  208,   92,  195,
99908  /*  1530 */   174,  174,  183,  252,  183,  183,  252,  191,  252,  235,
99909  /*  1540 */   186,  241,  241,  252,  186,  252,  252,  252,  252,  252,
99910  /*  1550 */   252,  252,  252,  252,  252,  252,  236,
99911 };
99912 #define YY_SHIFT_USE_DFLT (-74)
99913 #define YY_SHIFT_COUNT (418)
99914 #define YY_SHIFT_MIN   (-73)
99915 #define YY_SHIFT_MAX   (1468)
99916 static const short yy_shift_ofst[] = {
99917  /*     0 */   975, 1114, 1343, 1114, 1213, 1213,   90,   90,    0,  -19,
99918  /*    10 */  1213, 1213, 1213, 1213, 1213,  345,  445,  721, 1091, 1213,
99919  /*    20 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
99920  /*    30 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
99921  /*    40 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1236, 1213, 1213,
99922  /*    50 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
99923  /*    60 */  1213,  199,  445,  445,  835,  835,  365, 1164,   55,  647,
99924  /*    70 */   573,  499,  425,  351,  277,  203,  129,  795,  795,  795,
99925  /*    80 */   795,  795,  795,  795,  795,  795,  795,  795,  795,  795,
99926  /*    90 */   795,  795,  795,  795,  795,  869,  795,  943, 1017, 1017,
99927  /*   100 */   -69,  -45,  -45,  -45,  -45,  -45,   -1,   58,  138,  100,
99928  /*   110 */   445,  445,  445,  445,  445,  445,  445,  445,  445,  445,
99929  /*   120 */   445,  445,  445,  445,  445,  445,  537,  438,  445,  445,
99930  /*   130 */   445,  445,  445,  365,  807, 1436,  -74,  -74,  -74, 1293,
99931  /*   140 */    73,  434,  434,  311,  314,  290,  283,  286,  540,  467,
99932  /*   150 */   445,  445,  445,  445,  445,  445,  445,  445,  445,  445,
99933  /*   160 */   445,  445,  445,  445,  445,  445,  445,  445,  445,  445,
99934  /*   170 */   445,  445,  445,  445,  445,  445,  445,  445,  445,  445,
99935  /*   180 */   445,  445,   65,  722,  722,  722,  688,  266, 1164, 1164,
99936  /*   190 */  1164,  -74,  -74,  -74,  136,  168,  168,  234,  360,  360,
99937  /*   200 */   360,  430,  372,  435,  352,  278,  126,  -36,  -36,  -36,
99938  /*   210 */   -36,  421,  651,  -36,  -36,  592,  292,  212,  623,  158,
99939  /*   220 */   204,  204,  505,  158,  505,  144,  365,  154,  365,  154,
99940  /*   230 */   645,  154,  204,  154,  154,  535,  548,  548,  365,  387,
99941  /*   240 */   508,  233, 1464, 1222, 1222, 1456, 1456, 1222, 1462, 1410,
99942  /*   250 */  1165, 1468, 1468, 1468, 1468, 1222, 1165, 1462, 1410, 1410,
99943  /*   260 */  1222, 1448, 1338, 1425, 1222, 1222, 1448, 1222, 1448, 1222,
99944  /*   270 */  1448, 1419, 1313, 1313, 1313, 1387, 1364, 1364, 1419, 1313,
99945  /*   280 */  1336, 1313, 1387, 1313, 1313, 1254, 1245, 1254, 1245, 1254,
99946  /*   290 */  1245, 1222, 1222, 1186, 1189, 1175, 1169, 1171, 1165, 1164,
99947  /*   300 */  1243, 1244, 1244, 1212, 1212, 1212, 1212,  -74,  -74,  -74,
99948  /*   310 */   -74,  -74,  -74,  939,  104,  680,  571,  327,    1,  980,
99949  /*   320 */    26,  972,  971,  946,  901,  870,  830,  806,   54,   21,
99950  /*   330 */   -73,  510,  242, 1198, 1190, 1170, 1042, 1161, 1108, 1146,
99951  /*   340 */  1141, 1132, 1015, 1127, 1026, 1034, 1020, 1107, 1004, 1116,
99952  /*   350 */  1121, 1005, 1099,  951, 1043, 1003,  969, 1045, 1035,  950,
99953  /*   360 */  1053, 1047, 1025,  942,  913,  992, 1019,  945,  984,  940,
99954  /*   370 */   876,  904,  953,  896,  748,  804,  880,  786,  868,  819,
99955  /*   380 */   805,  810,  773,  751,  766,  706,  716,  691,  681,  568,
99956  /*   390 */   655,  638,  676,  516,  541,  594,  599,  567,  541,  534,
99957  /*   400 */   507,  527,  498,  523,  466,  382,  409,  384,  357,    6,
99958  /*   410 */   240,  224,  143,   62,   18,   71,   39,    9,    5,
99959 };
99960 #define YY_REDUCE_USE_DFLT (-142)
99961 #define YY_REDUCE_COUNT (312)
99962 #define YY_REDUCE_MIN   (-141)
99963 #define YY_REDUCE_MAX   (1369)
99964 static const short yy_reduce_ofst[] = {
99965  /*     0 */  -141,  994, 1118,  223,  157,  -53,   93,   89,   83,  375,
99966  /*    10 */   386,  381,  379,  308,  295,  325,  -47,   27, 1240, 1234,
99967  /*    20 */  1228, 1221, 1208, 1187, 1151, 1111, 1109, 1077, 1054, 1022,
99968  /*    30 */  1016, 1000,  911,  908,  906,  890,  888,  874,  834,  816,
99969  /*    40 */   800,  760,  758,  755,  742,  739,  726,  685,  672,  668,
99970  /*    50 */   665,  652,  611,  609,  607,  604,  591,  578,  526,  519,
99971  /*    60 */   453,  474,  454,  461,  443,  245,  442,  473,  484,  484,
99972  /*    70 */   484,  484,  484,  484,  484,  484,  484,  484,  484,  484,
99973  /*    80 */   484,  484,  484,  484,  484,  484,  484,  484,  484,  484,
99974  /*    90 */   484,  484,  484,  484,  484,  484,  484,  484,  484,  484,
99975  /*   100 */   484,  484,  484,  484,  484,  484,  484,  130,  484,  484,
99976  /*   110 */  1145,  909, 1110, 1088, 1084, 1033, 1002,  965,  820,  837,
99977  /*   120 */   746,  686,  612,  817,  610,  919,  221,  563,  814,  813,
99978  /*   130 */   744,  669,  470,  543,  484,  484,  484,  484,  484,  291,
99979  /*   140 */   569,  671,  658,  970, 1290, 1287, 1286, 1282,  518,  518,
99980  /*   150 */  1280, 1279, 1277, 1270, 1268, 1263, 1261, 1260, 1256, 1251,
99981  /*   160 */  1247, 1227, 1185, 1168, 1167, 1159, 1148, 1139, 1117, 1066,
99982  /*   170 */  1049, 1006,  998,  996,  995,  973,  970,  966,  964,  892,
99983  /*   180 */   762,  -52,  881,  932,  802,  731,  619,  812,  664,  660,
99984  /*   190 */   627,  392,  331,  124, 1358, 1357, 1356, 1354, 1352, 1351,
99985  /*   200 */  1349, 1319, 1334, 1346, 1334, 1334, 1334, 1334, 1334, 1334,
99986  /*   210 */  1334, 1320, 1304, 1334, 1334, 1319, 1360, 1325, 1369, 1326,
99987  /*   220 */  1315, 1311, 1301, 1324, 1300, 1335, 1350, 1345, 1348, 1342,
99988  /*   230 */  1333, 1341, 1303, 1332, 1331, 1284, 1278, 1274, 1339, 1309,
99989  /*   240 */  1308, 1347, 1258, 1344, 1340, 1257, 1253, 1337, 1273, 1302,
99990  /*   250 */  1299, 1298, 1297, 1296, 1295, 1328, 1294, 1264, 1292, 1291,
99991  /*   260 */  1322, 1321, 1238, 1232, 1318, 1317, 1316, 1314, 1312, 1310,
99992  /*   270 */  1307, 1283, 1289, 1288, 1285, 1276, 1229, 1224, 1267, 1281,
99993  /*   280 */  1265, 1262, 1235, 1255, 1205, 1183, 1179, 1177, 1162, 1140,
99994  /*   290 */  1153, 1184, 1182, 1102, 1124, 1103, 1095, 1090, 1089, 1093,
99995  /*   300 */  1112, 1115, 1086, 1105, 1092, 1087, 1068,  962,  955,  957,
99996  /*   310 */  1031, 1023, 1030,
99997 };
99998 static const YYACTIONTYPE yy_default[] = {
99999  /*     0 */   635,  870,  959,  959,  959,  870,  899,  899,  959,  759,
100000  /*    10 */   959,  959,  959,  959,  868,  959,  959,  933,  959,  959,
100001  /*    20 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
100002  /*    30 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
100003  /*    40 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
100004  /*    50 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
100005  /*    60 */   959,  959,  959,  959,  899,  899,  674,  763,  794,  959,
100006  /*    70 */   959,  959,  959,  959,  959,  959,  959,  932,  934,  809,
100007  /*    80 */   808,  802,  801,  912,  774,  799,  792,  785,  796,  871,
100008  /*    90 */   864,  865,  863,  867,  872,  959,  795,  831,  848,  830,
100009  /*   100 */   842,  847,  854,  846,  843,  833,  832,  666,  834,  835,
100010  /*   110 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
100011  /*   120 */   959,  959,  959,  959,  959,  959,  661,  728,  959,  959,
100012  /*   130 */   959,  959,  959,  959,  836,  837,  851,  850,  849,  959,
100013  /*   140 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
100014  /*   150 */   959,  939,  937,  959,  883,  959,  959,  959,  959,  959,
100015  /*   160 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
100016  /*   170 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
100017  /*   180 */   959,  641,  959,  759,  759,  759,  635,  959,  959,  959,
100018  /*   190 */   959,  951,  763,  753,  719,  959,  959,  959,  959,  959,
100019  /*   200 */   959,  959,  959,  959,  959,  959,  959,  804,  742,  922,
100020  /*   210 */   924,  959,  905,  740,  663,  761,  676,  751,  643,  798,
100021  /*   220 */   776,  776,  917,  798,  917,  700,  959,  788,  959,  788,
100022  /*   230 */   697,  788,  776,  788,  788,  866,  959,  959,  959,  760,
100023  /*   240 */   751,  959,  944,  767,  767,  936,  936,  767,  810,  732,
100024  /*   250 */   798,  739,  739,  739,  739,  767,  798,  810,  732,  732,
100025  /*   260 */   767,  658,  911,  909,  767,  767,  658,  767,  658,  767,
100026  /*   270 */   658,  876,  730,  730,  730,  715,  880,  880,  876,  730,
100027  /*   280 */   700,  730,  715,  730,  730,  780,  775,  780,  775,  780,
100028  /*   290 */   775,  767,  767,  959,  793,  781,  791,  789,  798,  959,
100029  /*   300 */   718,  651,  651,  640,  640,  640,  640,  956,  956,  951,
100030  /*   310 */   702,  702,  684,  959,  959,  959,  959,  959,  959,  959,
100031  /*   320 */   885,  959,  959,  959,  959,  959,  959,  959,  959,  959,
100032  /*   330 */   959,  959,  959,  959,  636,  946,  959,  959,  943,  959,
100033  /*   340 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
100034  /*   350 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  915,
100035  /*   360 */   959,  959,  959,  959,  959,  959,  908,  907,  959,  959,
100036  /*   370 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
100037  /*   380 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
100038  /*   390 */   959,  959,  959,  959,  790,  959,  782,  959,  869,  959,
100039  /*   400 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  745,
100040  /*   410 */   819,  959,  818,  822,  817,  668,  959,  649,  959,  632,
100041  /*   420 */   637,  955,  958,  957,  954,  953,  952,  947,  945,  942,
100042  /*   430 */   941,  940,  938,  935,  931,  889,  887,  894,  893,  892,
100043  /*   440 */   891,  890,  888,  886,  884,  805,  803,  800,  797,  930,
100044  /*   450 */   882,  741,  738,  737,  657,  948,  914,  923,  921,  811,
100045  /*   460 */   920,  919,  918,  916,  913,  900,  807,  806,  733,  874,
100046  /*   470 */   873,  660,  904,  903,  902,  906,  910,  901,  769,  659,
100047  /*   480 */   656,  665,  722,  721,  729,  727,  726,  725,  724,  723,
100048  /*   490 */   720,  667,  675,  686,  714,  699,  698,  879,  881,  878,
100049  /*   500 */   877,  707,  706,  712,  711,  710,  709,  708,  705,  704,
100050  /*   510 */   703,  696,  695,  701,  694,  717,  716,  713,  693,  736,
100051  /*   520 */   735,  734,  731,  692,  691,  690,  822,  689,  688,  828,
100052  /*   530 */   827,  815,  858,  756,  755,  754,  766,  765,  778,  777,
100053  /*   540 */   813,  812,  779,  764,  758,  757,  773,  772,  771,  770,
100054  /*   550 */   762,  752,  784,  787,  786,  783,  860,  768,  857,  929,
100055  /*   560 */   928,  927,  926,  925,  862,  861,  829,  826,  679,  680,
100056  /*   570 */   898,  896,  897,  895,  682,  681,  678,  677,  859,  747,
100057  /*   580 */   746,  855,  852,  844,  840,  856,  853,  845,  841,  839,
100058  /*   590 */   838,  824,  823,  821,  820,  816,  825,  670,  748,  744,
100059  /*   600 */   743,  814,  750,  749,  687,  685,  683,  664,  662,  655,
100060  /*   610 */   653,  652,  654,  650,  648,  647,  646,  645,  644,  673,
100061  /*   620 */   672,  671,  669,  668,  642,  639,  638,  634,  633,  631,
100062 };
100063
100064 /* The next table maps tokens into fallback tokens.  If a construct
100065 ** like the following:
100066 ** 
100067 **      %fallback ID X Y Z.
100068 **
100069 ** appears in the grammar, then ID becomes a fallback token for X, Y,
100070 ** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
100071 ** but it does not parse, the type of the token is changed to ID and
100072 ** the parse is retried before an error is thrown.
100073 */
100074 #ifdef YYFALLBACK
100075 static const YYCODETYPE yyFallback[] = {
100076     0,  /*          $ => nothing */
100077     0,  /*       SEMI => nothing */
100078    26,  /*    EXPLAIN => ID */
100079    26,  /*      QUERY => ID */
100080    26,  /*       PLAN => ID */
100081    26,  /*      BEGIN => ID */
100082     0,  /* TRANSACTION => nothing */
100083    26,  /*   DEFERRED => ID */
100084    26,  /*  IMMEDIATE => ID */
100085    26,  /*  EXCLUSIVE => ID */
100086     0,  /*     COMMIT => nothing */
100087    26,  /*        END => ID */
100088    26,  /*   ROLLBACK => ID */
100089    26,  /*  SAVEPOINT => ID */
100090    26,  /*    RELEASE => ID */
100091     0,  /*         TO => nothing */
100092     0,  /*      TABLE => nothing */
100093     0,  /*     CREATE => nothing */
100094    26,  /*         IF => ID */
100095     0,  /*        NOT => nothing */
100096     0,  /*     EXISTS => nothing */
100097    26,  /*       TEMP => ID */
100098     0,  /*         LP => nothing */
100099     0,  /*         RP => nothing */
100100     0,  /*         AS => nothing */
100101     0,  /*      COMMA => nothing */
100102     0,  /*         ID => nothing */
100103     0,  /*    INDEXED => nothing */
100104    26,  /*      ABORT => ID */
100105    26,  /*     ACTION => ID */
100106    26,  /*      AFTER => ID */
100107    26,  /*    ANALYZE => ID */
100108    26,  /*        ASC => ID */
100109    26,  /*     ATTACH => ID */
100110    26,  /*     BEFORE => ID */
100111    26,  /*         BY => ID */
100112    26,  /*    CASCADE => ID */
100113    26,  /*       CAST => ID */
100114    26,  /*   COLUMNKW => ID */
100115    26,  /*   CONFLICT => ID */
100116    26,  /*   DATABASE => ID */
100117    26,  /*       DESC => ID */
100118    26,  /*     DETACH => ID */
100119    26,  /*       EACH => ID */
100120    26,  /*       FAIL => ID */
100121    26,  /*        FOR => ID */
100122    26,  /*     IGNORE => ID */
100123    26,  /*  INITIALLY => ID */
100124    26,  /*    INSTEAD => ID */
100125    26,  /*    LIKE_KW => ID */
100126    26,  /*      MATCH => ID */
100127    26,  /*         NO => ID */
100128    26,  /*        KEY => ID */
100129    26,  /*         OF => ID */
100130    26,  /*     OFFSET => ID */
100131    26,  /*     PRAGMA => ID */
100132    26,  /*      RAISE => ID */
100133    26,  /*    REPLACE => ID */
100134    26,  /*   RESTRICT => ID */
100135    26,  /*        ROW => ID */
100136    26,  /*    TRIGGER => ID */
100137    26,  /*     VACUUM => ID */
100138    26,  /*       VIEW => ID */
100139    26,  /*    VIRTUAL => ID */
100140    26,  /*    REINDEX => ID */
100141    26,  /*     RENAME => ID */
100142    26,  /*   CTIME_KW => ID */
100143 };
100144 #endif /* YYFALLBACK */
100145
100146 /* The following structure represents a single element of the
100147 ** parser's stack.  Information stored includes:
100148 **
100149 **   +  The state number for the parser at this level of the stack.
100150 **
100151 **   +  The value of the token stored at this level of the stack.
100152 **      (In other words, the "major" token.)
100153 **
100154 **   +  The semantic value stored at this level of the stack.  This is
100155 **      the information used by the action routines in the grammar.
100156 **      It is sometimes called the "minor" token.
100157 */
100158 struct yyStackEntry {
100159   YYACTIONTYPE stateno;  /* The state-number */
100160   YYCODETYPE major;      /* The major token value.  This is the code
100161                          ** number for the token at this stack level */
100162   YYMINORTYPE minor;     /* The user-supplied minor token value.  This
100163                          ** is the value of the token  */
100164 };
100165 typedef struct yyStackEntry yyStackEntry;
100166
100167 /* The state of the parser is completely contained in an instance of
100168 ** the following structure */
100169 struct yyParser {
100170   int yyidx;                    /* Index of top element in stack */
100171 #ifdef YYTRACKMAXSTACKDEPTH
100172   int yyidxMax;                 /* Maximum value of yyidx */
100173 #endif
100174   int yyerrcnt;                 /* Shifts left before out of the error */
100175   sqlite3ParserARG_SDECL                /* A place to hold %extra_argument */
100176 #if YYSTACKDEPTH<=0
100177   int yystksz;                  /* Current side of the stack */
100178   yyStackEntry *yystack;        /* The parser's stack */
100179 #else
100180   yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */
100181 #endif
100182 };
100183 typedef struct yyParser yyParser;
100184
100185 #ifndef NDEBUG
100186 static FILE *yyTraceFILE = 0;
100187 static char *yyTracePrompt = 0;
100188 #endif /* NDEBUG */
100189
100190 #ifndef NDEBUG
100191 /* 
100192 ** Turn parser tracing on by giving a stream to which to write the trace
100193 ** and a prompt to preface each trace message.  Tracing is turned off
100194 ** by making either argument NULL 
100195 **
100196 ** Inputs:
100197 ** <ul>
100198 ** <li> A FILE* to which trace output should be written.
100199 **      If NULL, then tracing is turned off.
100200 ** <li> A prefix string written at the beginning of every
100201 **      line of trace output.  If NULL, then tracing is
100202 **      turned off.
100203 ** </ul>
100204 **
100205 ** Outputs:
100206 ** None.
100207 */
100208 SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
100209   yyTraceFILE = TraceFILE;
100210   yyTracePrompt = zTracePrompt;
100211   if( yyTraceFILE==0 ) yyTracePrompt = 0;
100212   else if( yyTracePrompt==0 ) yyTraceFILE = 0;
100213 }
100214 #endif /* NDEBUG */
100215
100216 #ifndef NDEBUG
100217 /* For tracing shifts, the names of all terminals and nonterminals
100218 ** are required.  The following table supplies these names */
100219 static const char *const yyTokenName[] = { 
100220   "$",             "SEMI",          "EXPLAIN",       "QUERY",       
100221   "PLAN",          "BEGIN",         "TRANSACTION",   "DEFERRED",    
100222   "IMMEDIATE",     "EXCLUSIVE",     "COMMIT",        "END",         
100223   "ROLLBACK",      "SAVEPOINT",     "RELEASE",       "TO",          
100224   "TABLE",         "CREATE",        "IF",            "NOT",         
100225   "EXISTS",        "TEMP",          "LP",            "RP",          
100226   "AS",            "COMMA",         "ID",            "INDEXED",     
100227   "ABORT",         "ACTION",        "AFTER",         "ANALYZE",     
100228   "ASC",           "ATTACH",        "BEFORE",        "BY",          
100229   "CASCADE",       "CAST",          "COLUMNKW",      "CONFLICT",    
100230   "DATABASE",      "DESC",          "DETACH",        "EACH",        
100231   "FAIL",          "FOR",           "IGNORE",        "INITIALLY",   
100232   "INSTEAD",       "LIKE_KW",       "MATCH",         "NO",          
100233   "KEY",           "OF",            "OFFSET",        "PRAGMA",      
100234   "RAISE",         "REPLACE",       "RESTRICT",      "ROW",         
100235   "TRIGGER",       "VACUUM",        "VIEW",          "VIRTUAL",     
100236   "REINDEX",       "RENAME",        "CTIME_KW",      "ANY",         
100237   "OR",            "AND",           "IS",            "BETWEEN",     
100238   "IN",            "ISNULL",        "NOTNULL",       "NE",          
100239   "EQ",            "GT",            "LE",            "LT",          
100240   "GE",            "ESCAPE",        "BITAND",        "BITOR",       
100241   "LSHIFT",        "RSHIFT",        "PLUS",          "MINUS",       
100242   "STAR",          "SLASH",         "REM",           "CONCAT",      
100243   "COLLATE",       "BITNOT",        "STRING",        "JOIN_KW",     
100244   "CONSTRAINT",    "DEFAULT",       "NULL",          "PRIMARY",     
100245   "UNIQUE",        "CHECK",         "REFERENCES",    "AUTOINCR",    
100246   "ON",            "INSERT",        "DELETE",        "UPDATE",      
100247   "SET",           "DEFERRABLE",    "FOREIGN",       "DROP",        
100248   "UNION",         "ALL",           "EXCEPT",        "INTERSECT",   
100249   "SELECT",        "DISTINCT",      "DOT",           "FROM",        
100250   "JOIN",          "USING",         "ORDER",         "GROUP",       
100251   "HAVING",        "LIMIT",         "WHERE",         "INTO",        
100252   "VALUES",        "INTEGER",       "FLOAT",         "BLOB",        
100253   "REGISTER",      "VARIABLE",      "CASE",          "WHEN",        
100254   "THEN",          "ELSE",          "INDEX",         "ALTER",       
100255   "ADD",           "error",         "input",         "cmdlist",     
100256   "ecmd",          "explain",       "cmdx",          "cmd",         
100257   "transtype",     "trans_opt",     "nm",            "savepoint_opt",
100258   "create_table",  "create_table_args",  "createkw",      "temp",        
100259   "ifnotexists",   "dbnm",          "columnlist",    "conslist_opt",
100260   "select",        "column",        "columnid",      "type",        
100261   "carglist",      "id",            "ids",           "typetoken",   
100262   "typename",      "signed",        "plus_num",      "minus_num",   
100263   "carg",          "ccons",         "term",          "expr",        
100264   "onconf",        "sortorder",     "autoinc",       "idxlist_opt", 
100265   "refargs",       "defer_subclause",  "refarg",        "refact",      
100266   "init_deferred_pred_opt",  "conslist",      "tcons",         "idxlist",     
100267   "defer_subclause_opt",  "orconf",        "resolvetype",   "raisetype",   
100268   "ifexists",      "fullname",      "oneselect",     "multiselect_op",
100269   "distinct",      "selcollist",    "from",          "where_opt",   
100270   "groupby_opt",   "having_opt",    "orderby_opt",   "limit_opt",   
100271   "sclp",          "as",            "seltablist",    "stl_prefix",  
100272   "joinop",        "indexed_opt",   "on_opt",        "using_opt",   
100273   "joinop2",       "inscollist",    "sortlist",      "sortitem",    
100274   "nexprlist",     "setlist",       "insert_cmd",    "inscollist_opt",
100275   "itemlist",      "exprlist",      "likeop",        "between_op",  
100276   "in_op",         "case_operand",  "case_exprlist",  "case_else",   
100277   "uniqueflag",    "collate",       "nmnum",         "plus_opt",    
100278   "number",        "trigger_decl",  "trigger_cmd_list",  "trigger_time",
100279   "trigger_event",  "foreach_clause",  "when_clause",   "trigger_cmd", 
100280   "trnm",          "tridxby",       "database_kw_opt",  "key_opt",     
100281   "add_column_fullname",  "kwcolumn_opt",  "create_vtab",   "vtabarglist", 
100282   "vtabarg",       "vtabargtoken",  "lp",            "anylist",     
100283 };
100284 #endif /* NDEBUG */
100285
100286 #ifndef NDEBUG
100287 /* For tracing reduce actions, the names of all rules are required.
100288 */
100289 static const char *const yyRuleName[] = {
100290  /*   0 */ "input ::= cmdlist",
100291  /*   1 */ "cmdlist ::= cmdlist ecmd",
100292  /*   2 */ "cmdlist ::= ecmd",
100293  /*   3 */ "ecmd ::= SEMI",
100294  /*   4 */ "ecmd ::= explain cmdx SEMI",
100295  /*   5 */ "explain ::=",
100296  /*   6 */ "explain ::= EXPLAIN",
100297  /*   7 */ "explain ::= EXPLAIN QUERY PLAN",
100298  /*   8 */ "cmdx ::= cmd",
100299  /*   9 */ "cmd ::= BEGIN transtype trans_opt",
100300  /*  10 */ "trans_opt ::=",
100301  /*  11 */ "trans_opt ::= TRANSACTION",
100302  /*  12 */ "trans_opt ::= TRANSACTION nm",
100303  /*  13 */ "transtype ::=",
100304  /*  14 */ "transtype ::= DEFERRED",
100305  /*  15 */ "transtype ::= IMMEDIATE",
100306  /*  16 */ "transtype ::= EXCLUSIVE",
100307  /*  17 */ "cmd ::= COMMIT trans_opt",
100308  /*  18 */ "cmd ::= END trans_opt",
100309  /*  19 */ "cmd ::= ROLLBACK trans_opt",
100310  /*  20 */ "savepoint_opt ::= SAVEPOINT",
100311  /*  21 */ "savepoint_opt ::=",
100312  /*  22 */ "cmd ::= SAVEPOINT nm",
100313  /*  23 */ "cmd ::= RELEASE savepoint_opt nm",
100314  /*  24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
100315  /*  25 */ "cmd ::= create_table create_table_args",
100316  /*  26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
100317  /*  27 */ "createkw ::= CREATE",
100318  /*  28 */ "ifnotexists ::=",
100319  /*  29 */ "ifnotexists ::= IF NOT EXISTS",
100320  /*  30 */ "temp ::= TEMP",
100321  /*  31 */ "temp ::=",
100322  /*  32 */ "create_table_args ::= LP columnlist conslist_opt RP",
100323  /*  33 */ "create_table_args ::= AS select",
100324  /*  34 */ "columnlist ::= columnlist COMMA column",
100325  /*  35 */ "columnlist ::= column",
100326  /*  36 */ "column ::= columnid type carglist",
100327  /*  37 */ "columnid ::= nm",
100328  /*  38 */ "id ::= ID",
100329  /*  39 */ "id ::= INDEXED",
100330  /*  40 */ "ids ::= ID|STRING",
100331  /*  41 */ "nm ::= id",
100332  /*  42 */ "nm ::= STRING",
100333  /*  43 */ "nm ::= JOIN_KW",
100334  /*  44 */ "type ::=",
100335  /*  45 */ "type ::= typetoken",
100336  /*  46 */ "typetoken ::= typename",
100337  /*  47 */ "typetoken ::= typename LP signed RP",
100338  /*  48 */ "typetoken ::= typename LP signed COMMA signed RP",
100339  /*  49 */ "typename ::= ids",
100340  /*  50 */ "typename ::= typename ids",
100341  /*  51 */ "signed ::= plus_num",
100342  /*  52 */ "signed ::= minus_num",
100343  /*  53 */ "carglist ::= carglist carg",
100344  /*  54 */ "carglist ::=",
100345  /*  55 */ "carg ::= CONSTRAINT nm ccons",
100346  /*  56 */ "carg ::= ccons",
100347  /*  57 */ "ccons ::= DEFAULT term",
100348  /*  58 */ "ccons ::= DEFAULT LP expr RP",
100349  /*  59 */ "ccons ::= DEFAULT PLUS term",
100350  /*  60 */ "ccons ::= DEFAULT MINUS term",
100351  /*  61 */ "ccons ::= DEFAULT id",
100352  /*  62 */ "ccons ::= NULL onconf",
100353  /*  63 */ "ccons ::= NOT NULL onconf",
100354  /*  64 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
100355  /*  65 */ "ccons ::= UNIQUE onconf",
100356  /*  66 */ "ccons ::= CHECK LP expr RP",
100357  /*  67 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
100358  /*  68 */ "ccons ::= defer_subclause",
100359  /*  69 */ "ccons ::= COLLATE ids",
100360  /*  70 */ "autoinc ::=",
100361  /*  71 */ "autoinc ::= AUTOINCR",
100362  /*  72 */ "refargs ::=",
100363  /*  73 */ "refargs ::= refargs refarg",
100364  /*  74 */ "refarg ::= MATCH nm",
100365  /*  75 */ "refarg ::= ON INSERT refact",
100366  /*  76 */ "refarg ::= ON DELETE refact",
100367  /*  77 */ "refarg ::= ON UPDATE refact",
100368  /*  78 */ "refact ::= SET NULL",
100369  /*  79 */ "refact ::= SET DEFAULT",
100370  /*  80 */ "refact ::= CASCADE",
100371  /*  81 */ "refact ::= RESTRICT",
100372  /*  82 */ "refact ::= NO ACTION",
100373  /*  83 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
100374  /*  84 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
100375  /*  85 */ "init_deferred_pred_opt ::=",
100376  /*  86 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
100377  /*  87 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
100378  /*  88 */ "conslist_opt ::=",
100379  /*  89 */ "conslist_opt ::= COMMA conslist",
100380  /*  90 */ "conslist ::= conslist COMMA tcons",
100381  /*  91 */ "conslist ::= conslist tcons",
100382  /*  92 */ "conslist ::= tcons",
100383  /*  93 */ "tcons ::= CONSTRAINT nm",
100384  /*  94 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
100385  /*  95 */ "tcons ::= UNIQUE LP idxlist RP onconf",
100386  /*  96 */ "tcons ::= CHECK LP expr RP onconf",
100387  /*  97 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
100388  /*  98 */ "defer_subclause_opt ::=",
100389  /*  99 */ "defer_subclause_opt ::= defer_subclause",
100390  /* 100 */ "onconf ::=",
100391  /* 101 */ "onconf ::= ON CONFLICT resolvetype",
100392  /* 102 */ "orconf ::=",
100393  /* 103 */ "orconf ::= OR resolvetype",
100394  /* 104 */ "resolvetype ::= raisetype",
100395  /* 105 */ "resolvetype ::= IGNORE",
100396  /* 106 */ "resolvetype ::= REPLACE",
100397  /* 107 */ "cmd ::= DROP TABLE ifexists fullname",
100398  /* 108 */ "ifexists ::= IF EXISTS",
100399  /* 109 */ "ifexists ::=",
100400  /* 110 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select",
100401  /* 111 */ "cmd ::= DROP VIEW ifexists fullname",
100402  /* 112 */ "cmd ::= select",
100403  /* 113 */ "select ::= oneselect",
100404  /* 114 */ "select ::= select multiselect_op oneselect",
100405  /* 115 */ "multiselect_op ::= UNION",
100406  /* 116 */ "multiselect_op ::= UNION ALL",
100407  /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
100408  /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
100409  /* 119 */ "distinct ::= DISTINCT",
100410  /* 120 */ "distinct ::= ALL",
100411  /* 121 */ "distinct ::=",
100412  /* 122 */ "sclp ::= selcollist COMMA",
100413  /* 123 */ "sclp ::=",
100414  /* 124 */ "selcollist ::= sclp expr as",
100415  /* 125 */ "selcollist ::= sclp STAR",
100416  /* 126 */ "selcollist ::= sclp nm DOT STAR",
100417  /* 127 */ "as ::= AS nm",
100418  /* 128 */ "as ::= ids",
100419  /* 129 */ "as ::=",
100420  /* 130 */ "from ::=",
100421  /* 131 */ "from ::= FROM seltablist",
100422  /* 132 */ "stl_prefix ::= seltablist joinop",
100423  /* 133 */ "stl_prefix ::=",
100424  /* 134 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
100425  /* 135 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
100426  /* 136 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
100427  /* 137 */ "dbnm ::=",
100428  /* 138 */ "dbnm ::= DOT nm",
100429  /* 139 */ "fullname ::= nm dbnm",
100430  /* 140 */ "joinop ::= COMMA|JOIN",
100431  /* 141 */ "joinop ::= JOIN_KW JOIN",
100432  /* 142 */ "joinop ::= JOIN_KW nm JOIN",
100433  /* 143 */ "joinop ::= JOIN_KW nm nm JOIN",
100434  /* 144 */ "on_opt ::= ON expr",
100435  /* 145 */ "on_opt ::=",
100436  /* 146 */ "indexed_opt ::=",
100437  /* 147 */ "indexed_opt ::= INDEXED BY nm",
100438  /* 148 */ "indexed_opt ::= NOT INDEXED",
100439  /* 149 */ "using_opt ::= USING LP inscollist RP",
100440  /* 150 */ "using_opt ::=",
100441  /* 151 */ "orderby_opt ::=",
100442  /* 152 */ "orderby_opt ::= ORDER BY sortlist",
100443  /* 153 */ "sortlist ::= sortlist COMMA sortitem sortorder",
100444  /* 154 */ "sortlist ::= sortitem sortorder",
100445  /* 155 */ "sortitem ::= expr",
100446  /* 156 */ "sortorder ::= ASC",
100447  /* 157 */ "sortorder ::= DESC",
100448  /* 158 */ "sortorder ::=",
100449  /* 159 */ "groupby_opt ::=",
100450  /* 160 */ "groupby_opt ::= GROUP BY nexprlist",
100451  /* 161 */ "having_opt ::=",
100452  /* 162 */ "having_opt ::= HAVING expr",
100453  /* 163 */ "limit_opt ::=",
100454  /* 164 */ "limit_opt ::= LIMIT expr",
100455  /* 165 */ "limit_opt ::= LIMIT expr OFFSET expr",
100456  /* 166 */ "limit_opt ::= LIMIT expr COMMA expr",
100457  /* 167 */ "cmd ::= DELETE FROM fullname indexed_opt where_opt",
100458  /* 168 */ "where_opt ::=",
100459  /* 169 */ "where_opt ::= WHERE expr",
100460  /* 170 */ "cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt",
100461  /* 171 */ "setlist ::= setlist COMMA nm EQ expr",
100462  /* 172 */ "setlist ::= nm EQ expr",
100463  /* 173 */ "cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP",
100464  /* 174 */ "cmd ::= insert_cmd INTO fullname inscollist_opt select",
100465  /* 175 */ "cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
100466  /* 176 */ "insert_cmd ::= INSERT orconf",
100467  /* 177 */ "insert_cmd ::= REPLACE",
100468  /* 178 */ "itemlist ::= itemlist COMMA expr",
100469  /* 179 */ "itemlist ::= expr",
100470  /* 180 */ "inscollist_opt ::=",
100471  /* 181 */ "inscollist_opt ::= LP inscollist RP",
100472  /* 182 */ "inscollist ::= inscollist COMMA nm",
100473  /* 183 */ "inscollist ::= nm",
100474  /* 184 */ "expr ::= term",
100475  /* 185 */ "expr ::= LP expr RP",
100476  /* 186 */ "term ::= NULL",
100477  /* 187 */ "expr ::= id",
100478  /* 188 */ "expr ::= JOIN_KW",
100479  /* 189 */ "expr ::= nm DOT nm",
100480  /* 190 */ "expr ::= nm DOT nm DOT nm",
100481  /* 191 */ "term ::= INTEGER|FLOAT|BLOB",
100482  /* 192 */ "term ::= STRING",
100483  /* 193 */ "expr ::= REGISTER",
100484  /* 194 */ "expr ::= VARIABLE",
100485  /* 195 */ "expr ::= expr COLLATE ids",
100486  /* 196 */ "expr ::= CAST LP expr AS typetoken RP",
100487  /* 197 */ "expr ::= ID LP distinct exprlist RP",
100488  /* 198 */ "expr ::= ID LP STAR RP",
100489  /* 199 */ "term ::= CTIME_KW",
100490  /* 200 */ "expr ::= expr AND expr",
100491  /* 201 */ "expr ::= expr OR expr",
100492  /* 202 */ "expr ::= expr LT|GT|GE|LE expr",
100493  /* 203 */ "expr ::= expr EQ|NE expr",
100494  /* 204 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
100495  /* 205 */ "expr ::= expr PLUS|MINUS expr",
100496  /* 206 */ "expr ::= expr STAR|SLASH|REM expr",
100497  /* 207 */ "expr ::= expr CONCAT expr",
100498  /* 208 */ "likeop ::= LIKE_KW",
100499  /* 209 */ "likeop ::= NOT LIKE_KW",
100500  /* 210 */ "likeop ::= MATCH",
100501  /* 211 */ "likeop ::= NOT MATCH",
100502  /* 212 */ "expr ::= expr likeop expr",
100503  /* 213 */ "expr ::= expr likeop expr ESCAPE expr",
100504  /* 214 */ "expr ::= expr ISNULL|NOTNULL",
100505  /* 215 */ "expr ::= expr NOT NULL",
100506  /* 216 */ "expr ::= expr IS expr",
100507  /* 217 */ "expr ::= expr IS NOT expr",
100508  /* 218 */ "expr ::= NOT expr",
100509  /* 219 */ "expr ::= BITNOT expr",
100510  /* 220 */ "expr ::= MINUS expr",
100511  /* 221 */ "expr ::= PLUS expr",
100512  /* 222 */ "between_op ::= BETWEEN",
100513  /* 223 */ "between_op ::= NOT BETWEEN",
100514  /* 224 */ "expr ::= expr between_op expr AND expr",
100515  /* 225 */ "in_op ::= IN",
100516  /* 226 */ "in_op ::= NOT IN",
100517  /* 227 */ "expr ::= expr in_op LP exprlist RP",
100518  /* 228 */ "expr ::= LP select RP",
100519  /* 229 */ "expr ::= expr in_op LP select RP",
100520  /* 230 */ "expr ::= expr in_op nm dbnm",
100521  /* 231 */ "expr ::= EXISTS LP select RP",
100522  /* 232 */ "expr ::= CASE case_operand case_exprlist case_else END",
100523  /* 233 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
100524  /* 234 */ "case_exprlist ::= WHEN expr THEN expr",
100525  /* 235 */ "case_else ::= ELSE expr",
100526  /* 236 */ "case_else ::=",
100527  /* 237 */ "case_operand ::= expr",
100528  /* 238 */ "case_operand ::=",
100529  /* 239 */ "exprlist ::= nexprlist",
100530  /* 240 */ "exprlist ::=",
100531  /* 241 */ "nexprlist ::= nexprlist COMMA expr",
100532  /* 242 */ "nexprlist ::= expr",
100533  /* 243 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP",
100534  /* 244 */ "uniqueflag ::= UNIQUE",
100535  /* 245 */ "uniqueflag ::=",
100536  /* 246 */ "idxlist_opt ::=",
100537  /* 247 */ "idxlist_opt ::= LP idxlist RP",
100538  /* 248 */ "idxlist ::= idxlist COMMA nm collate sortorder",
100539  /* 249 */ "idxlist ::= nm collate sortorder",
100540  /* 250 */ "collate ::=",
100541  /* 251 */ "collate ::= COLLATE ids",
100542  /* 252 */ "cmd ::= DROP INDEX ifexists fullname",
100543  /* 253 */ "cmd ::= VACUUM",
100544  /* 254 */ "cmd ::= VACUUM nm",
100545  /* 255 */ "cmd ::= PRAGMA nm dbnm",
100546  /* 256 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
100547  /* 257 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
100548  /* 258 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
100549  /* 259 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
100550  /* 260 */ "nmnum ::= plus_num",
100551  /* 261 */ "nmnum ::= nm",
100552  /* 262 */ "nmnum ::= ON",
100553  /* 263 */ "nmnum ::= DELETE",
100554  /* 264 */ "nmnum ::= DEFAULT",
100555  /* 265 */ "plus_num ::= plus_opt number",
100556  /* 266 */ "minus_num ::= MINUS number",
100557  /* 267 */ "number ::= INTEGER|FLOAT",
100558  /* 268 */ "plus_opt ::= PLUS",
100559  /* 269 */ "plus_opt ::=",
100560  /* 270 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
100561  /* 271 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
100562  /* 272 */ "trigger_time ::= BEFORE",
100563  /* 273 */ "trigger_time ::= AFTER",
100564  /* 274 */ "trigger_time ::= INSTEAD OF",
100565  /* 275 */ "trigger_time ::=",
100566  /* 276 */ "trigger_event ::= DELETE|INSERT",
100567  /* 277 */ "trigger_event ::= UPDATE",
100568  /* 278 */ "trigger_event ::= UPDATE OF inscollist",
100569  /* 279 */ "foreach_clause ::=",
100570  /* 280 */ "foreach_clause ::= FOR EACH ROW",
100571  /* 281 */ "when_clause ::=",
100572  /* 282 */ "when_clause ::= WHEN expr",
100573  /* 283 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
100574  /* 284 */ "trigger_cmd_list ::= trigger_cmd SEMI",
100575  /* 285 */ "trnm ::= nm",
100576  /* 286 */ "trnm ::= nm DOT nm",
100577  /* 287 */ "tridxby ::=",
100578  /* 288 */ "tridxby ::= INDEXED BY nm",
100579  /* 289 */ "tridxby ::= NOT INDEXED",
100580  /* 290 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
100581  /* 291 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt VALUES LP itemlist RP",
100582  /* 292 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select",
100583  /* 293 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
100584  /* 294 */ "trigger_cmd ::= select",
100585  /* 295 */ "expr ::= RAISE LP IGNORE RP",
100586  /* 296 */ "expr ::= RAISE LP raisetype COMMA nm RP",
100587  /* 297 */ "raisetype ::= ROLLBACK",
100588  /* 298 */ "raisetype ::= ABORT",
100589  /* 299 */ "raisetype ::= FAIL",
100590  /* 300 */ "cmd ::= DROP TRIGGER ifexists fullname",
100591  /* 301 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
100592  /* 302 */ "cmd ::= DETACH database_kw_opt expr",
100593  /* 303 */ "key_opt ::=",
100594  /* 304 */ "key_opt ::= KEY expr",
100595  /* 305 */ "database_kw_opt ::= DATABASE",
100596  /* 306 */ "database_kw_opt ::=",
100597  /* 307 */ "cmd ::= REINDEX",
100598  /* 308 */ "cmd ::= REINDEX nm dbnm",
100599  /* 309 */ "cmd ::= ANALYZE",
100600  /* 310 */ "cmd ::= ANALYZE nm dbnm",
100601  /* 311 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
100602  /* 312 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
100603  /* 313 */ "add_column_fullname ::= fullname",
100604  /* 314 */ "kwcolumn_opt ::=",
100605  /* 315 */ "kwcolumn_opt ::= COLUMNKW",
100606  /* 316 */ "cmd ::= create_vtab",
100607  /* 317 */ "cmd ::= create_vtab LP vtabarglist RP",
100608  /* 318 */ "create_vtab ::= createkw VIRTUAL TABLE nm dbnm USING nm",
100609  /* 319 */ "vtabarglist ::= vtabarg",
100610  /* 320 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
100611  /* 321 */ "vtabarg ::=",
100612  /* 322 */ "vtabarg ::= vtabarg vtabargtoken",
100613  /* 323 */ "vtabargtoken ::= ANY",
100614  /* 324 */ "vtabargtoken ::= lp anylist RP",
100615  /* 325 */ "lp ::= LP",
100616  /* 326 */ "anylist ::=",
100617  /* 327 */ "anylist ::= anylist LP anylist RP",
100618  /* 328 */ "anylist ::= anylist ANY",
100619 };
100620 #endif /* NDEBUG */
100621
100622
100623 #if YYSTACKDEPTH<=0
100624 /*
100625 ** Try to increase the size of the parser stack.
100626 */
100627 static void yyGrowStack(yyParser *p){
100628   int newSize;
100629   yyStackEntry *pNew;
100630
100631   newSize = p->yystksz*2 + 100;
100632   pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
100633   if( pNew ){
100634     p->yystack = pNew;
100635     p->yystksz = newSize;
100636 #ifndef NDEBUG
100637     if( yyTraceFILE ){
100638       fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
100639               yyTracePrompt, p->yystksz);
100640     }
100641 #endif
100642   }
100643 }
100644 #endif
100645
100646 /* 
100647 ** This function allocates a new parser.
100648 ** The only argument is a pointer to a function which works like
100649 ** malloc.
100650 **
100651 ** Inputs:
100652 ** A pointer to the function used to allocate memory.
100653 **
100654 ** Outputs:
100655 ** A pointer to a parser.  This pointer is used in subsequent calls
100656 ** to sqlite3Parser and sqlite3ParserFree.
100657 */
100658 SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){
100659   yyParser *pParser;
100660   pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
100661   if( pParser ){
100662     pParser->yyidx = -1;
100663 #ifdef YYTRACKMAXSTACKDEPTH
100664     pParser->yyidxMax = 0;
100665 #endif
100666 #if YYSTACKDEPTH<=0
100667     pParser->yystack = NULL;
100668     pParser->yystksz = 0;
100669     yyGrowStack(pParser);
100670 #endif
100671   }
100672   return pParser;
100673 }
100674
100675 /* The following function deletes the value associated with a
100676 ** symbol.  The symbol can be either a terminal or nonterminal.
100677 ** "yymajor" is the symbol code, and "yypminor" is a pointer to
100678 ** the value.
100679 */
100680 static void yy_destructor(
100681   yyParser *yypParser,    /* The parser */
100682   YYCODETYPE yymajor,     /* Type code for object to destroy */
100683   YYMINORTYPE *yypminor   /* The object to be destroyed */
100684 ){
100685   sqlite3ParserARG_FETCH;
100686   switch( yymajor ){
100687     /* Here is inserted the actions which take place when a
100688     ** terminal or non-terminal is destroyed.  This can happen
100689     ** when the symbol is popped from the stack during a
100690     ** reduce or during error processing or when a parser is 
100691     ** being destroyed before it is finished parsing.
100692     **
100693     ** Note: during a reduce, the only symbols destroyed are those
100694     ** which appear on the RHS of the rule, but which are not used
100695     ** inside the C code.
100696     */
100697     case 160: /* select */
100698     case 194: /* oneselect */
100699 {
100700 sqlite3SelectDelete(pParse->db, (yypminor->yy387));
100701 }
100702       break;
100703     case 174: /* term */
100704     case 175: /* expr */
100705 {
100706 sqlite3ExprDelete(pParse->db, (yypminor->yy118).pExpr);
100707 }
100708       break;
100709     case 179: /* idxlist_opt */
100710     case 187: /* idxlist */
100711     case 197: /* selcollist */
100712     case 200: /* groupby_opt */
100713     case 202: /* orderby_opt */
100714     case 204: /* sclp */
100715     case 214: /* sortlist */
100716     case 216: /* nexprlist */
100717     case 217: /* setlist */
100718     case 220: /* itemlist */
100719     case 221: /* exprlist */
100720     case 226: /* case_exprlist */
100721 {
100722 sqlite3ExprListDelete(pParse->db, (yypminor->yy322));
100723 }
100724       break;
100725     case 193: /* fullname */
100726     case 198: /* from */
100727     case 206: /* seltablist */
100728     case 207: /* stl_prefix */
100729 {
100730 sqlite3SrcListDelete(pParse->db, (yypminor->yy259));
100731 }
100732       break;
100733     case 199: /* where_opt */
100734     case 201: /* having_opt */
100735     case 210: /* on_opt */
100736     case 215: /* sortitem */
100737     case 225: /* case_operand */
100738     case 227: /* case_else */
100739     case 238: /* when_clause */
100740     case 243: /* key_opt */
100741 {
100742 sqlite3ExprDelete(pParse->db, (yypminor->yy314));
100743 }
100744       break;
100745     case 211: /* using_opt */
100746     case 213: /* inscollist */
100747     case 219: /* inscollist_opt */
100748 {
100749 sqlite3IdListDelete(pParse->db, (yypminor->yy384));
100750 }
100751       break;
100752     case 234: /* trigger_cmd_list */
100753     case 239: /* trigger_cmd */
100754 {
100755 sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy203));
100756 }
100757       break;
100758     case 236: /* trigger_event */
100759 {
100760 sqlite3IdListDelete(pParse->db, (yypminor->yy90).b);
100761 }
100762       break;
100763     default:  break;   /* If no destructor action specified: do nothing */
100764   }
100765 }
100766
100767 /*
100768 ** Pop the parser's stack once.
100769 **
100770 ** If there is a destructor routine associated with the token which
100771 ** is popped from the stack, then call it.
100772 **
100773 ** Return the major token number for the symbol popped.
100774 */
100775 static int yy_pop_parser_stack(yyParser *pParser){
100776   YYCODETYPE yymajor;
100777   yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
100778
100779   /* There is no mechanism by which the parser stack can be popped below
100780   ** empty in SQLite.  */
100781   if( NEVER(pParser->yyidx<0) ) return 0;
100782 #ifndef NDEBUG
100783   if( yyTraceFILE && pParser->yyidx>=0 ){
100784     fprintf(yyTraceFILE,"%sPopping %s\n",
100785       yyTracePrompt,
100786       yyTokenName[yytos->major]);
100787   }
100788 #endif
100789   yymajor = yytos->major;
100790   yy_destructor(pParser, yymajor, &yytos->minor);
100791   pParser->yyidx--;
100792   return yymajor;
100793 }
100794
100795 /* 
100796 ** Deallocate and destroy a parser.  Destructors are all called for
100797 ** all stack elements before shutting the parser down.
100798 **
100799 ** Inputs:
100800 ** <ul>
100801 ** <li>  A pointer to the parser.  This should be a pointer
100802 **       obtained from sqlite3ParserAlloc.
100803 ** <li>  A pointer to a function used to reclaim memory obtained
100804 **       from malloc.
100805 ** </ul>
100806 */
100807 SQLITE_PRIVATE void sqlite3ParserFree(
100808   void *p,                    /* The parser to be deleted */
100809   void (*freeProc)(void*)     /* Function used to reclaim memory */
100810 ){
100811   yyParser *pParser = (yyParser*)p;
100812   /* In SQLite, we never try to destroy a parser that was not successfully
100813   ** created in the first place. */
100814   if( NEVER(pParser==0) ) return;
100815   while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
100816 #if YYSTACKDEPTH<=0
100817   free(pParser->yystack);
100818 #endif
100819   (*freeProc)((void*)pParser);
100820 }
100821
100822 /*
100823 ** Return the peak depth of the stack for a parser.
100824 */
100825 #ifdef YYTRACKMAXSTACKDEPTH
100826 SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
100827   yyParser *pParser = (yyParser*)p;
100828   return pParser->yyidxMax;
100829 }
100830 #endif
100831
100832 /*
100833 ** Find the appropriate action for a parser given the terminal
100834 ** look-ahead token iLookAhead.
100835 **
100836 ** If the look-ahead token is YYNOCODE, then check to see if the action is
100837 ** independent of the look-ahead.  If it is, return the action, otherwise
100838 ** return YY_NO_ACTION.
100839 */
100840 static int yy_find_shift_action(
100841   yyParser *pParser,        /* The parser */
100842   YYCODETYPE iLookAhead     /* The look-ahead token */
100843 ){
100844   int i;
100845   int stateno = pParser->yystack[pParser->yyidx].stateno;
100846  
100847   if( stateno>YY_SHIFT_COUNT
100848    || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
100849     return yy_default[stateno];
100850   }
100851   assert( iLookAhead!=YYNOCODE );
100852   i += iLookAhead;
100853   if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
100854     if( iLookAhead>0 ){
100855 #ifdef YYFALLBACK
100856       YYCODETYPE iFallback;            /* Fallback token */
100857       if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
100858              && (iFallback = yyFallback[iLookAhead])!=0 ){
100859 #ifndef NDEBUG
100860         if( yyTraceFILE ){
100861           fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
100862              yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
100863         }
100864 #endif
100865         return yy_find_shift_action(pParser, iFallback);
100866       }
100867 #endif
100868 #ifdef YYWILDCARD
100869       {
100870         int j = i - iLookAhead + YYWILDCARD;
100871         if( 
100872 #if YY_SHIFT_MIN+YYWILDCARD<0
100873           j>=0 &&
100874 #endif
100875 #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
100876           j<YY_ACTTAB_COUNT &&
100877 #endif
100878           yy_lookahead[j]==YYWILDCARD
100879         ){
100880 #ifndef NDEBUG
100881           if( yyTraceFILE ){
100882             fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
100883                yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
100884           }
100885 #endif /* NDEBUG */
100886           return yy_action[j];
100887         }
100888       }
100889 #endif /* YYWILDCARD */
100890     }
100891     return yy_default[stateno];
100892   }else{
100893     return yy_action[i];
100894   }
100895 }
100896
100897 /*
100898 ** Find the appropriate action for a parser given the non-terminal
100899 ** look-ahead token iLookAhead.
100900 **
100901 ** If the look-ahead token is YYNOCODE, then check to see if the action is
100902 ** independent of the look-ahead.  If it is, return the action, otherwise
100903 ** return YY_NO_ACTION.
100904 */
100905 static int yy_find_reduce_action(
100906   int stateno,              /* Current state number */
100907   YYCODETYPE iLookAhead     /* The look-ahead token */
100908 ){
100909   int i;
100910 #ifdef YYERRORSYMBOL
100911   if( stateno>YY_REDUCE_COUNT ){
100912     return yy_default[stateno];
100913   }
100914 #else
100915   assert( stateno<=YY_REDUCE_COUNT );
100916 #endif
100917   i = yy_reduce_ofst[stateno];
100918   assert( i!=YY_REDUCE_USE_DFLT );
100919   assert( iLookAhead!=YYNOCODE );
100920   i += iLookAhead;
100921 #ifdef YYERRORSYMBOL
100922   if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
100923     return yy_default[stateno];
100924   }
100925 #else
100926   assert( i>=0 && i<YY_ACTTAB_COUNT );
100927   assert( yy_lookahead[i]==iLookAhead );
100928 #endif
100929   return yy_action[i];
100930 }
100931
100932 /*
100933 ** The following routine is called if the stack overflows.
100934 */
100935 static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
100936    sqlite3ParserARG_FETCH;
100937    yypParser->yyidx--;
100938 #ifndef NDEBUG
100939    if( yyTraceFILE ){
100940      fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
100941    }
100942 #endif
100943    while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
100944    /* Here code is inserted which will execute if the parser
100945    ** stack every overflows */
100946
100947   UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
100948   sqlite3ErrorMsg(pParse, "parser stack overflow");
100949   pParse->parseError = 1;
100950    sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
100951 }
100952
100953 /*
100954 ** Perform a shift action.
100955 */
100956 static void yy_shift(
100957   yyParser *yypParser,          /* The parser to be shifted */
100958   int yyNewState,               /* The new state to shift in */
100959   int yyMajor,                  /* The major token to shift in */
100960   YYMINORTYPE *yypMinor         /* Pointer to the minor token to shift in */
100961 ){
100962   yyStackEntry *yytos;
100963   yypParser->yyidx++;
100964 #ifdef YYTRACKMAXSTACKDEPTH
100965   if( yypParser->yyidx>yypParser->yyidxMax ){
100966     yypParser->yyidxMax = yypParser->yyidx;
100967   }
100968 #endif
100969 #if YYSTACKDEPTH>0 
100970   if( yypParser->yyidx>=YYSTACKDEPTH ){
100971     yyStackOverflow(yypParser, yypMinor);
100972     return;
100973   }
100974 #else
100975   if( yypParser->yyidx>=yypParser->yystksz ){
100976     yyGrowStack(yypParser);
100977     if( yypParser->yyidx>=yypParser->yystksz ){
100978       yyStackOverflow(yypParser, yypMinor);
100979       return;
100980     }
100981   }
100982 #endif
100983   yytos = &yypParser->yystack[yypParser->yyidx];
100984   yytos->stateno = (YYACTIONTYPE)yyNewState;
100985   yytos->major = (YYCODETYPE)yyMajor;
100986   yytos->minor = *yypMinor;
100987 #ifndef NDEBUG
100988   if( yyTraceFILE && yypParser->yyidx>0 ){
100989     int i;
100990     fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
100991     fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
100992     for(i=1; i<=yypParser->yyidx; i++)
100993       fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
100994     fprintf(yyTraceFILE,"\n");
100995   }
100996 #endif
100997 }
100998
100999 /* The following table contains information about every rule that
101000 ** is used during the reduce.
101001 */
101002 static const struct {
101003   YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
101004   unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
101005 } yyRuleInfo[] = {
101006   { 142, 1 },
101007   { 143, 2 },
101008   { 143, 1 },
101009   { 144, 1 },
101010   { 144, 3 },
101011   { 145, 0 },
101012   { 145, 1 },
101013   { 145, 3 },
101014   { 146, 1 },
101015   { 147, 3 },
101016   { 149, 0 },
101017   { 149, 1 },
101018   { 149, 2 },
101019   { 148, 0 },
101020   { 148, 1 },
101021   { 148, 1 },
101022   { 148, 1 },
101023   { 147, 2 },
101024   { 147, 2 },
101025   { 147, 2 },
101026   { 151, 1 },
101027   { 151, 0 },
101028   { 147, 2 },
101029   { 147, 3 },
101030   { 147, 5 },
101031   { 147, 2 },
101032   { 152, 6 },
101033   { 154, 1 },
101034   { 156, 0 },
101035   { 156, 3 },
101036   { 155, 1 },
101037   { 155, 0 },
101038   { 153, 4 },
101039   { 153, 2 },
101040   { 158, 3 },
101041   { 158, 1 },
101042   { 161, 3 },
101043   { 162, 1 },
101044   { 165, 1 },
101045   { 165, 1 },
101046   { 166, 1 },
101047   { 150, 1 },
101048   { 150, 1 },
101049   { 150, 1 },
101050   { 163, 0 },
101051   { 163, 1 },
101052   { 167, 1 },
101053   { 167, 4 },
101054   { 167, 6 },
101055   { 168, 1 },
101056   { 168, 2 },
101057   { 169, 1 },
101058   { 169, 1 },
101059   { 164, 2 },
101060   { 164, 0 },
101061   { 172, 3 },
101062   { 172, 1 },
101063   { 173, 2 },
101064   { 173, 4 },
101065   { 173, 3 },
101066   { 173, 3 },
101067   { 173, 2 },
101068   { 173, 2 },
101069   { 173, 3 },
101070   { 173, 5 },
101071   { 173, 2 },
101072   { 173, 4 },
101073   { 173, 4 },
101074   { 173, 1 },
101075   { 173, 2 },
101076   { 178, 0 },
101077   { 178, 1 },
101078   { 180, 0 },
101079   { 180, 2 },
101080   { 182, 2 },
101081   { 182, 3 },
101082   { 182, 3 },
101083   { 182, 3 },
101084   { 183, 2 },
101085   { 183, 2 },
101086   { 183, 1 },
101087   { 183, 1 },
101088   { 183, 2 },
101089   { 181, 3 },
101090   { 181, 2 },
101091   { 184, 0 },
101092   { 184, 2 },
101093   { 184, 2 },
101094   { 159, 0 },
101095   { 159, 2 },
101096   { 185, 3 },
101097   { 185, 2 },
101098   { 185, 1 },
101099   { 186, 2 },
101100   { 186, 7 },
101101   { 186, 5 },
101102   { 186, 5 },
101103   { 186, 10 },
101104   { 188, 0 },
101105   { 188, 1 },
101106   { 176, 0 },
101107   { 176, 3 },
101108   { 189, 0 },
101109   { 189, 2 },
101110   { 190, 1 },
101111   { 190, 1 },
101112   { 190, 1 },
101113   { 147, 4 },
101114   { 192, 2 },
101115   { 192, 0 },
101116   { 147, 8 },
101117   { 147, 4 },
101118   { 147, 1 },
101119   { 160, 1 },
101120   { 160, 3 },
101121   { 195, 1 },
101122   { 195, 2 },
101123   { 195, 1 },
101124   { 194, 9 },
101125   { 196, 1 },
101126   { 196, 1 },
101127   { 196, 0 },
101128   { 204, 2 },
101129   { 204, 0 },
101130   { 197, 3 },
101131   { 197, 2 },
101132   { 197, 4 },
101133   { 205, 2 },
101134   { 205, 1 },
101135   { 205, 0 },
101136   { 198, 0 },
101137   { 198, 2 },
101138   { 207, 2 },
101139   { 207, 0 },
101140   { 206, 7 },
101141   { 206, 7 },
101142   { 206, 7 },
101143   { 157, 0 },
101144   { 157, 2 },
101145   { 193, 2 },
101146   { 208, 1 },
101147   { 208, 2 },
101148   { 208, 3 },
101149   { 208, 4 },
101150   { 210, 2 },
101151   { 210, 0 },
101152   { 209, 0 },
101153   { 209, 3 },
101154   { 209, 2 },
101155   { 211, 4 },
101156   { 211, 0 },
101157   { 202, 0 },
101158   { 202, 3 },
101159   { 214, 4 },
101160   { 214, 2 },
101161   { 215, 1 },
101162   { 177, 1 },
101163   { 177, 1 },
101164   { 177, 0 },
101165   { 200, 0 },
101166   { 200, 3 },
101167   { 201, 0 },
101168   { 201, 2 },
101169   { 203, 0 },
101170   { 203, 2 },
101171   { 203, 4 },
101172   { 203, 4 },
101173   { 147, 5 },
101174   { 199, 0 },
101175   { 199, 2 },
101176   { 147, 7 },
101177   { 217, 5 },
101178   { 217, 3 },
101179   { 147, 8 },
101180   { 147, 5 },
101181   { 147, 6 },
101182   { 218, 2 },
101183   { 218, 1 },
101184   { 220, 3 },
101185   { 220, 1 },
101186   { 219, 0 },
101187   { 219, 3 },
101188   { 213, 3 },
101189   { 213, 1 },
101190   { 175, 1 },
101191   { 175, 3 },
101192   { 174, 1 },
101193   { 175, 1 },
101194   { 175, 1 },
101195   { 175, 3 },
101196   { 175, 5 },
101197   { 174, 1 },
101198   { 174, 1 },
101199   { 175, 1 },
101200   { 175, 1 },
101201   { 175, 3 },
101202   { 175, 6 },
101203   { 175, 5 },
101204   { 175, 4 },
101205   { 174, 1 },
101206   { 175, 3 },
101207   { 175, 3 },
101208   { 175, 3 },
101209   { 175, 3 },
101210   { 175, 3 },
101211   { 175, 3 },
101212   { 175, 3 },
101213   { 175, 3 },
101214   { 222, 1 },
101215   { 222, 2 },
101216   { 222, 1 },
101217   { 222, 2 },
101218   { 175, 3 },
101219   { 175, 5 },
101220   { 175, 2 },
101221   { 175, 3 },
101222   { 175, 3 },
101223   { 175, 4 },
101224   { 175, 2 },
101225   { 175, 2 },
101226   { 175, 2 },
101227   { 175, 2 },
101228   { 223, 1 },
101229   { 223, 2 },
101230   { 175, 5 },
101231   { 224, 1 },
101232   { 224, 2 },
101233   { 175, 5 },
101234   { 175, 3 },
101235   { 175, 5 },
101236   { 175, 4 },
101237   { 175, 4 },
101238   { 175, 5 },
101239   { 226, 5 },
101240   { 226, 4 },
101241   { 227, 2 },
101242   { 227, 0 },
101243   { 225, 1 },
101244   { 225, 0 },
101245   { 221, 1 },
101246   { 221, 0 },
101247   { 216, 3 },
101248   { 216, 1 },
101249   { 147, 11 },
101250   { 228, 1 },
101251   { 228, 0 },
101252   { 179, 0 },
101253   { 179, 3 },
101254   { 187, 5 },
101255   { 187, 3 },
101256   { 229, 0 },
101257   { 229, 2 },
101258   { 147, 4 },
101259   { 147, 1 },
101260   { 147, 2 },
101261   { 147, 3 },
101262   { 147, 5 },
101263   { 147, 6 },
101264   { 147, 5 },
101265   { 147, 6 },
101266   { 230, 1 },
101267   { 230, 1 },
101268   { 230, 1 },
101269   { 230, 1 },
101270   { 230, 1 },
101271   { 170, 2 },
101272   { 171, 2 },
101273   { 232, 1 },
101274   { 231, 1 },
101275   { 231, 0 },
101276   { 147, 5 },
101277   { 233, 11 },
101278   { 235, 1 },
101279   { 235, 1 },
101280   { 235, 2 },
101281   { 235, 0 },
101282   { 236, 1 },
101283   { 236, 1 },
101284   { 236, 3 },
101285   { 237, 0 },
101286   { 237, 3 },
101287   { 238, 0 },
101288   { 238, 2 },
101289   { 234, 3 },
101290   { 234, 2 },
101291   { 240, 1 },
101292   { 240, 3 },
101293   { 241, 0 },
101294   { 241, 3 },
101295   { 241, 2 },
101296   { 239, 7 },
101297   { 239, 8 },
101298   { 239, 5 },
101299   { 239, 5 },
101300   { 239, 1 },
101301   { 175, 4 },
101302   { 175, 6 },
101303   { 191, 1 },
101304   { 191, 1 },
101305   { 191, 1 },
101306   { 147, 4 },
101307   { 147, 6 },
101308   { 147, 3 },
101309   { 243, 0 },
101310   { 243, 2 },
101311   { 242, 1 },
101312   { 242, 0 },
101313   { 147, 1 },
101314   { 147, 3 },
101315   { 147, 1 },
101316   { 147, 3 },
101317   { 147, 6 },
101318   { 147, 6 },
101319   { 244, 1 },
101320   { 245, 0 },
101321   { 245, 1 },
101322   { 147, 1 },
101323   { 147, 4 },
101324   { 246, 7 },
101325   { 247, 1 },
101326   { 247, 3 },
101327   { 248, 0 },
101328   { 248, 2 },
101329   { 249, 1 },
101330   { 249, 3 },
101331   { 250, 1 },
101332   { 251, 0 },
101333   { 251, 4 },
101334   { 251, 2 },
101335 };
101336
101337 static void yy_accept(yyParser*);  /* Forward Declaration */
101338
101339 /*
101340 ** Perform a reduce action and the shift that must immediately
101341 ** follow the reduce.
101342 */
101343 static void yy_reduce(
101344   yyParser *yypParser,         /* The parser */
101345   int yyruleno                 /* Number of the rule by which to reduce */
101346 ){
101347   int yygoto;                     /* The next state */
101348   int yyact;                      /* The next action */
101349   YYMINORTYPE yygotominor;        /* The LHS of the rule reduced */
101350   yyStackEntry *yymsp;            /* The top of the parser's stack */
101351   int yysize;                     /* Amount to pop the stack */
101352   sqlite3ParserARG_FETCH;
101353   yymsp = &yypParser->yystack[yypParser->yyidx];
101354 #ifndef NDEBUG
101355   if( yyTraceFILE && yyruleno>=0 
101356         && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
101357     fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
101358       yyRuleName[yyruleno]);
101359   }
101360 #endif /* NDEBUG */
101361
101362   /* Silence complaints from purify about yygotominor being uninitialized
101363   ** in some cases when it is copied into the stack after the following
101364   ** switch.  yygotominor is uninitialized when a rule reduces that does
101365   ** not set the value of its left-hand side nonterminal.  Leaving the
101366   ** value of the nonterminal uninitialized is utterly harmless as long
101367   ** as the value is never used.  So really the only thing this code
101368   ** accomplishes is to quieten purify.  
101369   **
101370   ** 2007-01-16:  The wireshark project (www.wireshark.org) reports that
101371   ** without this code, their parser segfaults.  I'm not sure what there
101372   ** parser is doing to make this happen.  This is the second bug report
101373   ** from wireshark this week.  Clearly they are stressing Lemon in ways
101374   ** that it has not been previously stressed...  (SQLite ticket #2172)
101375   */
101376   /*memset(&yygotominor, 0, sizeof(yygotominor));*/
101377   yygotominor = yyzerominor;
101378
101379
101380   switch( yyruleno ){
101381   /* Beginning here are the reduction cases.  A typical example
101382   ** follows:
101383   **   case 0:
101384   **  #line <lineno> <grammarfile>
101385   **     { ... }           // User supplied code
101386   **  #line <lineno> <thisfile>
101387   **     break;
101388   */
101389       case 5: /* explain ::= */
101390 { sqlite3BeginParse(pParse, 0); }
101391         break;
101392       case 6: /* explain ::= EXPLAIN */
101393 { sqlite3BeginParse(pParse, 1); }
101394         break;
101395       case 7: /* explain ::= EXPLAIN QUERY PLAN */
101396 { sqlite3BeginParse(pParse, 2); }
101397         break;
101398       case 8: /* cmdx ::= cmd */
101399 { sqlite3FinishCoding(pParse); }
101400         break;
101401       case 9: /* cmd ::= BEGIN transtype trans_opt */
101402 {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy4);}
101403         break;
101404       case 13: /* transtype ::= */
101405 {yygotominor.yy4 = TK_DEFERRED;}
101406         break;
101407       case 14: /* transtype ::= DEFERRED */
101408       case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
101409       case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
101410       case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
101411       case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
101412 {yygotominor.yy4 = yymsp[0].major;}
101413         break;
101414       case 17: /* cmd ::= COMMIT trans_opt */
101415       case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
101416 {sqlite3CommitTransaction(pParse);}
101417         break;
101418       case 19: /* cmd ::= ROLLBACK trans_opt */
101419 {sqlite3RollbackTransaction(pParse);}
101420         break;
101421       case 22: /* cmd ::= SAVEPOINT nm */
101422 {
101423   sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
101424 }
101425         break;
101426       case 23: /* cmd ::= RELEASE savepoint_opt nm */
101427 {
101428   sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
101429 }
101430         break;
101431       case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
101432 {
101433   sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
101434 }
101435         break;
101436       case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
101437 {
101438    sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy4,0,0,yymsp[-2].minor.yy4);
101439 }
101440         break;
101441       case 27: /* createkw ::= CREATE */
101442 {
101443   pParse->db->lookaside.bEnabled = 0;
101444   yygotominor.yy0 = yymsp[0].minor.yy0;
101445 }
101446         break;
101447       case 28: /* ifnotexists ::= */
101448       case 31: /* temp ::= */ yytestcase(yyruleno==31);
101449       case 70: /* autoinc ::= */ yytestcase(yyruleno==70);
101450       case 83: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==83);
101451       case 85: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==85);
101452       case 87: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==87);
101453       case 98: /* defer_subclause_opt ::= */ yytestcase(yyruleno==98);
101454       case 109: /* ifexists ::= */ yytestcase(yyruleno==109);
101455       case 120: /* distinct ::= ALL */ yytestcase(yyruleno==120);
101456       case 121: /* distinct ::= */ yytestcase(yyruleno==121);
101457       case 222: /* between_op ::= BETWEEN */ yytestcase(yyruleno==222);
101458       case 225: /* in_op ::= IN */ yytestcase(yyruleno==225);
101459 {yygotominor.yy4 = 0;}
101460         break;
101461       case 29: /* ifnotexists ::= IF NOT EXISTS */
101462       case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
101463       case 71: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==71);
101464       case 86: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==86);
101465       case 108: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==108);
101466       case 119: /* distinct ::= DISTINCT */ yytestcase(yyruleno==119);
101467       case 223: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==223);
101468       case 226: /* in_op ::= NOT IN */ yytestcase(yyruleno==226);
101469 {yygotominor.yy4 = 1;}
101470         break;
101471       case 32: /* create_table_args ::= LP columnlist conslist_opt RP */
101472 {
101473   sqlite3EndTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0);
101474 }
101475         break;
101476       case 33: /* create_table_args ::= AS select */
101477 {
101478   sqlite3EndTable(pParse,0,0,yymsp[0].minor.yy387);
101479   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy387);
101480 }
101481         break;
101482       case 36: /* column ::= columnid type carglist */
101483 {
101484   yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
101485   yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
101486 }
101487         break;
101488       case 37: /* columnid ::= nm */
101489 {
101490   sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
101491   yygotominor.yy0 = yymsp[0].minor.yy0;
101492 }
101493         break;
101494       case 38: /* id ::= ID */
101495       case 39: /* id ::= INDEXED */ yytestcase(yyruleno==39);
101496       case 40: /* ids ::= ID|STRING */ yytestcase(yyruleno==40);
101497       case 41: /* nm ::= id */ yytestcase(yyruleno==41);
101498       case 42: /* nm ::= STRING */ yytestcase(yyruleno==42);
101499       case 43: /* nm ::= JOIN_KW */ yytestcase(yyruleno==43);
101500       case 46: /* typetoken ::= typename */ yytestcase(yyruleno==46);
101501       case 49: /* typename ::= ids */ yytestcase(yyruleno==49);
101502       case 127: /* as ::= AS nm */ yytestcase(yyruleno==127);
101503       case 128: /* as ::= ids */ yytestcase(yyruleno==128);
101504       case 138: /* dbnm ::= DOT nm */ yytestcase(yyruleno==138);
101505       case 147: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==147);
101506       case 251: /* collate ::= COLLATE ids */ yytestcase(yyruleno==251);
101507       case 260: /* nmnum ::= plus_num */ yytestcase(yyruleno==260);
101508       case 261: /* nmnum ::= nm */ yytestcase(yyruleno==261);
101509       case 262: /* nmnum ::= ON */ yytestcase(yyruleno==262);
101510       case 263: /* nmnum ::= DELETE */ yytestcase(yyruleno==263);
101511       case 264: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==264);
101512       case 265: /* plus_num ::= plus_opt number */ yytestcase(yyruleno==265);
101513       case 266: /* minus_num ::= MINUS number */ yytestcase(yyruleno==266);
101514       case 267: /* number ::= INTEGER|FLOAT */ yytestcase(yyruleno==267);
101515       case 285: /* trnm ::= nm */ yytestcase(yyruleno==285);
101516 {yygotominor.yy0 = yymsp[0].minor.yy0;}
101517         break;
101518       case 45: /* type ::= typetoken */
101519 {sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
101520         break;
101521       case 47: /* typetoken ::= typename LP signed RP */
101522 {
101523   yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
101524   yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
101525 }
101526         break;
101527       case 48: /* typetoken ::= typename LP signed COMMA signed RP */
101528 {
101529   yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
101530   yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
101531 }
101532         break;
101533       case 50: /* typename ::= typename ids */
101534 {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);}
101535         break;
101536       case 57: /* ccons ::= DEFAULT term */
101537       case 59: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==59);
101538 {sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy118);}
101539         break;
101540       case 58: /* ccons ::= DEFAULT LP expr RP */
101541 {sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy118);}
101542         break;
101543       case 60: /* ccons ::= DEFAULT MINUS term */
101544 {
101545   ExprSpan v;
101546   v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy118.pExpr, 0, 0);
101547   v.zStart = yymsp[-1].minor.yy0.z;
101548   v.zEnd = yymsp[0].minor.yy118.zEnd;
101549   sqlite3AddDefaultValue(pParse,&v);
101550 }
101551         break;
101552       case 61: /* ccons ::= DEFAULT id */
101553 {
101554   ExprSpan v;
101555   spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
101556   sqlite3AddDefaultValue(pParse,&v);
101557 }
101558         break;
101559       case 63: /* ccons ::= NOT NULL onconf */
101560 {sqlite3AddNotNull(pParse, yymsp[0].minor.yy4);}
101561         break;
101562       case 64: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
101563 {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy4,yymsp[0].minor.yy4,yymsp[-2].minor.yy4);}
101564         break;
101565       case 65: /* ccons ::= UNIQUE onconf */
101566 {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy4,0,0,0,0);}
101567         break;
101568       case 66: /* ccons ::= CHECK LP expr RP */
101569 {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy118.pExpr);}
101570         break;
101571       case 67: /* ccons ::= REFERENCES nm idxlist_opt refargs */
101572 {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy322,yymsp[0].minor.yy4);}
101573         break;
101574       case 68: /* ccons ::= defer_subclause */
101575 {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy4);}
101576         break;
101577       case 69: /* ccons ::= COLLATE ids */
101578 {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
101579         break;
101580       case 72: /* refargs ::= */
101581 { yygotominor.yy4 = OE_None*0x0101; /* EV: R-19803-45884 */}
101582         break;
101583       case 73: /* refargs ::= refargs refarg */
101584 { yygotominor.yy4 = (yymsp[-1].minor.yy4 & ~yymsp[0].minor.yy215.mask) | yymsp[0].minor.yy215.value; }
101585         break;
101586       case 74: /* refarg ::= MATCH nm */
101587       case 75: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==75);
101588 { yygotominor.yy215.value = 0;     yygotominor.yy215.mask = 0x000000; }
101589         break;
101590       case 76: /* refarg ::= ON DELETE refact */
101591 { yygotominor.yy215.value = yymsp[0].minor.yy4;     yygotominor.yy215.mask = 0x0000ff; }
101592         break;
101593       case 77: /* refarg ::= ON UPDATE refact */
101594 { yygotominor.yy215.value = yymsp[0].minor.yy4<<8;  yygotominor.yy215.mask = 0x00ff00; }
101595         break;
101596       case 78: /* refact ::= SET NULL */
101597 { yygotominor.yy4 = OE_SetNull;  /* EV: R-33326-45252 */}
101598         break;
101599       case 79: /* refact ::= SET DEFAULT */
101600 { yygotominor.yy4 = OE_SetDflt;  /* EV: R-33326-45252 */}
101601         break;
101602       case 80: /* refact ::= CASCADE */
101603 { yygotominor.yy4 = OE_Cascade;  /* EV: R-33326-45252 */}
101604         break;
101605       case 81: /* refact ::= RESTRICT */
101606 { yygotominor.yy4 = OE_Restrict; /* EV: R-33326-45252 */}
101607         break;
101608       case 82: /* refact ::= NO ACTION */
101609 { yygotominor.yy4 = OE_None;     /* EV: R-33326-45252 */}
101610         break;
101611       case 84: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
101612       case 99: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==99);
101613       case 101: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==101);
101614       case 104: /* resolvetype ::= raisetype */ yytestcase(yyruleno==104);
101615 {yygotominor.yy4 = yymsp[0].minor.yy4;}
101616         break;
101617       case 88: /* conslist_opt ::= */
101618 {yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
101619         break;
101620       case 89: /* conslist_opt ::= COMMA conslist */
101621 {yygotominor.yy0 = yymsp[-1].minor.yy0;}
101622         break;
101623       case 94: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
101624 {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy322,yymsp[0].minor.yy4,yymsp[-2].minor.yy4,0);}
101625         break;
101626       case 95: /* tcons ::= UNIQUE LP idxlist RP onconf */
101627 {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy322,yymsp[0].minor.yy4,0,0,0,0);}
101628         break;
101629       case 96: /* tcons ::= CHECK LP expr RP onconf */
101630 {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy118.pExpr);}
101631         break;
101632       case 97: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
101633 {
101634     sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy322, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy322, yymsp[-1].minor.yy4);
101635     sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy4);
101636 }
101637         break;
101638       case 100: /* onconf ::= */
101639 {yygotominor.yy4 = OE_Default;}
101640         break;
101641       case 102: /* orconf ::= */
101642 {yygotominor.yy210 = OE_Default;}
101643         break;
101644       case 103: /* orconf ::= OR resolvetype */
101645 {yygotominor.yy210 = (u8)yymsp[0].minor.yy4;}
101646         break;
101647       case 105: /* resolvetype ::= IGNORE */
101648 {yygotominor.yy4 = OE_Ignore;}
101649         break;
101650       case 106: /* resolvetype ::= REPLACE */
101651 {yygotominor.yy4 = OE_Replace;}
101652         break;
101653       case 107: /* cmd ::= DROP TABLE ifexists fullname */
101654 {
101655   sqlite3DropTable(pParse, yymsp[0].minor.yy259, 0, yymsp[-1].minor.yy4);
101656 }
101657         break;
101658       case 110: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */
101659 {
101660   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);
101661 }
101662         break;
101663       case 111: /* cmd ::= DROP VIEW ifexists fullname */
101664 {
101665   sqlite3DropTable(pParse, yymsp[0].minor.yy259, 1, yymsp[-1].minor.yy4);
101666 }
101667         break;
101668       case 112: /* cmd ::= select */
101669 {
101670   SelectDest dest = {SRT_Output, 0, 0, 0, 0};
101671   sqlite3Select(pParse, yymsp[0].minor.yy387, &dest);
101672   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy387);
101673 }
101674         break;
101675       case 113: /* select ::= oneselect */
101676 {yygotominor.yy387 = yymsp[0].minor.yy387;}
101677         break;
101678       case 114: /* select ::= select multiselect_op oneselect */
101679 {
101680   if( yymsp[0].minor.yy387 ){
101681     yymsp[0].minor.yy387->op = (u8)yymsp[-1].minor.yy4;
101682     yymsp[0].minor.yy387->pPrior = yymsp[-2].minor.yy387;
101683   }else{
101684     sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy387);
101685   }
101686   yygotominor.yy387 = yymsp[0].minor.yy387;
101687 }
101688         break;
101689       case 116: /* multiselect_op ::= UNION ALL */
101690 {yygotominor.yy4 = TK_ALL;}
101691         break;
101692       case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
101693 {
101694   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);
101695 }
101696         break;
101697       case 122: /* sclp ::= selcollist COMMA */
101698       case 247: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==247);
101699 {yygotominor.yy322 = yymsp[-1].minor.yy322;}
101700         break;
101701       case 123: /* sclp ::= */
101702       case 151: /* orderby_opt ::= */ yytestcase(yyruleno==151);
101703       case 159: /* groupby_opt ::= */ yytestcase(yyruleno==159);
101704       case 240: /* exprlist ::= */ yytestcase(yyruleno==240);
101705       case 246: /* idxlist_opt ::= */ yytestcase(yyruleno==246);
101706 {yygotominor.yy322 = 0;}
101707         break;
101708       case 124: /* selcollist ::= sclp expr as */
101709 {
101710    yygotominor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy322, yymsp[-1].minor.yy118.pExpr);
101711    if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[0].minor.yy0, 1);
101712    sqlite3ExprListSetSpan(pParse,yygotominor.yy322,&yymsp[-1].minor.yy118);
101713 }
101714         break;
101715       case 125: /* selcollist ::= sclp STAR */
101716 {
101717   Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
101718   yygotominor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy322, p);
101719 }
101720         break;
101721       case 126: /* selcollist ::= sclp nm DOT STAR */
101722 {
101723   Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
101724   Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
101725   Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
101726   yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy322, pDot);
101727 }
101728         break;
101729       case 129: /* as ::= */
101730 {yygotominor.yy0.n = 0;}
101731         break;
101732       case 130: /* from ::= */
101733 {yygotominor.yy259 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy259));}
101734         break;
101735       case 131: /* from ::= FROM seltablist */
101736 {
101737   yygotominor.yy259 = yymsp[0].minor.yy259;
101738   sqlite3SrcListShiftJoinType(yygotominor.yy259);
101739 }
101740         break;
101741       case 132: /* stl_prefix ::= seltablist joinop */
101742 {
101743    yygotominor.yy259 = yymsp[-1].minor.yy259;
101744    if( ALWAYS(yygotominor.yy259 && yygotominor.yy259->nSrc>0) ) yygotominor.yy259->a[yygotominor.yy259->nSrc-1].jointype = (u8)yymsp[0].minor.yy4;
101745 }
101746         break;
101747       case 133: /* stl_prefix ::= */
101748 {yygotominor.yy259 = 0;}
101749         break;
101750       case 134: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
101751 {
101752   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);
101753   sqlite3SrcListIndexedBy(pParse, yygotominor.yy259, &yymsp[-2].minor.yy0);
101754 }
101755         break;
101756       case 135: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
101757 {
101758     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);
101759   }
101760         break;
101761       case 136: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
101762 {
101763     if( yymsp[-6].minor.yy259==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy314==0 && yymsp[0].minor.yy384==0 ){
101764       yygotominor.yy259 = yymsp[-4].minor.yy259;
101765     }else{
101766       Select *pSubquery;
101767       sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy259);
101768       pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy259,0,0,0,0,0,0,0);
101769       yygotominor.yy259 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy259,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy314,yymsp[0].minor.yy384);
101770     }
101771   }
101772         break;
101773       case 137: /* dbnm ::= */
101774       case 146: /* indexed_opt ::= */ yytestcase(yyruleno==146);
101775 {yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
101776         break;
101777       case 139: /* fullname ::= nm dbnm */
101778 {yygotominor.yy259 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
101779         break;
101780       case 140: /* joinop ::= COMMA|JOIN */
101781 { yygotominor.yy4 = JT_INNER; }
101782         break;
101783       case 141: /* joinop ::= JOIN_KW JOIN */
101784 { yygotominor.yy4 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
101785         break;
101786       case 142: /* joinop ::= JOIN_KW nm JOIN */
101787 { yygotominor.yy4 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
101788         break;
101789       case 143: /* joinop ::= JOIN_KW nm nm JOIN */
101790 { yygotominor.yy4 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
101791         break;
101792       case 144: /* on_opt ::= ON expr */
101793       case 155: /* sortitem ::= expr */ yytestcase(yyruleno==155);
101794       case 162: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==162);
101795       case 169: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==169);
101796       case 235: /* case_else ::= ELSE expr */ yytestcase(yyruleno==235);
101797       case 237: /* case_operand ::= expr */ yytestcase(yyruleno==237);
101798 {yygotominor.yy314 = yymsp[0].minor.yy118.pExpr;}
101799         break;
101800       case 145: /* on_opt ::= */
101801       case 161: /* having_opt ::= */ yytestcase(yyruleno==161);
101802       case 168: /* where_opt ::= */ yytestcase(yyruleno==168);
101803       case 236: /* case_else ::= */ yytestcase(yyruleno==236);
101804       case 238: /* case_operand ::= */ yytestcase(yyruleno==238);
101805 {yygotominor.yy314 = 0;}
101806         break;
101807       case 148: /* indexed_opt ::= NOT INDEXED */
101808 {yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
101809         break;
101810       case 149: /* using_opt ::= USING LP inscollist RP */
101811       case 181: /* inscollist_opt ::= LP inscollist RP */ yytestcase(yyruleno==181);
101812 {yygotominor.yy384 = yymsp[-1].minor.yy384;}
101813         break;
101814       case 150: /* using_opt ::= */
101815       case 180: /* inscollist_opt ::= */ yytestcase(yyruleno==180);
101816 {yygotominor.yy384 = 0;}
101817         break;
101818       case 152: /* orderby_opt ::= ORDER BY sortlist */
101819       case 160: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==160);
101820       case 239: /* exprlist ::= nexprlist */ yytestcase(yyruleno==239);
101821 {yygotominor.yy322 = yymsp[0].minor.yy322;}
101822         break;
101823       case 153: /* sortlist ::= sortlist COMMA sortitem sortorder */
101824 {
101825   yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy322,yymsp[-1].minor.yy314);
101826   if( yygotominor.yy322 ) yygotominor.yy322->a[yygotominor.yy322->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy4;
101827 }
101828         break;
101829       case 154: /* sortlist ::= sortitem sortorder */
101830 {
101831   yygotominor.yy322 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy314);
101832   if( yygotominor.yy322 && ALWAYS(yygotominor.yy322->a) ) yygotominor.yy322->a[0].sortOrder = (u8)yymsp[0].minor.yy4;
101833 }
101834         break;
101835       case 156: /* sortorder ::= ASC */
101836       case 158: /* sortorder ::= */ yytestcase(yyruleno==158);
101837 {yygotominor.yy4 = SQLITE_SO_ASC;}
101838         break;
101839       case 157: /* sortorder ::= DESC */
101840 {yygotominor.yy4 = SQLITE_SO_DESC;}
101841         break;
101842       case 163: /* limit_opt ::= */
101843 {yygotominor.yy292.pLimit = 0; yygotominor.yy292.pOffset = 0;}
101844         break;
101845       case 164: /* limit_opt ::= LIMIT expr */
101846 {yygotominor.yy292.pLimit = yymsp[0].minor.yy118.pExpr; yygotominor.yy292.pOffset = 0;}
101847         break;
101848       case 165: /* limit_opt ::= LIMIT expr OFFSET expr */
101849 {yygotominor.yy292.pLimit = yymsp[-2].minor.yy118.pExpr; yygotominor.yy292.pOffset = yymsp[0].minor.yy118.pExpr;}
101850         break;
101851       case 166: /* limit_opt ::= LIMIT expr COMMA expr */
101852 {yygotominor.yy292.pOffset = yymsp[-2].minor.yy118.pExpr; yygotominor.yy292.pLimit = yymsp[0].minor.yy118.pExpr;}
101853         break;
101854       case 167: /* cmd ::= DELETE FROM fullname indexed_opt where_opt */
101855 {
101856   sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy259, &yymsp[-1].minor.yy0);
101857   sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy259,yymsp[0].minor.yy314);
101858 }
101859         break;
101860       case 170: /* cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt */
101861 {
101862   sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy259, &yymsp[-3].minor.yy0);
101863   sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy322,"set list"); 
101864   sqlite3Update(pParse,yymsp[-4].minor.yy259,yymsp[-1].minor.yy322,yymsp[0].minor.yy314,yymsp[-5].minor.yy210);
101865 }
101866         break;
101867       case 171: /* setlist ::= setlist COMMA nm EQ expr */
101868 {
101869   yygotominor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy322, yymsp[0].minor.yy118.pExpr);
101870   sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[-2].minor.yy0, 1);
101871 }
101872         break;
101873       case 172: /* setlist ::= nm EQ expr */
101874 {
101875   yygotominor.yy322 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy118.pExpr);
101876   sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[-2].minor.yy0, 1);
101877 }
101878         break;
101879       case 173: /* cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP */
101880 {sqlite3Insert(pParse, yymsp[-5].minor.yy259, yymsp[-1].minor.yy322, 0, yymsp[-4].minor.yy384, yymsp[-7].minor.yy210);}
101881         break;
101882       case 174: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */
101883 {sqlite3Insert(pParse, yymsp[-2].minor.yy259, 0, yymsp[0].minor.yy387, yymsp[-1].minor.yy384, yymsp[-4].minor.yy210);}
101884         break;
101885       case 175: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
101886 {sqlite3Insert(pParse, yymsp[-3].minor.yy259, 0, 0, yymsp[-2].minor.yy384, yymsp[-5].minor.yy210);}
101887         break;
101888       case 176: /* insert_cmd ::= INSERT orconf */
101889 {yygotominor.yy210 = yymsp[0].minor.yy210;}
101890         break;
101891       case 177: /* insert_cmd ::= REPLACE */
101892 {yygotominor.yy210 = OE_Replace;}
101893         break;
101894       case 178: /* itemlist ::= itemlist COMMA expr */
101895       case 241: /* nexprlist ::= nexprlist COMMA expr */ yytestcase(yyruleno==241);
101896 {yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy322,yymsp[0].minor.yy118.pExpr);}
101897         break;
101898       case 179: /* itemlist ::= expr */
101899       case 242: /* nexprlist ::= expr */ yytestcase(yyruleno==242);
101900 {yygotominor.yy322 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy118.pExpr);}
101901         break;
101902       case 182: /* inscollist ::= inscollist COMMA nm */
101903 {yygotominor.yy384 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy384,&yymsp[0].minor.yy0);}
101904         break;
101905       case 183: /* inscollist ::= nm */
101906 {yygotominor.yy384 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
101907         break;
101908       case 184: /* expr ::= term */
101909 {yygotominor.yy118 = yymsp[0].minor.yy118;}
101910         break;
101911       case 185: /* expr ::= LP expr RP */
101912 {yygotominor.yy118.pExpr = yymsp[-1].minor.yy118.pExpr; spanSet(&yygotominor.yy118,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
101913         break;
101914       case 186: /* term ::= NULL */
101915       case 191: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==191);
101916       case 192: /* term ::= STRING */ yytestcase(yyruleno==192);
101917 {spanExpr(&yygotominor.yy118, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
101918         break;
101919       case 187: /* expr ::= id */
101920       case 188: /* expr ::= JOIN_KW */ yytestcase(yyruleno==188);
101921 {spanExpr(&yygotominor.yy118, pParse, TK_ID, &yymsp[0].minor.yy0);}
101922         break;
101923       case 189: /* expr ::= nm DOT nm */
101924 {
101925   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
101926   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
101927   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
101928   spanSet(&yygotominor.yy118,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
101929 }
101930         break;
101931       case 190: /* expr ::= nm DOT nm DOT nm */
101932 {
101933   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
101934   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
101935   Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
101936   Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
101937   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
101938   spanSet(&yygotominor.yy118,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
101939 }
101940         break;
101941       case 193: /* expr ::= REGISTER */
101942 {
101943   /* When doing a nested parse, one can include terms in an expression
101944   ** that look like this:   #1 #2 ...  These terms refer to registers
101945   ** in the virtual machine.  #N is the N-th register. */
101946   if( pParse->nested==0 ){
101947     sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
101948     yygotominor.yy118.pExpr = 0;
101949   }else{
101950     yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
101951     if( yygotominor.yy118.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy118.pExpr->iTable);
101952   }
101953   spanSet(&yygotominor.yy118, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
101954 }
101955         break;
101956       case 194: /* expr ::= VARIABLE */
101957 {
101958   spanExpr(&yygotominor.yy118, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
101959   sqlite3ExprAssignVarNumber(pParse, yygotominor.yy118.pExpr);
101960   spanSet(&yygotominor.yy118, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
101961 }
101962         break;
101963       case 195: /* expr ::= expr COLLATE ids */
101964 {
101965   yygotominor.yy118.pExpr = sqlite3ExprSetCollByToken(pParse, yymsp[-2].minor.yy118.pExpr, &yymsp[0].minor.yy0);
101966   yygotominor.yy118.zStart = yymsp[-2].minor.yy118.zStart;
101967   yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
101968 }
101969         break;
101970       case 196: /* expr ::= CAST LP expr AS typetoken RP */
101971 {
101972   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy118.pExpr, 0, &yymsp[-1].minor.yy0);
101973   spanSet(&yygotominor.yy118,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
101974 }
101975         break;
101976       case 197: /* expr ::= ID LP distinct exprlist RP */
101977 {
101978   if( yymsp[-1].minor.yy322 && yymsp[-1].minor.yy322->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
101979     sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
101980   }
101981   yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy322, &yymsp[-4].minor.yy0);
101982   spanSet(&yygotominor.yy118,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
101983   if( yymsp[-2].minor.yy4 && yygotominor.yy118.pExpr ){
101984     yygotominor.yy118.pExpr->flags |= EP_Distinct;
101985   }
101986 }
101987         break;
101988       case 198: /* expr ::= ID LP STAR RP */
101989 {
101990   yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
101991   spanSet(&yygotominor.yy118,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
101992 }
101993         break;
101994       case 199: /* term ::= CTIME_KW */
101995 {
101996   /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are
101997   ** treated as functions that return constants */
101998   yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, 0,&yymsp[0].minor.yy0);
101999   if( yygotominor.yy118.pExpr ){
102000     yygotominor.yy118.pExpr->op = TK_CONST_FUNC;  
102001   }
102002   spanSet(&yygotominor.yy118, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
102003 }
102004         break;
102005       case 200: /* expr ::= expr AND expr */
102006       case 201: /* expr ::= expr OR expr */ yytestcase(yyruleno==201);
102007       case 202: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==202);
102008       case 203: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==203);
102009       case 204: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==204);
102010       case 205: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==205);
102011       case 206: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==206);
102012       case 207: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==207);
102013 {spanBinaryExpr(&yygotominor.yy118,pParse,yymsp[-1].major,&yymsp[-2].minor.yy118,&yymsp[0].minor.yy118);}
102014         break;
102015       case 208: /* likeop ::= LIKE_KW */
102016       case 210: /* likeop ::= MATCH */ yytestcase(yyruleno==210);
102017 {yygotominor.yy342.eOperator = yymsp[0].minor.yy0; yygotominor.yy342.not = 0;}
102018         break;
102019       case 209: /* likeop ::= NOT LIKE_KW */
102020       case 211: /* likeop ::= NOT MATCH */ yytestcase(yyruleno==211);
102021 {yygotominor.yy342.eOperator = yymsp[0].minor.yy0; yygotominor.yy342.not = 1;}
102022         break;
102023       case 212: /* expr ::= expr likeop expr */
102024 {
102025   ExprList *pList;
102026   pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy118.pExpr);
102027   pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy118.pExpr);
102028   yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy342.eOperator);
102029   if( yymsp[-1].minor.yy342.not ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
102030   yygotominor.yy118.zStart = yymsp[-2].minor.yy118.zStart;
102031   yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd;
102032   if( yygotominor.yy118.pExpr ) yygotominor.yy118.pExpr->flags |= EP_InfixFunc;
102033 }
102034         break;
102035       case 213: /* expr ::= expr likeop expr ESCAPE expr */
102036 {
102037   ExprList *pList;
102038   pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy118.pExpr);
102039   pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy118.pExpr);
102040   pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy118.pExpr);
102041   yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy342.eOperator);
102042   if( yymsp[-3].minor.yy342.not ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
102043   yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
102044   yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd;
102045   if( yygotominor.yy118.pExpr ) yygotominor.yy118.pExpr->flags |= EP_InfixFunc;
102046 }
102047         break;
102048       case 214: /* expr ::= expr ISNULL|NOTNULL */
102049 {spanUnaryPostfix(&yygotominor.yy118,pParse,yymsp[0].major,&yymsp[-1].minor.yy118,&yymsp[0].minor.yy0);}
102050         break;
102051       case 215: /* expr ::= expr NOT NULL */
102052 {spanUnaryPostfix(&yygotominor.yy118,pParse,TK_NOTNULL,&yymsp[-2].minor.yy118,&yymsp[0].minor.yy0);}
102053         break;
102054       case 216: /* expr ::= expr IS expr */
102055 {
102056   spanBinaryExpr(&yygotominor.yy118,pParse,TK_IS,&yymsp[-2].minor.yy118,&yymsp[0].minor.yy118);
102057   binaryToUnaryIfNull(pParse, yymsp[0].minor.yy118.pExpr, yygotominor.yy118.pExpr, TK_ISNULL);
102058 }
102059         break;
102060       case 217: /* expr ::= expr IS NOT expr */
102061 {
102062   spanBinaryExpr(&yygotominor.yy118,pParse,TK_ISNOT,&yymsp[-3].minor.yy118,&yymsp[0].minor.yy118);
102063   binaryToUnaryIfNull(pParse, yymsp[0].minor.yy118.pExpr, yygotominor.yy118.pExpr, TK_NOTNULL);
102064 }
102065         break;
102066       case 218: /* expr ::= NOT expr */
102067       case 219: /* expr ::= BITNOT expr */ yytestcase(yyruleno==219);
102068 {spanUnaryPrefix(&yygotominor.yy118,pParse,yymsp[-1].major,&yymsp[0].minor.yy118,&yymsp[-1].minor.yy0);}
102069         break;
102070       case 220: /* expr ::= MINUS expr */
102071 {spanUnaryPrefix(&yygotominor.yy118,pParse,TK_UMINUS,&yymsp[0].minor.yy118,&yymsp[-1].minor.yy0);}
102072         break;
102073       case 221: /* expr ::= PLUS expr */
102074 {spanUnaryPrefix(&yygotominor.yy118,pParse,TK_UPLUS,&yymsp[0].minor.yy118,&yymsp[-1].minor.yy0);}
102075         break;
102076       case 224: /* expr ::= expr between_op expr AND expr */
102077 {
102078   ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy118.pExpr);
102079   pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy118.pExpr);
102080   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy118.pExpr, 0, 0);
102081   if( yygotominor.yy118.pExpr ){
102082     yygotominor.yy118.pExpr->x.pList = pList;
102083   }else{
102084     sqlite3ExprListDelete(pParse->db, pList);
102085   } 
102086   if( yymsp[-3].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
102087   yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
102088   yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd;
102089 }
102090         break;
102091       case 227: /* expr ::= expr in_op LP exprlist RP */
102092 {
102093     if( yymsp[-1].minor.yy322==0 ){
102094       /* Expressions of the form
102095       **
102096       **      expr1 IN ()
102097       **      expr1 NOT IN ()
102098       **
102099       ** simplify to constants 0 (false) and 1 (true), respectively,
102100       ** regardless of the value of expr1.
102101       */
102102       yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy4]);
102103       sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy118.pExpr);
102104     }else{
102105       yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy118.pExpr, 0, 0);
102106       if( yygotominor.yy118.pExpr ){
102107         yygotominor.yy118.pExpr->x.pList = yymsp[-1].minor.yy322;
102108         sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
102109       }else{
102110         sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy322);
102111       }
102112       if( yymsp[-3].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
102113     }
102114     yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
102115     yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
102116   }
102117         break;
102118       case 228: /* expr ::= LP select RP */
102119 {
102120     yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
102121     if( yygotominor.yy118.pExpr ){
102122       yygotominor.yy118.pExpr->x.pSelect = yymsp[-1].minor.yy387;
102123       ExprSetProperty(yygotominor.yy118.pExpr, EP_xIsSelect);
102124       sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
102125     }else{
102126       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
102127     }
102128     yygotominor.yy118.zStart = yymsp[-2].minor.yy0.z;
102129     yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
102130   }
102131         break;
102132       case 229: /* expr ::= expr in_op LP select RP */
102133 {
102134     yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy118.pExpr, 0, 0);
102135     if( yygotominor.yy118.pExpr ){
102136       yygotominor.yy118.pExpr->x.pSelect = yymsp[-1].minor.yy387;
102137       ExprSetProperty(yygotominor.yy118.pExpr, EP_xIsSelect);
102138       sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
102139     }else{
102140       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
102141     }
102142     if( yymsp[-3].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
102143     yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
102144     yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
102145   }
102146         break;
102147       case 230: /* expr ::= expr in_op nm dbnm */
102148 {
102149     SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
102150     yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy118.pExpr, 0, 0);
102151     if( yygotominor.yy118.pExpr ){
102152       yygotominor.yy118.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
102153       ExprSetProperty(yygotominor.yy118.pExpr, EP_xIsSelect);
102154       sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
102155     }else{
102156       sqlite3SrcListDelete(pParse->db, pSrc);
102157     }
102158     if( yymsp[-2].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
102159     yygotominor.yy118.zStart = yymsp[-3].minor.yy118.zStart;
102160     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];
102161   }
102162         break;
102163       case 231: /* expr ::= EXISTS LP select RP */
102164 {
102165     Expr *p = yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
102166     if( p ){
102167       p->x.pSelect = yymsp[-1].minor.yy387;
102168       ExprSetProperty(p, EP_xIsSelect);
102169       sqlite3ExprSetHeight(pParse, p);
102170     }else{
102171       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
102172     }
102173     yygotominor.yy118.zStart = yymsp[-3].minor.yy0.z;
102174     yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
102175   }
102176         break;
102177       case 232: /* expr ::= CASE case_operand case_exprlist case_else END */
102178 {
102179   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy314, yymsp[-1].minor.yy314, 0);
102180   if( yygotominor.yy118.pExpr ){
102181     yygotominor.yy118.pExpr->x.pList = yymsp[-2].minor.yy322;
102182     sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
102183   }else{
102184     sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy322);
102185   }
102186   yygotominor.yy118.zStart = yymsp[-4].minor.yy0.z;
102187   yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
102188 }
102189         break;
102190       case 233: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
102191 {
102192   yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy322, yymsp[-2].minor.yy118.pExpr);
102193   yygotominor.yy322 = sqlite3ExprListAppend(pParse,yygotominor.yy322, yymsp[0].minor.yy118.pExpr);
102194 }
102195         break;
102196       case 234: /* case_exprlist ::= WHEN expr THEN expr */
102197 {
102198   yygotominor.yy322 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy118.pExpr);
102199   yygotominor.yy322 = sqlite3ExprListAppend(pParse,yygotominor.yy322, yymsp[0].minor.yy118.pExpr);
102200 }
102201         break;
102202       case 243: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP */
102203 {
102204   sqlite3CreateIndex(pParse, &yymsp[-6].minor.yy0, &yymsp[-5].minor.yy0, 
102205                      sqlite3SrcListAppend(pParse->db,0,&yymsp[-3].minor.yy0,0), yymsp[-1].minor.yy322, yymsp[-9].minor.yy4,
102206                       &yymsp[-10].minor.yy0, &yymsp[0].minor.yy0, SQLITE_SO_ASC, yymsp[-7].minor.yy4);
102207 }
102208         break;
102209       case 244: /* uniqueflag ::= UNIQUE */
102210       case 298: /* raisetype ::= ABORT */ yytestcase(yyruleno==298);
102211 {yygotominor.yy4 = OE_Abort;}
102212         break;
102213       case 245: /* uniqueflag ::= */
102214 {yygotominor.yy4 = OE_None;}
102215         break;
102216       case 248: /* idxlist ::= idxlist COMMA nm collate sortorder */
102217 {
102218   Expr *p = 0;
102219   if( yymsp[-1].minor.yy0.n>0 ){
102220     p = sqlite3Expr(pParse->db, TK_COLUMN, 0);
102221     sqlite3ExprSetCollByToken(pParse, p, &yymsp[-1].minor.yy0);
102222   }
102223   yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy322, p);
102224   sqlite3ExprListSetName(pParse,yygotominor.yy322,&yymsp[-2].minor.yy0,1);
102225   sqlite3ExprListCheckLength(pParse, yygotominor.yy322, "index");
102226   if( yygotominor.yy322 ) yygotominor.yy322->a[yygotominor.yy322->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy4;
102227 }
102228         break;
102229       case 249: /* idxlist ::= nm collate sortorder */
102230 {
102231   Expr *p = 0;
102232   if( yymsp[-1].minor.yy0.n>0 ){
102233     p = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
102234     sqlite3ExprSetCollByToken(pParse, p, &yymsp[-1].minor.yy0);
102235   }
102236   yygotominor.yy322 = sqlite3ExprListAppend(pParse,0, p);
102237   sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[-2].minor.yy0, 1);
102238   sqlite3ExprListCheckLength(pParse, yygotominor.yy322, "index");
102239   if( yygotominor.yy322 ) yygotominor.yy322->a[yygotominor.yy322->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy4;
102240 }
102241         break;
102242       case 250: /* collate ::= */
102243 {yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
102244         break;
102245       case 252: /* cmd ::= DROP INDEX ifexists fullname */
102246 {sqlite3DropIndex(pParse, yymsp[0].minor.yy259, yymsp[-1].minor.yy4);}
102247         break;
102248       case 253: /* cmd ::= VACUUM */
102249       case 254: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==254);
102250 {sqlite3Vacuum(pParse);}
102251         break;
102252       case 255: /* cmd ::= PRAGMA nm dbnm */
102253 {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
102254         break;
102255       case 256: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
102256 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
102257         break;
102258       case 257: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
102259 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
102260         break;
102261       case 258: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
102262 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
102263         break;
102264       case 259: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
102265 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
102266         break;
102267       case 270: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
102268 {
102269   Token all;
102270   all.z = yymsp[-3].minor.yy0.z;
102271   all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
102272   sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy203, &all);
102273 }
102274         break;
102275       case 271: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
102276 {
102277   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);
102278   yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
102279 }
102280         break;
102281       case 272: /* trigger_time ::= BEFORE */
102282       case 275: /* trigger_time ::= */ yytestcase(yyruleno==275);
102283 { yygotominor.yy4 = TK_BEFORE; }
102284         break;
102285       case 273: /* trigger_time ::= AFTER */
102286 { yygotominor.yy4 = TK_AFTER;  }
102287         break;
102288       case 274: /* trigger_time ::= INSTEAD OF */
102289 { yygotominor.yy4 = TK_INSTEAD;}
102290         break;
102291       case 276: /* trigger_event ::= DELETE|INSERT */
102292       case 277: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==277);
102293 {yygotominor.yy90.a = yymsp[0].major; yygotominor.yy90.b = 0;}
102294         break;
102295       case 278: /* trigger_event ::= UPDATE OF inscollist */
102296 {yygotominor.yy90.a = TK_UPDATE; yygotominor.yy90.b = yymsp[0].minor.yy384;}
102297         break;
102298       case 281: /* when_clause ::= */
102299       case 303: /* key_opt ::= */ yytestcase(yyruleno==303);
102300 { yygotominor.yy314 = 0; }
102301         break;
102302       case 282: /* when_clause ::= WHEN expr */
102303       case 304: /* key_opt ::= KEY expr */ yytestcase(yyruleno==304);
102304 { yygotominor.yy314 = yymsp[0].minor.yy118.pExpr; }
102305         break;
102306       case 283: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
102307 {
102308   assert( yymsp[-2].minor.yy203!=0 );
102309   yymsp[-2].minor.yy203->pLast->pNext = yymsp[-1].minor.yy203;
102310   yymsp[-2].minor.yy203->pLast = yymsp[-1].minor.yy203;
102311   yygotominor.yy203 = yymsp[-2].minor.yy203;
102312 }
102313         break;
102314       case 284: /* trigger_cmd_list ::= trigger_cmd SEMI */
102315
102316   assert( yymsp[-1].minor.yy203!=0 );
102317   yymsp[-1].minor.yy203->pLast = yymsp[-1].minor.yy203;
102318   yygotominor.yy203 = yymsp[-1].minor.yy203;
102319 }
102320         break;
102321       case 286: /* trnm ::= nm DOT nm */
102322 {
102323   yygotominor.yy0 = yymsp[0].minor.yy0;
102324   sqlite3ErrorMsg(pParse, 
102325         "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
102326         "statements within triggers");
102327 }
102328         break;
102329       case 288: /* tridxby ::= INDEXED BY nm */
102330 {
102331   sqlite3ErrorMsg(pParse,
102332         "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
102333         "within triggers");
102334 }
102335         break;
102336       case 289: /* tridxby ::= NOT INDEXED */
102337 {
102338   sqlite3ErrorMsg(pParse,
102339         "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
102340         "within triggers");
102341 }
102342         break;
102343       case 290: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
102344 { yygotominor.yy203 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy322, yymsp[0].minor.yy314, yymsp[-5].minor.yy210); }
102345         break;
102346       case 291: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt VALUES LP itemlist RP */
102347 {yygotominor.yy203 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy384, yymsp[-1].minor.yy322, 0, yymsp[-7].minor.yy210);}
102348         break;
102349       case 292: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */
102350 {yygotominor.yy203 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy384, 0, yymsp[0].minor.yy387, yymsp[-4].minor.yy210);}
102351         break;
102352       case 293: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
102353 {yygotominor.yy203 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy314);}
102354         break;
102355       case 294: /* trigger_cmd ::= select */
102356 {yygotominor.yy203 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy387); }
102357         break;
102358       case 295: /* expr ::= RAISE LP IGNORE RP */
102359 {
102360   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0); 
102361   if( yygotominor.yy118.pExpr ){
102362     yygotominor.yy118.pExpr->affinity = OE_Ignore;
102363   }
102364   yygotominor.yy118.zStart = yymsp[-3].minor.yy0.z;
102365   yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
102366 }
102367         break;
102368       case 296: /* expr ::= RAISE LP raisetype COMMA nm RP */
102369 {
102370   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0); 
102371   if( yygotominor.yy118.pExpr ) {
102372     yygotominor.yy118.pExpr->affinity = (char)yymsp[-3].minor.yy4;
102373   }
102374   yygotominor.yy118.zStart = yymsp[-5].minor.yy0.z;
102375   yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
102376 }
102377         break;
102378       case 297: /* raisetype ::= ROLLBACK */
102379 {yygotominor.yy4 = OE_Rollback;}
102380         break;
102381       case 299: /* raisetype ::= FAIL */
102382 {yygotominor.yy4 = OE_Fail;}
102383         break;
102384       case 300: /* cmd ::= DROP TRIGGER ifexists fullname */
102385 {
102386   sqlite3DropTrigger(pParse,yymsp[0].minor.yy259,yymsp[-1].minor.yy4);
102387 }
102388         break;
102389       case 301: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
102390 {
102391   sqlite3Attach(pParse, yymsp[-3].minor.yy118.pExpr, yymsp[-1].minor.yy118.pExpr, yymsp[0].minor.yy314);
102392 }
102393         break;
102394       case 302: /* cmd ::= DETACH database_kw_opt expr */
102395 {
102396   sqlite3Detach(pParse, yymsp[0].minor.yy118.pExpr);
102397 }
102398         break;
102399       case 307: /* cmd ::= REINDEX */
102400 {sqlite3Reindex(pParse, 0, 0);}
102401         break;
102402       case 308: /* cmd ::= REINDEX nm dbnm */
102403 {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
102404         break;
102405       case 309: /* cmd ::= ANALYZE */
102406 {sqlite3Analyze(pParse, 0, 0);}
102407         break;
102408       case 310: /* cmd ::= ANALYZE nm dbnm */
102409 {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
102410         break;
102411       case 311: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
102412 {
102413   sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy259,&yymsp[0].minor.yy0);
102414 }
102415         break;
102416       case 312: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
102417 {
102418   sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
102419 }
102420         break;
102421       case 313: /* add_column_fullname ::= fullname */
102422 {
102423   pParse->db->lookaside.bEnabled = 0;
102424   sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy259);
102425 }
102426         break;
102427       case 316: /* cmd ::= create_vtab */
102428 {sqlite3VtabFinishParse(pParse,0);}
102429         break;
102430       case 317: /* cmd ::= create_vtab LP vtabarglist RP */
102431 {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
102432         break;
102433       case 318: /* create_vtab ::= createkw VIRTUAL TABLE nm dbnm USING nm */
102434 {
102435     sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0);
102436 }
102437         break;
102438       case 321: /* vtabarg ::= */
102439 {sqlite3VtabArgInit(pParse);}
102440         break;
102441       case 323: /* vtabargtoken ::= ANY */
102442       case 324: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==324);
102443       case 325: /* lp ::= LP */ yytestcase(yyruleno==325);
102444 {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
102445         break;
102446       default:
102447       /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
102448       /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
102449       /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
102450       /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
102451       /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
102452       /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
102453       /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
102454       /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
102455       /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
102456       /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
102457       /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
102458       /* (34) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==34);
102459       /* (35) columnlist ::= column */ yytestcase(yyruleno==35);
102460       /* (44) type ::= */ yytestcase(yyruleno==44);
102461       /* (51) signed ::= plus_num */ yytestcase(yyruleno==51);
102462       /* (52) signed ::= minus_num */ yytestcase(yyruleno==52);
102463       /* (53) carglist ::= carglist carg */ yytestcase(yyruleno==53);
102464       /* (54) carglist ::= */ yytestcase(yyruleno==54);
102465       /* (55) carg ::= CONSTRAINT nm ccons */ yytestcase(yyruleno==55);
102466       /* (56) carg ::= ccons */ yytestcase(yyruleno==56);
102467       /* (62) ccons ::= NULL onconf */ yytestcase(yyruleno==62);
102468       /* (90) conslist ::= conslist COMMA tcons */ yytestcase(yyruleno==90);
102469       /* (91) conslist ::= conslist tcons */ yytestcase(yyruleno==91);
102470       /* (92) conslist ::= tcons */ yytestcase(yyruleno==92);
102471       /* (93) tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==93);
102472       /* (268) plus_opt ::= PLUS */ yytestcase(yyruleno==268);
102473       /* (269) plus_opt ::= */ yytestcase(yyruleno==269);
102474       /* (279) foreach_clause ::= */ yytestcase(yyruleno==279);
102475       /* (280) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==280);
102476       /* (287) tridxby ::= */ yytestcase(yyruleno==287);
102477       /* (305) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==305);
102478       /* (306) database_kw_opt ::= */ yytestcase(yyruleno==306);
102479       /* (314) kwcolumn_opt ::= */ yytestcase(yyruleno==314);
102480       /* (315) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==315);
102481       /* (319) vtabarglist ::= vtabarg */ yytestcase(yyruleno==319);
102482       /* (320) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==320);
102483       /* (322) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==322);
102484       /* (326) anylist ::= */ yytestcase(yyruleno==326);
102485       /* (327) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==327);
102486       /* (328) anylist ::= anylist ANY */ yytestcase(yyruleno==328);
102487         break;
102488   };
102489   yygoto = yyRuleInfo[yyruleno].lhs;
102490   yysize = yyRuleInfo[yyruleno].nrhs;
102491   yypParser->yyidx -= yysize;
102492   yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
102493   if( yyact < YYNSTATE ){
102494 #ifdef NDEBUG
102495     /* If we are not debugging and the reduce action popped at least
102496     ** one element off the stack, then we can push the new element back
102497     ** onto the stack here, and skip the stack overflow test in yy_shift().
102498     ** That gives a significant speed improvement. */
102499     if( yysize ){
102500       yypParser->yyidx++;
102501       yymsp -= yysize-1;
102502       yymsp->stateno = (YYACTIONTYPE)yyact;
102503       yymsp->major = (YYCODETYPE)yygoto;
102504       yymsp->minor = yygotominor;
102505     }else
102506 #endif
102507     {
102508       yy_shift(yypParser,yyact,yygoto,&yygotominor);
102509     }
102510   }else{
102511     assert( yyact == YYNSTATE + YYNRULE + 1 );
102512     yy_accept(yypParser);
102513   }
102514 }
102515
102516 /*
102517 ** The following code executes when the parse fails
102518 */
102519 #ifndef YYNOERRORRECOVERY
102520 static void yy_parse_failed(
102521   yyParser *yypParser           /* The parser */
102522 ){
102523   sqlite3ParserARG_FETCH;
102524 #ifndef NDEBUG
102525   if( yyTraceFILE ){
102526     fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
102527   }
102528 #endif
102529   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
102530   /* Here code is inserted which will be executed whenever the
102531   ** parser fails */
102532   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
102533 }
102534 #endif /* YYNOERRORRECOVERY */
102535
102536 /*
102537 ** The following code executes when a syntax error first occurs.
102538 */
102539 static void yy_syntax_error(
102540   yyParser *yypParser,           /* The parser */
102541   int yymajor,                   /* The major type of the error token */
102542   YYMINORTYPE yyminor            /* The minor type of the error token */
102543 ){
102544   sqlite3ParserARG_FETCH;
102545 #define TOKEN (yyminor.yy0)
102546
102547   UNUSED_PARAMETER(yymajor);  /* Silence some compiler warnings */
102548   assert( TOKEN.z[0] );  /* The tokenizer always gives us a token */
102549   sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
102550   pParse->parseError = 1;
102551   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
102552 }
102553
102554 /*
102555 ** The following is executed when the parser accepts
102556 */
102557 static void yy_accept(
102558   yyParser *yypParser           /* The parser */
102559 ){
102560   sqlite3ParserARG_FETCH;
102561 #ifndef NDEBUG
102562   if( yyTraceFILE ){
102563     fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
102564   }
102565 #endif
102566   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
102567   /* Here code is inserted which will be executed whenever the
102568   ** parser accepts */
102569   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
102570 }
102571
102572 /* The main parser program.
102573 ** The first argument is a pointer to a structure obtained from
102574 ** "sqlite3ParserAlloc" which describes the current state of the parser.
102575 ** The second argument is the major token number.  The third is
102576 ** the minor token.  The fourth optional argument is whatever the
102577 ** user wants (and specified in the grammar) and is available for
102578 ** use by the action routines.
102579 **
102580 ** Inputs:
102581 ** <ul>
102582 ** <li> A pointer to the parser (an opaque structure.)
102583 ** <li> The major token number.
102584 ** <li> The minor token number.
102585 ** <li> An option argument of a grammar-specified type.
102586 ** </ul>
102587 **
102588 ** Outputs:
102589 ** None.
102590 */
102591 SQLITE_PRIVATE void sqlite3Parser(
102592   void *yyp,                   /* The parser */
102593   int yymajor,                 /* The major token code number */
102594   sqlite3ParserTOKENTYPE yyminor       /* The value for the token */
102595   sqlite3ParserARG_PDECL               /* Optional %extra_argument parameter */
102596 ){
102597   YYMINORTYPE yyminorunion;
102598   int yyact;            /* The parser action. */
102599   int yyendofinput;     /* True if we are at the end of input */
102600 #ifdef YYERRORSYMBOL
102601   int yyerrorhit = 0;   /* True if yymajor has invoked an error */
102602 #endif
102603   yyParser *yypParser;  /* The parser */
102604
102605   /* (re)initialize the parser, if necessary */
102606   yypParser = (yyParser*)yyp;
102607   if( yypParser->yyidx<0 ){
102608 #if YYSTACKDEPTH<=0
102609     if( yypParser->yystksz <=0 ){
102610       /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
102611       yyminorunion = yyzerominor;
102612       yyStackOverflow(yypParser, &yyminorunion);
102613       return;
102614     }
102615 #endif
102616     yypParser->yyidx = 0;
102617     yypParser->yyerrcnt = -1;
102618     yypParser->yystack[0].stateno = 0;
102619     yypParser->yystack[0].major = 0;
102620   }
102621   yyminorunion.yy0 = yyminor;
102622   yyendofinput = (yymajor==0);
102623   sqlite3ParserARG_STORE;
102624
102625 #ifndef NDEBUG
102626   if( yyTraceFILE ){
102627     fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
102628   }
102629 #endif
102630
102631   do{
102632     yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
102633     if( yyact<YYNSTATE ){
102634       assert( !yyendofinput );  /* Impossible to shift the $ token */
102635       yy_shift(yypParser,yyact,yymajor,&yyminorunion);
102636       yypParser->yyerrcnt--;
102637       yymajor = YYNOCODE;
102638     }else if( yyact < YYNSTATE + YYNRULE ){
102639       yy_reduce(yypParser,yyact-YYNSTATE);
102640     }else{
102641       assert( yyact == YY_ERROR_ACTION );
102642 #ifdef YYERRORSYMBOL
102643       int yymx;
102644 #endif
102645 #ifndef NDEBUG
102646       if( yyTraceFILE ){
102647         fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
102648       }
102649 #endif
102650 #ifdef YYERRORSYMBOL
102651       /* A syntax error has occurred.
102652       ** The response to an error depends upon whether or not the
102653       ** grammar defines an error token "ERROR".  
102654       **
102655       ** This is what we do if the grammar does define ERROR:
102656       **
102657       **  * Call the %syntax_error function.
102658       **
102659       **  * Begin popping the stack until we enter a state where
102660       **    it is legal to shift the error symbol, then shift
102661       **    the error symbol.
102662       **
102663       **  * Set the error count to three.
102664       **
102665       **  * Begin accepting and shifting new tokens.  No new error
102666       **    processing will occur until three tokens have been
102667       **    shifted successfully.
102668       **
102669       */
102670       if( yypParser->yyerrcnt<0 ){
102671         yy_syntax_error(yypParser,yymajor,yyminorunion);
102672       }
102673       yymx = yypParser->yystack[yypParser->yyidx].major;
102674       if( yymx==YYERRORSYMBOL || yyerrorhit ){
102675 #ifndef NDEBUG
102676         if( yyTraceFILE ){
102677           fprintf(yyTraceFILE,"%sDiscard input token %s\n",
102678              yyTracePrompt,yyTokenName[yymajor]);
102679         }
102680 #endif
102681         yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
102682         yymajor = YYNOCODE;
102683       }else{
102684          while(
102685           yypParser->yyidx >= 0 &&
102686           yymx != YYERRORSYMBOL &&
102687           (yyact = yy_find_reduce_action(
102688                         yypParser->yystack[yypParser->yyidx].stateno,
102689                         YYERRORSYMBOL)) >= YYNSTATE
102690         ){
102691           yy_pop_parser_stack(yypParser);
102692         }
102693         if( yypParser->yyidx < 0 || yymajor==0 ){
102694           yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
102695           yy_parse_failed(yypParser);
102696           yymajor = YYNOCODE;
102697         }else if( yymx!=YYERRORSYMBOL ){
102698           YYMINORTYPE u2;
102699           u2.YYERRSYMDT = 0;
102700           yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
102701         }
102702       }
102703       yypParser->yyerrcnt = 3;
102704       yyerrorhit = 1;
102705 #elif defined(YYNOERRORRECOVERY)
102706       /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
102707       ** do any kind of error recovery.  Instead, simply invoke the syntax
102708       ** error routine and continue going as if nothing had happened.
102709       **
102710       ** Applications can set this macro (for example inside %include) if
102711       ** they intend to abandon the parse upon the first syntax error seen.
102712       */
102713       yy_syntax_error(yypParser,yymajor,yyminorunion);
102714       yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
102715       yymajor = YYNOCODE;
102716       
102717 #else  /* YYERRORSYMBOL is not defined */
102718       /* This is what we do if the grammar does not define ERROR:
102719       **
102720       **  * Report an error message, and throw away the input token.
102721       **
102722       **  * If the input token is $, then fail the parse.
102723       **
102724       ** As before, subsequent error messages are suppressed until
102725       ** three input tokens have been successfully shifted.
102726       */
102727       if( yypParser->yyerrcnt<=0 ){
102728         yy_syntax_error(yypParser,yymajor,yyminorunion);
102729       }
102730       yypParser->yyerrcnt = 3;
102731       yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
102732       if( yyendofinput ){
102733         yy_parse_failed(yypParser);
102734       }
102735       yymajor = YYNOCODE;
102736 #endif
102737     }
102738   }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
102739   return;
102740 }
102741
102742 /************** End of parse.c ***********************************************/
102743 /************** Begin file tokenize.c ****************************************/
102744 /*
102745 ** 2001 September 15
102746 **
102747 ** The author disclaims copyright to this source code.  In place of
102748 ** a legal notice, here is a blessing:
102749 **
102750 **    May you do good and not evil.
102751 **    May you find forgiveness for yourself and forgive others.
102752 **    May you share freely, never taking more than you give.
102753 **
102754 *************************************************************************
102755 ** An tokenizer for SQL
102756 **
102757 ** This file contains C code that splits an SQL input string up into
102758 ** individual tokens and sends those tokens one-by-one over to the
102759 ** parser for analysis.
102760 */
102761
102762 /*
102763 ** The charMap() macro maps alphabetic characters into their
102764 ** lower-case ASCII equivalent.  On ASCII machines, this is just
102765 ** an upper-to-lower case map.  On EBCDIC machines we also need
102766 ** to adjust the encoding.  Only alphabetic characters and underscores
102767 ** need to be translated.
102768 */
102769 #ifdef SQLITE_ASCII
102770 # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
102771 #endif
102772 #ifdef SQLITE_EBCDIC
102773 # define charMap(X) ebcdicToAscii[(unsigned char)X]
102774 const unsigned char ebcdicToAscii[] = {
102775 /* 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F */
102776    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 0x */
102777    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 1x */
102778    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 2x */
102779    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 3x */
102780    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 4x */
102781    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 5x */
102782    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 95,  0,  0,  /* 6x */
102783    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 7x */
102784    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* 8x */
102785    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* 9x */
102786    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ax */
102787    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Bx */
102788    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* Cx */
102789    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* Dx */
102790    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ex */
102791    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Fx */
102792 };
102793 #endif
102794
102795 /*
102796 ** The sqlite3KeywordCode function looks up an identifier to determine if
102797 ** it is a keyword.  If it is a keyword, the token code of that keyword is 
102798 ** returned.  If the input is not a keyword, TK_ID is returned.
102799 **
102800 ** The implementation of this routine was generated by a program,
102801 ** mkkeywordhash.h, located in the tool subdirectory of the distribution.
102802 ** The output of the mkkeywordhash.c program is written into a file
102803 ** named keywordhash.h and then included into this source file by
102804 ** the #include below.
102805 */
102806 /************** Include keywordhash.h in the middle of tokenize.c ************/
102807 /************** Begin file keywordhash.h *************************************/
102808 /***** This file contains automatically generated code ******
102809 **
102810 ** The code in this file has been automatically generated by
102811 **
102812 **   sqlite/tool/mkkeywordhash.c
102813 **
102814 ** The code in this file implements a function that determines whether
102815 ** or not a given identifier is really an SQL keyword.  The same thing
102816 ** might be implemented more directly using a hand-written hash table.
102817 ** But by using this automatically generated code, the size of the code
102818 ** is substantially reduced.  This is important for embedded applications
102819 ** on platforms with limited memory.
102820 */
102821 /* Hash score: 175 */
102822 static int keywordCode(const char *z, int n){
102823   /* zText[] encodes 811 bytes of keywords in 541 bytes */
102824   /*   REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT       */
102825   /*   ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE         */
102826   /*   XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY         */
102827   /*   UNIQUERYATTACHAVINGROUPDATEBEGINNERELEASEBETWEENOTNULLIKE          */
102828   /*   CASCADELETECASECOLLATECREATECURRENT_DATEDETACHIMMEDIATEJOIN        */
102829   /*   SERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHENWHERENAME         */
102830   /*   AFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSS     */
102831   /*   CURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOBYIF      */
102832   /*   ISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUMVIEW         */
102833   /*   INITIALLY                                                          */
102834   static const char zText[540] = {
102835     'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
102836     'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
102837     'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
102838     'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
102839     'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
102840     'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
102841     'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
102842     'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
102843     'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
102844     'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
102845     'U','E','R','Y','A','T','T','A','C','H','A','V','I','N','G','R','O','U',
102846     'P','D','A','T','E','B','E','G','I','N','N','E','R','E','L','E','A','S',
102847     'E','B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C',
102848     'A','S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L',
102849     'A','T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D',
102850     'A','T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E',
102851     'J','O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A',
102852     'L','Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U',
102853     'E','S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W',
102854     'H','E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C',
102855     'E','A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R',
102856     'E','M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M',
102857     'M','I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U',
102858     'R','R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M',
102859     'A','R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T',
102860     'D','R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L',
102861     'O','B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S',
102862     'T','R','I','C','T','O','U','T','E','R','I','G','H','T','R','O','L','L',
102863     'B','A','C','K','R','O','W','U','N','I','O','N','U','S','I','N','G','V',
102864     'A','C','U','U','M','V','I','E','W','I','N','I','T','I','A','L','L','Y',
102865   };
102866   static const unsigned char aHash[127] = {
102867       72, 101, 114,  70,   0,  45,   0,   0,  78,   0,  73,   0,   0,
102868       42,  12,  74,  15,   0, 113,  81,  50, 108,   0,  19,   0,   0,
102869      118,   0, 116, 111,   0,  22,  89,   0,   9,   0,   0,  66,  67,
102870        0,  65,   6,   0,  48,  86,  98,   0, 115,  97,   0,   0,  44,
102871        0,  99,  24,   0,  17,   0, 119,  49,  23,   0,   5, 106,  25,
102872       92,   0,   0, 121, 102,  56, 120,  53,  28,  51,   0,  87,   0,
102873       96,  26,   0,  95,   0,   0,   0,  91,  88,  93,  84, 105,  14,
102874       39, 104,   0,  77,   0,  18,  85, 107,  32,   0, 117,  76, 109,
102875       58,  46,  80,   0,   0,  90,  40,   0, 112,   0,  36,   0,   0,
102876       29,   0,  82,  59,  60,   0,  20,  57,   0,  52,
102877   };
102878   static const unsigned char aNext[121] = {
102879        0,   0,   0,   0,   4,   0,   0,   0,   0,   0,   0,   0,   0,
102880        0,   2,   0,   0,   0,   0,   0,   0,  13,   0,   0,   0,   0,
102881        0,   7,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,
102882        0,   0,   0,   0,  33,   0,  21,   0,   0,   0,  43,   3,  47,
102883        0,   0,   0,   0,  30,   0,  54,   0,  38,   0,   0,   0,   1,
102884       62,   0,   0,  63,   0,  41,   0,   0,   0,   0,   0,   0,   0,
102885       61,   0,   0,   0,   0,  31,  55,  16,  34,  10,   0,   0,   0,
102886        0,   0,   0,   0,  11,  68,  75,   0,   8,   0, 100,  94,   0,
102887      103,   0,  83,   0,  71,   0,   0, 110,  27,  37,  69,  79,   0,
102888       35,  64,   0,   0,
102889   };
102890   static const unsigned char aLen[121] = {
102891        7,   7,   5,   4,   6,   4,   5,   3,   6,   7,   3,   6,   6,
102892        7,   7,   3,   8,   2,   6,   5,   4,   4,   3,  10,   4,   6,
102893       11,   6,   2,   7,   5,   5,   9,   6,   9,   9,   7,  10,  10,
102894        4,   6,   2,   3,   9,   4,   2,   6,   5,   6,   6,   5,   6,
102895        5,   5,   7,   7,   7,   3,   2,   4,   4,   7,   3,   6,   4,
102896        7,   6,  12,   6,   9,   4,   6,   5,   4,   7,   6,   5,   6,
102897        7,   5,   4,   5,   6,   5,   7,   3,   7,  13,   2,   2,   4,
102898        6,   6,   8,   5,  17,  12,   7,   8,   8,   2,   4,   4,   4,
102899        4,   4,   2,   2,   6,   5,   8,   5,   5,   8,   3,   5,   5,
102900        6,   4,   9,   3,
102901   };
102902   static const unsigned short int aOffset[121] = {
102903        0,   2,   2,   8,   9,  14,  16,  20,  23,  25,  25,  29,  33,
102904       36,  41,  46,  48,  53,  54,  59,  62,  65,  67,  69,  78,  81,
102905       86,  91,  95,  96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
102906      159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 189, 194, 197,
102907      203, 206, 210, 217, 223, 223, 223, 226, 229, 233, 234, 238, 244,
102908      248, 255, 261, 273, 279, 288, 290, 296, 301, 303, 310, 315, 320,
102909      326, 332, 337, 341, 344, 350, 354, 361, 363, 370, 372, 374, 383,
102910      387, 393, 399, 407, 412, 412, 428, 435, 442, 443, 450, 454, 458,
102911      462, 466, 469, 471, 473, 479, 483, 491, 495, 500, 508, 511, 516,
102912      521, 527, 531, 536,
102913   };
102914   static const unsigned char aCode[121] = {
102915     TK_REINDEX,    TK_INDEXED,    TK_INDEX,      TK_DESC,       TK_ESCAPE,     
102916     TK_EACH,       TK_CHECK,      TK_KEY,        TK_BEFORE,     TK_FOREIGN,    
102917     TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    TK_EXPLAIN,    TK_INSTEAD,    
102918     TK_ADD,        TK_DATABASE,   TK_AS,         TK_SELECT,     TK_TABLE,      
102919     TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DEFERRABLE, TK_ELSE,       
102920     TK_EXCEPT,     TK_TRANSACTION,TK_ACTION,     TK_ON,         TK_JOIN_KW,    
102921     TK_ALTER,      TK_RAISE,      TK_EXCLUSIVE,  TK_EXISTS,     TK_SAVEPOINT,  
102922     TK_INTERSECT,  TK_TRIGGER,    TK_REFERENCES, TK_CONSTRAINT, TK_INTO,       
102923     TK_OFFSET,     TK_OF,         TK_SET,        TK_TEMP,       TK_TEMP,       
102924     TK_OR,         TK_UNIQUE,     TK_QUERY,      TK_ATTACH,     TK_HAVING,     
102925     TK_GROUP,      TK_UPDATE,     TK_BEGIN,      TK_JOIN_KW,    TK_RELEASE,    
102926     TK_BETWEEN,    TK_NOTNULL,    TK_NOT,        TK_NO,         TK_NULL,       
102927     TK_LIKE_KW,    TK_CASCADE,    TK_ASC,        TK_DELETE,     TK_CASE,       
102928     TK_COLLATE,    TK_CREATE,     TK_CTIME_KW,   TK_DETACH,     TK_IMMEDIATE,  
102929     TK_JOIN,       TK_INSERT,     TK_MATCH,      TK_PLAN,       TK_ANALYZE,    
102930     TK_PRAGMA,     TK_ABORT,      TK_VALUES,     TK_VIRTUAL,    TK_LIMIT,      
102931     TK_WHEN,       TK_WHERE,      TK_RENAME,     TK_AFTER,      TK_REPLACE,    
102932     TK_AND,        TK_DEFAULT,    TK_AUTOINCR,   TK_TO,         TK_IN,         
102933     TK_CAST,       TK_COLUMNKW,   TK_COMMIT,     TK_CONFLICT,   TK_JOIN_KW,    
102934     TK_CTIME_KW,   TK_CTIME_KW,   TK_PRIMARY,    TK_DEFERRED,   TK_DISTINCT,   
102935     TK_IS,         TK_DROP,       TK_FAIL,       TK_FROM,       TK_JOIN_KW,    
102936     TK_LIKE_KW,    TK_BY,         TK_IF,         TK_ISNULL,     TK_ORDER,      
102937     TK_RESTRICT,   TK_JOIN_KW,    TK_JOIN_KW,    TK_ROLLBACK,   TK_ROW,        
102938     TK_UNION,      TK_USING,      TK_VACUUM,     TK_VIEW,       TK_INITIALLY,  
102939     TK_ALL,        
102940   };
102941   int h, i;
102942   if( n<2 ) return TK_ID;
102943   h = ((charMap(z[0])*4) ^
102944       (charMap(z[n-1])*3) ^
102945       n) % 127;
102946   for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
102947     if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
102948       testcase( i==0 ); /* REINDEX */
102949       testcase( i==1 ); /* INDEXED */
102950       testcase( i==2 ); /* INDEX */
102951       testcase( i==3 ); /* DESC */
102952       testcase( i==4 ); /* ESCAPE */
102953       testcase( i==5 ); /* EACH */
102954       testcase( i==6 ); /* CHECK */
102955       testcase( i==7 ); /* KEY */
102956       testcase( i==8 ); /* BEFORE */
102957       testcase( i==9 ); /* FOREIGN */
102958       testcase( i==10 ); /* FOR */
102959       testcase( i==11 ); /* IGNORE */
102960       testcase( i==12 ); /* REGEXP */
102961       testcase( i==13 ); /* EXPLAIN */
102962       testcase( i==14 ); /* INSTEAD */
102963       testcase( i==15 ); /* ADD */
102964       testcase( i==16 ); /* DATABASE */
102965       testcase( i==17 ); /* AS */
102966       testcase( i==18 ); /* SELECT */
102967       testcase( i==19 ); /* TABLE */
102968       testcase( i==20 ); /* LEFT */
102969       testcase( i==21 ); /* THEN */
102970       testcase( i==22 ); /* END */
102971       testcase( i==23 ); /* DEFERRABLE */
102972       testcase( i==24 ); /* ELSE */
102973       testcase( i==25 ); /* EXCEPT */
102974       testcase( i==26 ); /* TRANSACTION */
102975       testcase( i==27 ); /* ACTION */
102976       testcase( i==28 ); /* ON */
102977       testcase( i==29 ); /* NATURAL */
102978       testcase( i==30 ); /* ALTER */
102979       testcase( i==31 ); /* RAISE */
102980       testcase( i==32 ); /* EXCLUSIVE */
102981       testcase( i==33 ); /* EXISTS */
102982       testcase( i==34 ); /* SAVEPOINT */
102983       testcase( i==35 ); /* INTERSECT */
102984       testcase( i==36 ); /* TRIGGER */
102985       testcase( i==37 ); /* REFERENCES */
102986       testcase( i==38 ); /* CONSTRAINT */
102987       testcase( i==39 ); /* INTO */
102988       testcase( i==40 ); /* OFFSET */
102989       testcase( i==41 ); /* OF */
102990       testcase( i==42 ); /* SET */
102991       testcase( i==43 ); /* TEMPORARY */
102992       testcase( i==44 ); /* TEMP */
102993       testcase( i==45 ); /* OR */
102994       testcase( i==46 ); /* UNIQUE */
102995       testcase( i==47 ); /* QUERY */
102996       testcase( i==48 ); /* ATTACH */
102997       testcase( i==49 ); /* HAVING */
102998       testcase( i==50 ); /* GROUP */
102999       testcase( i==51 ); /* UPDATE */
103000       testcase( i==52 ); /* BEGIN */
103001       testcase( i==53 ); /* INNER */
103002       testcase( i==54 ); /* RELEASE */
103003       testcase( i==55 ); /* BETWEEN */
103004       testcase( i==56 ); /* NOTNULL */
103005       testcase( i==57 ); /* NOT */
103006       testcase( i==58 ); /* NO */
103007       testcase( i==59 ); /* NULL */
103008       testcase( i==60 ); /* LIKE */
103009       testcase( i==61 ); /* CASCADE */
103010       testcase( i==62 ); /* ASC */
103011       testcase( i==63 ); /* DELETE */
103012       testcase( i==64 ); /* CASE */
103013       testcase( i==65 ); /* COLLATE */
103014       testcase( i==66 ); /* CREATE */
103015       testcase( i==67 ); /* CURRENT_DATE */
103016       testcase( i==68 ); /* DETACH */
103017       testcase( i==69 ); /* IMMEDIATE */
103018       testcase( i==70 ); /* JOIN */
103019       testcase( i==71 ); /* INSERT */
103020       testcase( i==72 ); /* MATCH */
103021       testcase( i==73 ); /* PLAN */
103022       testcase( i==74 ); /* ANALYZE */
103023       testcase( i==75 ); /* PRAGMA */
103024       testcase( i==76 ); /* ABORT */
103025       testcase( i==77 ); /* VALUES */
103026       testcase( i==78 ); /* VIRTUAL */
103027       testcase( i==79 ); /* LIMIT */
103028       testcase( i==80 ); /* WHEN */
103029       testcase( i==81 ); /* WHERE */
103030       testcase( i==82 ); /* RENAME */
103031       testcase( i==83 ); /* AFTER */
103032       testcase( i==84 ); /* REPLACE */
103033       testcase( i==85 ); /* AND */
103034       testcase( i==86 ); /* DEFAULT */
103035       testcase( i==87 ); /* AUTOINCREMENT */
103036       testcase( i==88 ); /* TO */
103037       testcase( i==89 ); /* IN */
103038       testcase( i==90 ); /* CAST */
103039       testcase( i==91 ); /* COLUMN */
103040       testcase( i==92 ); /* COMMIT */
103041       testcase( i==93 ); /* CONFLICT */
103042       testcase( i==94 ); /* CROSS */
103043       testcase( i==95 ); /* CURRENT_TIMESTAMP */
103044       testcase( i==96 ); /* CURRENT_TIME */
103045       testcase( i==97 ); /* PRIMARY */
103046       testcase( i==98 ); /* DEFERRED */
103047       testcase( i==99 ); /* DISTINCT */
103048       testcase( i==100 ); /* IS */
103049       testcase( i==101 ); /* DROP */
103050       testcase( i==102 ); /* FAIL */
103051       testcase( i==103 ); /* FROM */
103052       testcase( i==104 ); /* FULL */
103053       testcase( i==105 ); /* GLOB */
103054       testcase( i==106 ); /* BY */
103055       testcase( i==107 ); /* IF */
103056       testcase( i==108 ); /* ISNULL */
103057       testcase( i==109 ); /* ORDER */
103058       testcase( i==110 ); /* RESTRICT */
103059       testcase( i==111 ); /* OUTER */
103060       testcase( i==112 ); /* RIGHT */
103061       testcase( i==113 ); /* ROLLBACK */
103062       testcase( i==114 ); /* ROW */
103063       testcase( i==115 ); /* UNION */
103064       testcase( i==116 ); /* USING */
103065       testcase( i==117 ); /* VACUUM */
103066       testcase( i==118 ); /* VIEW */
103067       testcase( i==119 ); /* INITIALLY */
103068       testcase( i==120 ); /* ALL */
103069       return aCode[i];
103070     }
103071   }
103072   return TK_ID;
103073 }
103074 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
103075   return keywordCode((char*)z, n);
103076 }
103077 #define SQLITE_N_KEYWORD 121
103078
103079 /************** End of keywordhash.h *****************************************/
103080 /************** Continuing where we left off in tokenize.c *******************/
103081
103082
103083 /*
103084 ** If X is a character that can be used in an identifier then
103085 ** IdChar(X) will be true.  Otherwise it is false.
103086 **
103087 ** For ASCII, any character with the high-order bit set is
103088 ** allowed in an identifier.  For 7-bit characters, 
103089 ** sqlite3IsIdChar[X] must be 1.
103090 **
103091 ** For EBCDIC, the rules are more complex but have the same
103092 ** end result.
103093 **
103094 ** Ticket #1066.  the SQL standard does not allow '$' in the
103095 ** middle of identfiers.  But many SQL implementations do. 
103096 ** SQLite will allow '$' in identifiers for compatibility.
103097 ** But the feature is undocumented.
103098 */
103099 #ifdef SQLITE_ASCII
103100 #define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
103101 #endif
103102 #ifdef SQLITE_EBCDIC
103103 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
103104 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
103105     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 4x */
103106     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0,  /* 5x */
103107     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,  /* 6x */
103108     0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,  /* 7x */
103109     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0,  /* 8x */
103110     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,  /* 9x */
103111     1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0,  /* Ax */
103112     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* Bx */
103113     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Cx */
103114     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Dx */
103115     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Ex */
103116     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0,  /* Fx */
103117 };
103118 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
103119 #endif
103120
103121
103122 /*
103123 ** Return the length of the token that begins at z[0]. 
103124 ** Store the token type in *tokenType before returning.
103125 */
103126 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
103127   int i, c;
103128   switch( *z ){
103129     case ' ': case '\t': case '\n': case '\f': case '\r': {
103130       testcase( z[0]==' ' );
103131       testcase( z[0]=='\t' );
103132       testcase( z[0]=='\n' );
103133       testcase( z[0]=='\f' );
103134       testcase( z[0]=='\r' );
103135       for(i=1; sqlite3Isspace(z[i]); i++){}
103136       *tokenType = TK_SPACE;
103137       return i;
103138     }
103139     case '-': {
103140       if( z[1]=='-' ){
103141         /* IMP: R-15891-05542 -- syntax diagram for comments */
103142         for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
103143         *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
103144         return i;
103145       }
103146       *tokenType = TK_MINUS;
103147       return 1;
103148     }
103149     case '(': {
103150       *tokenType = TK_LP;
103151       return 1;
103152     }
103153     case ')': {
103154       *tokenType = TK_RP;
103155       return 1;
103156     }
103157     case ';': {
103158       *tokenType = TK_SEMI;
103159       return 1;
103160     }
103161     case '+': {
103162       *tokenType = TK_PLUS;
103163       return 1;
103164     }
103165     case '*': {
103166       *tokenType = TK_STAR;
103167       return 1;
103168     }
103169     case '/': {
103170       if( z[1]!='*' || z[2]==0 ){
103171         *tokenType = TK_SLASH;
103172         return 1;
103173       }
103174       /* IMP: R-15891-05542 -- syntax diagram for comments */
103175       for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
103176       if( c ) i++;
103177       *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
103178       return i;
103179     }
103180     case '%': {
103181       *tokenType = TK_REM;
103182       return 1;
103183     }
103184     case '=': {
103185       *tokenType = TK_EQ;
103186       return 1 + (z[1]=='=');
103187     }
103188     case '<': {
103189       if( (c=z[1])=='=' ){
103190         *tokenType = TK_LE;
103191         return 2;
103192       }else if( c=='>' ){
103193         *tokenType = TK_NE;
103194         return 2;
103195       }else if( c=='<' ){
103196         *tokenType = TK_LSHIFT;
103197         return 2;
103198       }else{
103199         *tokenType = TK_LT;
103200         return 1;
103201       }
103202     }
103203     case '>': {
103204       if( (c=z[1])=='=' ){
103205         *tokenType = TK_GE;
103206         return 2;
103207       }else if( c=='>' ){
103208         *tokenType = TK_RSHIFT;
103209         return 2;
103210       }else{
103211         *tokenType = TK_GT;
103212         return 1;
103213       }
103214     }
103215     case '!': {
103216       if( z[1]!='=' ){
103217         *tokenType = TK_ILLEGAL;
103218         return 2;
103219       }else{
103220         *tokenType = TK_NE;
103221         return 2;
103222       }
103223     }
103224     case '|': {
103225       if( z[1]!='|' ){
103226         *tokenType = TK_BITOR;
103227         return 1;
103228       }else{
103229         *tokenType = TK_CONCAT;
103230         return 2;
103231       }
103232     }
103233     case ',': {
103234       *tokenType = TK_COMMA;
103235       return 1;
103236     }
103237     case '&': {
103238       *tokenType = TK_BITAND;
103239       return 1;
103240     }
103241     case '~': {
103242       *tokenType = TK_BITNOT;
103243       return 1;
103244     }
103245     case '`':
103246     case '\'':
103247     case '"': {
103248       int delim = z[0];
103249       testcase( delim=='`' );
103250       testcase( delim=='\'' );
103251       testcase( delim=='"' );
103252       for(i=1; (c=z[i])!=0; i++){
103253         if( c==delim ){
103254           if( z[i+1]==delim ){
103255             i++;
103256           }else{
103257             break;
103258           }
103259         }
103260       }
103261       if( c=='\'' ){
103262         *tokenType = TK_STRING;
103263         return i+1;
103264       }else if( c!=0 ){
103265         *tokenType = TK_ID;
103266         return i+1;
103267       }else{
103268         *tokenType = TK_ILLEGAL;
103269         return i;
103270       }
103271     }
103272     case '.': {
103273 #ifndef SQLITE_OMIT_FLOATING_POINT
103274       if( !sqlite3Isdigit(z[1]) )
103275 #endif
103276       {
103277         *tokenType = TK_DOT;
103278         return 1;
103279       }
103280       /* If the next character is a digit, this is a floating point
103281       ** number that begins with ".".  Fall thru into the next case */
103282     }
103283     case '0': case '1': case '2': case '3': case '4':
103284     case '5': case '6': case '7': case '8': case '9': {
103285       testcase( z[0]=='0' );  testcase( z[0]=='1' );  testcase( z[0]=='2' );
103286       testcase( z[0]=='3' );  testcase( z[0]=='4' );  testcase( z[0]=='5' );
103287       testcase( z[0]=='6' );  testcase( z[0]=='7' );  testcase( z[0]=='8' );
103288       testcase( z[0]=='9' );
103289       *tokenType = TK_INTEGER;
103290       for(i=0; sqlite3Isdigit(z[i]); i++){}
103291 #ifndef SQLITE_OMIT_FLOATING_POINT
103292       if( z[i]=='.' ){
103293         i++;
103294         while( sqlite3Isdigit(z[i]) ){ i++; }
103295         *tokenType = TK_FLOAT;
103296       }
103297       if( (z[i]=='e' || z[i]=='E') &&
103298            ( sqlite3Isdigit(z[i+1]) 
103299             || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
103300            )
103301       ){
103302         i += 2;
103303         while( sqlite3Isdigit(z[i]) ){ i++; }
103304         *tokenType = TK_FLOAT;
103305       }
103306 #endif
103307       while( IdChar(z[i]) ){
103308         *tokenType = TK_ILLEGAL;
103309         i++;
103310       }
103311       return i;
103312     }
103313     case '[': {
103314       for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
103315       *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
103316       return i;
103317     }
103318     case '?': {
103319       *tokenType = TK_VARIABLE;
103320       for(i=1; sqlite3Isdigit(z[i]); i++){}
103321       return i;
103322     }
103323     case '#': {
103324       for(i=1; sqlite3Isdigit(z[i]); i++){}
103325       if( i>1 ){
103326         /* Parameters of the form #NNN (where NNN is a number) are used
103327         ** internally by sqlite3NestedParse.  */
103328         *tokenType = TK_REGISTER;
103329         return i;
103330       }
103331       /* Fall through into the next case if the '#' is not followed by
103332       ** a digit. Try to match #AAAA where AAAA is a parameter name. */
103333     }
103334 #ifndef SQLITE_OMIT_TCL_VARIABLE
103335     case '$':
103336 #endif
103337     case '@':  /* For compatibility with MS SQL Server */
103338     case ':': {
103339       int n = 0;
103340       testcase( z[0]=='$' );  testcase( z[0]=='@' );  testcase( z[0]==':' );
103341       *tokenType = TK_VARIABLE;
103342       for(i=1; (c=z[i])!=0; i++){
103343         if( IdChar(c) ){
103344           n++;
103345 #ifndef SQLITE_OMIT_TCL_VARIABLE
103346         }else if( c=='(' && n>0 ){
103347           do{
103348             i++;
103349           }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
103350           if( c==')' ){
103351             i++;
103352           }else{
103353             *tokenType = TK_ILLEGAL;
103354           }
103355           break;
103356         }else if( c==':' && z[i+1]==':' ){
103357           i++;
103358 #endif
103359         }else{
103360           break;
103361         }
103362       }
103363       if( n==0 ) *tokenType = TK_ILLEGAL;
103364       return i;
103365     }
103366 #ifndef SQLITE_OMIT_BLOB_LITERAL
103367     case 'x': case 'X': {
103368       testcase( z[0]=='x' ); testcase( z[0]=='X' );
103369       if( z[1]=='\'' ){
103370         *tokenType = TK_BLOB;
103371         for(i=2; (c=z[i])!=0 && c!='\''; i++){
103372           if( !sqlite3Isxdigit(c) ){
103373             *tokenType = TK_ILLEGAL;
103374           }
103375         }
103376         if( i%2 || !c ) *tokenType = TK_ILLEGAL;
103377         if( c ) i++;
103378         return i;
103379       }
103380       /* Otherwise fall through to the next case */
103381     }
103382 #endif
103383     default: {
103384       if( !IdChar(*z) ){
103385         break;
103386       }
103387       for(i=1; IdChar(z[i]); i++){}
103388       *tokenType = keywordCode((char*)z, i);
103389       return i;
103390     }
103391   }
103392   *tokenType = TK_ILLEGAL;
103393   return 1;
103394 }
103395
103396 /*
103397 ** Run the parser on the given SQL string.  The parser structure is
103398 ** passed in.  An SQLITE_ status code is returned.  If an error occurs
103399 ** then an and attempt is made to write an error message into 
103400 ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
103401 ** error message.
103402 */
103403 SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
103404   int nErr = 0;                   /* Number of errors encountered */
103405   int i;                          /* Loop counter */
103406   void *pEngine;                  /* The LEMON-generated LALR(1) parser */
103407   int tokenType;                  /* type of the next token */
103408   int lastTokenParsed = -1;       /* type of the previous token */
103409   u8 enableLookaside;             /* Saved value of db->lookaside.bEnabled */
103410   sqlite3 *db = pParse->db;       /* The database connection */
103411   int mxSqlLen;                   /* Max length of an SQL string */
103412
103413
103414   mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
103415   if( db->activeVdbeCnt==0 ){
103416     db->u1.isInterrupted = 0;
103417   }
103418   pParse->rc = SQLITE_OK;
103419   pParse->zTail = zSql;
103420   i = 0;
103421   assert( pzErrMsg!=0 );
103422   pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc);
103423   if( pEngine==0 ){
103424     db->mallocFailed = 1;
103425     return SQLITE_NOMEM;
103426   }
103427   assert( pParse->pNewTable==0 );
103428   assert( pParse->pNewTrigger==0 );
103429   assert( pParse->nVar==0 );
103430   assert( pParse->nVarExpr==0 );
103431   assert( pParse->nVarExprAlloc==0 );
103432   assert( pParse->apVarExpr==0 );
103433   enableLookaside = db->lookaside.bEnabled;
103434   if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
103435   while( !db->mallocFailed && zSql[i]!=0 ){
103436     assert( i>=0 );
103437     pParse->sLastToken.z = &zSql[i];
103438     pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
103439     i += pParse->sLastToken.n;
103440     if( i>mxSqlLen ){
103441       pParse->rc = SQLITE_TOOBIG;
103442       break;
103443     }
103444     switch( tokenType ){
103445       case TK_SPACE: {
103446         if( db->u1.isInterrupted ){
103447           sqlite3ErrorMsg(pParse, "interrupt");
103448           pParse->rc = SQLITE_INTERRUPT;
103449           goto abort_parse;
103450         }
103451         break;
103452       }
103453       case TK_ILLEGAL: {
103454         sqlite3DbFree(db, *pzErrMsg);
103455         *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
103456                         &pParse->sLastToken);
103457         nErr++;
103458         goto abort_parse;
103459       }
103460       case TK_SEMI: {
103461         pParse->zTail = &zSql[i];
103462         /* Fall thru into the default case */
103463       }
103464       default: {
103465         sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
103466         lastTokenParsed = tokenType;
103467         if( pParse->rc!=SQLITE_OK ){
103468           goto abort_parse;
103469         }
103470         break;
103471       }
103472     }
103473   }
103474 abort_parse:
103475   if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
103476     if( lastTokenParsed!=TK_SEMI ){
103477       sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
103478       pParse->zTail = &zSql[i];
103479     }
103480     sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
103481   }
103482 #ifdef YYTRACKMAXSTACKDEPTH
103483   sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
103484       sqlite3ParserStackPeak(pEngine)
103485   );
103486 #endif /* YYDEBUG */
103487   sqlite3ParserFree(pEngine, sqlite3_free);
103488   db->lookaside.bEnabled = enableLookaside;
103489   if( db->mallocFailed ){
103490     pParse->rc = SQLITE_NOMEM;
103491   }
103492   if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
103493     sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
103494   }
103495   assert( pzErrMsg!=0 );
103496   if( pParse->zErrMsg ){
103497     *pzErrMsg = pParse->zErrMsg;
103498     sqlite3_log(pParse->rc, "%s", *pzErrMsg);
103499     pParse->zErrMsg = 0;
103500     nErr++;
103501   }
103502   if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
103503     sqlite3VdbeDelete(pParse->pVdbe);
103504     pParse->pVdbe = 0;
103505   }
103506 #ifndef SQLITE_OMIT_SHARED_CACHE
103507   if( pParse->nested==0 ){
103508     sqlite3DbFree(db, pParse->aTableLock);
103509     pParse->aTableLock = 0;
103510     pParse->nTableLock = 0;
103511   }
103512 #endif
103513 #ifndef SQLITE_OMIT_VIRTUALTABLE
103514   sqlite3_free(pParse->apVtabLock);
103515 #endif
103516
103517   if( !IN_DECLARE_VTAB ){
103518     /* If the pParse->declareVtab flag is set, do not delete any table 
103519     ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
103520     ** will take responsibility for freeing the Table structure.
103521     */
103522     sqlite3DeleteTable(db, pParse->pNewTable);
103523   }
103524
103525   sqlite3DeleteTrigger(db, pParse->pNewTrigger);
103526   sqlite3DbFree(db, pParse->apVarExpr);
103527   sqlite3DbFree(db, pParse->aAlias);
103528   while( pParse->pAinc ){
103529     AutoincInfo *p = pParse->pAinc;
103530     pParse->pAinc = p->pNext;
103531     sqlite3DbFree(db, p);
103532   }
103533   while( pParse->pZombieTab ){
103534     Table *p = pParse->pZombieTab;
103535     pParse->pZombieTab = p->pNextZombie;
103536     sqlite3DeleteTable(db, p);
103537   }
103538   if( nErr>0 && pParse->rc==SQLITE_OK ){
103539     pParse->rc = SQLITE_ERROR;
103540   }
103541   return nErr;
103542 }
103543
103544 /************** End of tokenize.c ********************************************/
103545 /************** Begin file complete.c ****************************************/
103546 /*
103547 ** 2001 September 15
103548 **
103549 ** The author disclaims copyright to this source code.  In place of
103550 ** a legal notice, here is a blessing:
103551 **
103552 **    May you do good and not evil.
103553 **    May you find forgiveness for yourself and forgive others.
103554 **    May you share freely, never taking more than you give.
103555 **
103556 *************************************************************************
103557 ** An tokenizer for SQL
103558 **
103559 ** This file contains C code that implements the sqlite3_complete() API.
103560 ** This code used to be part of the tokenizer.c source file.  But by
103561 ** separating it out, the code will be automatically omitted from
103562 ** static links that do not use it.
103563 */
103564 #ifndef SQLITE_OMIT_COMPLETE
103565
103566 /*
103567 ** This is defined in tokenize.c.  We just have to import the definition.
103568 */
103569 #ifndef SQLITE_AMALGAMATION
103570 #ifdef SQLITE_ASCII
103571 #define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
103572 #endif
103573 #ifdef SQLITE_EBCDIC
103574 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
103575 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
103576 #endif
103577 #endif /* SQLITE_AMALGAMATION */
103578
103579
103580 /*
103581 ** Token types used by the sqlite3_complete() routine.  See the header
103582 ** comments on that procedure for additional information.
103583 */
103584 #define tkSEMI    0
103585 #define tkWS      1
103586 #define tkOTHER   2
103587 #ifndef SQLITE_OMIT_TRIGGER
103588 #define tkEXPLAIN 3
103589 #define tkCREATE  4
103590 #define tkTEMP    5
103591 #define tkTRIGGER 6
103592 #define tkEND     7
103593 #endif
103594
103595 /*
103596 ** Return TRUE if the given SQL string ends in a semicolon.
103597 **
103598 ** Special handling is require for CREATE TRIGGER statements.
103599 ** Whenever the CREATE TRIGGER keywords are seen, the statement
103600 ** must end with ";END;".
103601 **
103602 ** This implementation uses a state machine with 8 states:
103603 **
103604 **   (0) INVALID   We have not yet seen a non-whitespace character.
103605 **
103606 **   (1) START     At the beginning or end of an SQL statement.  This routine
103607 **                 returns 1 if it ends in the START state and 0 if it ends
103608 **                 in any other state.
103609 **
103610 **   (2) NORMAL    We are in the middle of statement which ends with a single
103611 **                 semicolon.
103612 **
103613 **   (3) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of 
103614 **                 a statement.
103615 **
103616 **   (4) CREATE    The keyword CREATE has been seen at the beginning of a
103617 **                 statement, possibly preceeded by EXPLAIN and/or followed by
103618 **                 TEMP or TEMPORARY
103619 **
103620 **   (5) TRIGGER   We are in the middle of a trigger definition that must be
103621 **                 ended by a semicolon, the keyword END, and another semicolon.
103622 **
103623 **   (6) SEMI      We've seen the first semicolon in the ";END;" that occurs at
103624 **                 the end of a trigger definition.
103625 **
103626 **   (7) END       We've seen the ";END" of the ";END;" that occurs at the end
103627 **                 of a trigger difinition.
103628 **
103629 ** Transitions between states above are determined by tokens extracted
103630 ** from the input.  The following tokens are significant:
103631 **
103632 **   (0) tkSEMI      A semicolon.
103633 **   (1) tkWS        Whitespace.
103634 **   (2) tkOTHER     Any other SQL token.
103635 **   (3) tkEXPLAIN   The "explain" keyword.
103636 **   (4) tkCREATE    The "create" keyword.
103637 **   (5) tkTEMP      The "temp" or "temporary" keyword.
103638 **   (6) tkTRIGGER   The "trigger" keyword.
103639 **   (7) tkEND       The "end" keyword.
103640 **
103641 ** Whitespace never causes a state transition and is always ignored.
103642 ** This means that a SQL string of all whitespace is invalid.
103643 **
103644 ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
103645 ** to recognize the end of a trigger can be omitted.  All we have to do
103646 ** is look for a semicolon that is not part of an string or comment.
103647 */
103648 SQLITE_API int sqlite3_complete(const char *zSql){
103649   u8 state = 0;   /* Current state, using numbers defined in header comment */
103650   u8 token;       /* Value of the next token */
103651
103652 #ifndef SQLITE_OMIT_TRIGGER
103653   /* A complex statement machine used to detect the end of a CREATE TRIGGER
103654   ** statement.  This is the normal case.
103655   */
103656   static const u8 trans[8][8] = {
103657                      /* Token:                                                */
103658      /* State:       **  SEMI  WS  OTHER  EXPLAIN  CREATE  TEMP  TRIGGER  END */
103659      /* 0 INVALID: */ {    1,  0,     2,       3,      4,    2,       2,   2, },
103660      /* 1   START: */ {    1,  1,     2,       3,      4,    2,       2,   2, },
103661      /* 2  NORMAL: */ {    1,  2,     2,       2,      2,    2,       2,   2, },
103662      /* 3 EXPLAIN: */ {    1,  3,     3,       2,      4,    2,       2,   2, },
103663      /* 4  CREATE: */ {    1,  4,     2,       2,      2,    4,       5,   2, },
103664      /* 5 TRIGGER: */ {    6,  5,     5,       5,      5,    5,       5,   5, },
103665      /* 6    SEMI: */ {    6,  6,     5,       5,      5,    5,       5,   7, },
103666      /* 7     END: */ {    1,  7,     5,       5,      5,    5,       5,   5, },
103667   };
103668 #else
103669   /* If triggers are not supported by this compile then the statement machine
103670   ** used to detect the end of a statement is much simplier
103671   */
103672   static const u8 trans[3][3] = {
103673                      /* Token:           */
103674      /* State:       **  SEMI  WS  OTHER */
103675      /* 0 INVALID: */ {    1,  0,     2, },
103676      /* 1   START: */ {    1,  1,     2, },
103677      /* 2  NORMAL: */ {    1,  2,     2, },
103678   };
103679 #endif /* SQLITE_OMIT_TRIGGER */
103680
103681   while( *zSql ){
103682     switch( *zSql ){
103683       case ';': {  /* A semicolon */
103684         token = tkSEMI;
103685         break;
103686       }
103687       case ' ':
103688       case '\r':
103689       case '\t':
103690       case '\n':
103691       case '\f': {  /* White space is ignored */
103692         token = tkWS;
103693         break;
103694       }
103695       case '/': {   /* C-style comments */
103696         if( zSql[1]!='*' ){
103697           token = tkOTHER;
103698           break;
103699         }
103700         zSql += 2;
103701         while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
103702         if( zSql[0]==0 ) return 0;
103703         zSql++;
103704         token = tkWS;
103705         break;
103706       }
103707       case '-': {   /* SQL-style comments from "--" to end of line */
103708         if( zSql[1]!='-' ){
103709           token = tkOTHER;
103710           break;
103711         }
103712         while( *zSql && *zSql!='\n' ){ zSql++; }
103713         if( *zSql==0 ) return state==1;
103714         token = tkWS;
103715         break;
103716       }
103717       case '[': {   /* Microsoft-style identifiers in [...] */
103718         zSql++;
103719         while( *zSql && *zSql!=']' ){ zSql++; }
103720         if( *zSql==0 ) return 0;
103721         token = tkOTHER;
103722         break;
103723       }
103724       case '`':     /* Grave-accent quoted symbols used by MySQL */
103725       case '"':     /* single- and double-quoted strings */
103726       case '\'': {
103727         int c = *zSql;
103728         zSql++;
103729         while( *zSql && *zSql!=c ){ zSql++; }
103730         if( *zSql==0 ) return 0;
103731         token = tkOTHER;
103732         break;
103733       }
103734       default: {
103735 #ifdef SQLITE_EBCDIC
103736         unsigned char c;
103737 #endif
103738         if( IdChar((u8)*zSql) ){
103739           /* Keywords and unquoted identifiers */
103740           int nId;
103741           for(nId=1; IdChar(zSql[nId]); nId++){}
103742 #ifdef SQLITE_OMIT_TRIGGER
103743           token = tkOTHER;
103744 #else
103745           switch( *zSql ){
103746             case 'c': case 'C': {
103747               if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
103748                 token = tkCREATE;
103749               }else{
103750                 token = tkOTHER;
103751               }
103752               break;
103753             }
103754             case 't': case 'T': {
103755               if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
103756                 token = tkTRIGGER;
103757               }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
103758                 token = tkTEMP;
103759               }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
103760                 token = tkTEMP;
103761               }else{
103762                 token = tkOTHER;
103763               }
103764               break;
103765             }
103766             case 'e':  case 'E': {
103767               if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
103768                 token = tkEND;
103769               }else
103770 #ifndef SQLITE_OMIT_EXPLAIN
103771               if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
103772                 token = tkEXPLAIN;
103773               }else
103774 #endif
103775               {
103776                 token = tkOTHER;
103777               }
103778               break;
103779             }
103780             default: {
103781               token = tkOTHER;
103782               break;
103783             }
103784           }
103785 #endif /* SQLITE_OMIT_TRIGGER */
103786           zSql += nId-1;
103787         }else{
103788           /* Operators and special symbols */
103789           token = tkOTHER;
103790         }
103791         break;
103792       }
103793     }
103794     state = trans[state][token];
103795     zSql++;
103796   }
103797   return state==1;
103798 }
103799
103800 #ifndef SQLITE_OMIT_UTF16
103801 /*
103802 ** This routine is the same as the sqlite3_complete() routine described
103803 ** above, except that the parameter is required to be UTF-16 encoded, not
103804 ** UTF-8.
103805 */
103806 SQLITE_API int sqlite3_complete16(const void *zSql){
103807   sqlite3_value *pVal;
103808   char const *zSql8;
103809   int rc = SQLITE_NOMEM;
103810
103811 #ifndef SQLITE_OMIT_AUTOINIT
103812   rc = sqlite3_initialize();
103813   if( rc ) return rc;
103814 #endif
103815   pVal = sqlite3ValueNew(0);
103816   sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
103817   zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
103818   if( zSql8 ){
103819     rc = sqlite3_complete(zSql8);
103820   }else{
103821     rc = SQLITE_NOMEM;
103822   }
103823   sqlite3ValueFree(pVal);
103824   return sqlite3ApiExit(0, rc);
103825 }
103826 #endif /* SQLITE_OMIT_UTF16 */
103827 #endif /* SQLITE_OMIT_COMPLETE */
103828
103829 /************** End of complete.c ********************************************/
103830 /************** Begin file main.c ********************************************/
103831 /*
103832 ** 2001 September 15
103833 **
103834 ** The author disclaims copyright to this source code.  In place of
103835 ** a legal notice, here is a blessing:
103836 **
103837 **    May you do good and not evil.
103838 **    May you find forgiveness for yourself and forgive others.
103839 **    May you share freely, never taking more than you give.
103840 **
103841 *************************************************************************
103842 ** Main file for the SQLite library.  The routines in this file
103843 ** implement the programmer interface to the library.  Routines in
103844 ** other files are for internal use by SQLite and should not be
103845 ** accessed by users of the library.
103846 */
103847
103848 #ifdef SQLITE_ENABLE_FTS3
103849 /************** Include fts3.h in the middle of main.c ***********************/
103850 /************** Begin file fts3.h ********************************************/
103851 /*
103852 ** 2006 Oct 10
103853 **
103854 ** The author disclaims copyright to this source code.  In place of
103855 ** a legal notice, here is a blessing:
103856 **
103857 **    May you do good and not evil.
103858 **    May you find forgiveness for yourself and forgive others.
103859 **    May you share freely, never taking more than you give.
103860 **
103861 ******************************************************************************
103862 **
103863 ** This header file is used by programs that want to link against the
103864 ** FTS3 library.  All it does is declare the sqlite3Fts3Init() interface.
103865 */
103866
103867 #if 0
103868 extern "C" {
103869 #endif  /* __cplusplus */
103870
103871 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
103872
103873 #if 0
103874 }  /* extern "C" */
103875 #endif  /* __cplusplus */
103876
103877 /************** End of fts3.h ************************************************/
103878 /************** Continuing where we left off in main.c ***********************/
103879 #endif
103880 #ifdef SQLITE_ENABLE_RTREE
103881 /************** Include rtree.h in the middle of main.c **********************/
103882 /************** Begin file rtree.h *******************************************/
103883 /*
103884 ** 2008 May 26
103885 **
103886 ** The author disclaims copyright to this source code.  In place of
103887 ** a legal notice, here is a blessing:
103888 **
103889 **    May you do good and not evil.
103890 **    May you find forgiveness for yourself and forgive others.
103891 **    May you share freely, never taking more than you give.
103892 **
103893 ******************************************************************************
103894 **
103895 ** This header file is used by programs that want to link against the
103896 ** RTREE library.  All it does is declare the sqlite3RtreeInit() interface.
103897 */
103898
103899 #if 0
103900 extern "C" {
103901 #endif  /* __cplusplus */
103902
103903 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
103904
103905 #if 0
103906 }  /* extern "C" */
103907 #endif  /* __cplusplus */
103908
103909 /************** End of rtree.h ***********************************************/
103910 /************** Continuing where we left off in main.c ***********************/
103911 #endif
103912 #ifdef SQLITE_ENABLE_ICU
103913 /************** Include sqliteicu.h in the middle of main.c ******************/
103914 /************** Begin file sqliteicu.h ***************************************/
103915 /*
103916 ** 2008 May 26
103917 **
103918 ** The author disclaims copyright to this source code.  In place of
103919 ** a legal notice, here is a blessing:
103920 **
103921 **    May you do good and not evil.
103922 **    May you find forgiveness for yourself and forgive others.
103923 **    May you share freely, never taking more than you give.
103924 **
103925 ******************************************************************************
103926 **
103927 ** This header file is used by programs that want to link against the
103928 ** ICU extension.  All it does is declare the sqlite3IcuInit() interface.
103929 */
103930
103931 #if 0
103932 extern "C" {
103933 #endif  /* __cplusplus */
103934
103935 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
103936
103937 #if 0
103938 }  /* extern "C" */
103939 #endif  /* __cplusplus */
103940
103941
103942 /************** End of sqliteicu.h *******************************************/
103943 /************** Continuing where we left off in main.c ***********************/
103944 #endif
103945
103946 #ifndef SQLITE_AMALGAMATION
103947 /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
103948 ** contains the text of SQLITE_VERSION macro. 
103949 */
103950 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
103951 #endif
103952
103953 /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
103954 ** a pointer to the to the sqlite3_version[] string constant. 
103955 */
103956 SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
103957
103958 /* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
103959 ** pointer to a string constant whose value is the same as the
103960 ** SQLITE_SOURCE_ID C preprocessor macro. 
103961 */
103962 SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
103963
103964 /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
103965 ** returns an integer equal to SQLITE_VERSION_NUMBER.
103966 */
103967 SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
103968
103969 /* IMPLEMENTATION-OF: R-54823-41343 The sqlite3_threadsafe() function returns
103970 ** zero if and only if SQLite was compiled mutexing code omitted due to
103971 ** the SQLITE_THREADSAFE compile-time option being set to 0.
103972 */
103973 SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
103974
103975 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
103976 /*
103977 ** If the following function pointer is not NULL and if
103978 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
103979 ** I/O active are written using this function.  These messages
103980 ** are intended for debugging activity only.
103981 */
103982 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0;
103983 #endif
103984
103985 /*
103986 ** If the following global variable points to a string which is the
103987 ** name of a directory, then that directory will be used to store
103988 ** temporary files.
103989 **
103990 ** See also the "PRAGMA temp_store_directory" SQL command.
103991 */
103992 SQLITE_API char *sqlite3_temp_directory = 0;
103993
103994 /*
103995 ** Initialize SQLite.  
103996 **
103997 ** This routine must be called to initialize the memory allocation,
103998 ** VFS, and mutex subsystems prior to doing any serious work with
103999 ** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
104000 ** this routine will be called automatically by key routines such as
104001 ** sqlite3_open().  
104002 **
104003 ** This routine is a no-op except on its very first call for the process,
104004 ** or for the first call after a call to sqlite3_shutdown.
104005 **
104006 ** The first thread to call this routine runs the initialization to
104007 ** completion.  If subsequent threads call this routine before the first
104008 ** thread has finished the initialization process, then the subsequent
104009 ** threads must block until the first thread finishes with the initialization.
104010 **
104011 ** The first thread might call this routine recursively.  Recursive
104012 ** calls to this routine should not block, of course.  Otherwise the
104013 ** initialization process would never complete.
104014 **
104015 ** Let X be the first thread to enter this routine.  Let Y be some other
104016 ** thread.  Then while the initial invocation of this routine by X is
104017 ** incomplete, it is required that:
104018 **
104019 **    *  Calls to this routine from Y must block until the outer-most
104020 **       call by X completes.
104021 **
104022 **    *  Recursive calls to this routine from thread X return immediately
104023 **       without blocking.
104024 */
104025 SQLITE_API int sqlite3_initialize(void){
104026   sqlite3_mutex *pMaster;                      /* The main static mutex */
104027   int rc;                                      /* Result code */
104028
104029 #ifdef SQLITE_OMIT_WSD
104030   rc = sqlite3_wsd_init(4096, 24);
104031   if( rc!=SQLITE_OK ){
104032     return rc;
104033   }
104034 #endif
104035
104036   /* If SQLite is already completely initialized, then this call
104037   ** to sqlite3_initialize() should be a no-op.  But the initialization
104038   ** must be complete.  So isInit must not be set until the very end
104039   ** of this routine.
104040   */
104041   if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
104042
104043   /* Make sure the mutex subsystem is initialized.  If unable to 
104044   ** initialize the mutex subsystem, return early with the error.
104045   ** If the system is so sick that we are unable to allocate a mutex,
104046   ** there is not much SQLite is going to be able to do.
104047   **
104048   ** The mutex subsystem must take care of serializing its own
104049   ** initialization.
104050   */
104051   rc = sqlite3MutexInit();
104052   if( rc ) return rc;
104053
104054   /* Initialize the malloc() system and the recursive pInitMutex mutex.
104055   ** This operation is protected by the STATIC_MASTER mutex.  Note that
104056   ** MutexAlloc() is called for a static mutex prior to initializing the
104057   ** malloc subsystem - this implies that the allocation of a static
104058   ** mutex must not require support from the malloc subsystem.
104059   */
104060   pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
104061   sqlite3_mutex_enter(pMaster);
104062   sqlite3GlobalConfig.isMutexInit = 1;
104063   if( !sqlite3GlobalConfig.isMallocInit ){
104064     rc = sqlite3MallocInit();
104065   }
104066   if( rc==SQLITE_OK ){
104067     sqlite3GlobalConfig.isMallocInit = 1;
104068     if( !sqlite3GlobalConfig.pInitMutex ){
104069       sqlite3GlobalConfig.pInitMutex =
104070            sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
104071       if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
104072         rc = SQLITE_NOMEM;
104073       }
104074     }
104075   }
104076   if( rc==SQLITE_OK ){
104077     sqlite3GlobalConfig.nRefInitMutex++;
104078   }
104079   sqlite3_mutex_leave(pMaster);
104080
104081   /* If rc is not SQLITE_OK at this point, then either the malloc
104082   ** subsystem could not be initialized or the system failed to allocate
104083   ** the pInitMutex mutex. Return an error in either case.  */
104084   if( rc!=SQLITE_OK ){
104085     return rc;
104086   }
104087
104088   /* Do the rest of the initialization under the recursive mutex so
104089   ** that we will be able to handle recursive calls into
104090   ** sqlite3_initialize().  The recursive calls normally come through
104091   ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
104092   ** recursive calls might also be possible.
104093   **
104094   ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
104095   ** to the xInit method, so the xInit method need not be threadsafe.
104096   **
104097   ** The following mutex is what serializes access to the appdef pcache xInit
104098   ** methods.  The sqlite3_pcache_methods.xInit() all is embedded in the
104099   ** call to sqlite3PcacheInitialize().
104100   */
104101   sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
104102   if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
104103     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
104104     sqlite3GlobalConfig.inProgress = 1;
104105     memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
104106     sqlite3RegisterGlobalFunctions();
104107     if( sqlite3GlobalConfig.isPCacheInit==0 ){
104108       rc = sqlite3PcacheInitialize();
104109     }
104110     if( rc==SQLITE_OK ){
104111       sqlite3GlobalConfig.isPCacheInit = 1;
104112       rc = sqlite3OsInit();
104113     }
104114     if( rc==SQLITE_OK ){
104115       sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage, 
104116           sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
104117       sqlite3GlobalConfig.isInit = 1;
104118     }
104119     sqlite3GlobalConfig.inProgress = 0;
104120   }
104121   sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
104122
104123   /* Go back under the static mutex and clean up the recursive
104124   ** mutex to prevent a resource leak.
104125   */
104126   sqlite3_mutex_enter(pMaster);
104127   sqlite3GlobalConfig.nRefInitMutex--;
104128   if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
104129     assert( sqlite3GlobalConfig.nRefInitMutex==0 );
104130     sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
104131     sqlite3GlobalConfig.pInitMutex = 0;
104132   }
104133   sqlite3_mutex_leave(pMaster);
104134
104135   /* The following is just a sanity check to make sure SQLite has
104136   ** been compiled correctly.  It is important to run this code, but
104137   ** we don't want to run it too often and soak up CPU cycles for no
104138   ** reason.  So we run it once during initialization.
104139   */
104140 #ifndef NDEBUG
104141 #ifndef SQLITE_OMIT_FLOATING_POINT
104142   /* This section of code's only "output" is via assert() statements. */
104143   if ( rc==SQLITE_OK ){
104144     u64 x = (((u64)1)<<63)-1;
104145     double y;
104146     assert(sizeof(x)==8);
104147     assert(sizeof(x)==sizeof(y));
104148     memcpy(&y, &x, 8);
104149     assert( sqlite3IsNaN(y) );
104150   }
104151 #endif
104152 #endif
104153
104154   return rc;
104155 }
104156
104157 /*
104158 ** Undo the effects of sqlite3_initialize().  Must not be called while
104159 ** there are outstanding database connections or memory allocations or
104160 ** while any part of SQLite is otherwise in use in any thread.  This
104161 ** routine is not threadsafe.  But it is safe to invoke this routine
104162 ** on when SQLite is already shut down.  If SQLite is already shut down
104163 ** when this routine is invoked, then this routine is a harmless no-op.
104164 */
104165 SQLITE_API int sqlite3_shutdown(void){
104166   if( sqlite3GlobalConfig.isInit ){
104167     sqlite3_os_end();
104168     sqlite3_reset_auto_extension();
104169     sqlite3GlobalConfig.isInit = 0;
104170   }
104171   if( sqlite3GlobalConfig.isPCacheInit ){
104172     sqlite3PcacheShutdown();
104173     sqlite3GlobalConfig.isPCacheInit = 0;
104174   }
104175   if( sqlite3GlobalConfig.isMallocInit ){
104176     sqlite3MallocEnd();
104177     sqlite3GlobalConfig.isMallocInit = 0;
104178   }
104179   if( sqlite3GlobalConfig.isMutexInit ){
104180     sqlite3MutexEnd();
104181     sqlite3GlobalConfig.isMutexInit = 0;
104182   }
104183
104184   return SQLITE_OK;
104185 }
104186
104187 /*
104188 ** This API allows applications to modify the global configuration of
104189 ** the SQLite library at run-time.
104190 **
104191 ** This routine should only be called when there are no outstanding
104192 ** database connections or memory allocations.  This routine is not
104193 ** threadsafe.  Failure to heed these warnings can lead to unpredictable
104194 ** behavior.
104195 */
104196 SQLITE_API int sqlite3_config(int op, ...){
104197   va_list ap;
104198   int rc = SQLITE_OK;
104199
104200   /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
104201   ** the SQLite library is in use. */
104202   if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
104203
104204   va_start(ap, op);
104205   switch( op ){
104206
104207     /* Mutex configuration options are only available in a threadsafe
104208     ** compile. 
104209     */
104210 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
104211     case SQLITE_CONFIG_SINGLETHREAD: {
104212       /* Disable all mutexing */
104213       sqlite3GlobalConfig.bCoreMutex = 0;
104214       sqlite3GlobalConfig.bFullMutex = 0;
104215       break;
104216     }
104217     case SQLITE_CONFIG_MULTITHREAD: {
104218       /* Disable mutexing of database connections */
104219       /* Enable mutexing of core data structures */
104220       sqlite3GlobalConfig.bCoreMutex = 1;
104221       sqlite3GlobalConfig.bFullMutex = 0;
104222       break;
104223     }
104224     case SQLITE_CONFIG_SERIALIZED: {
104225       /* Enable all mutexing */
104226       sqlite3GlobalConfig.bCoreMutex = 1;
104227       sqlite3GlobalConfig.bFullMutex = 1;
104228       break;
104229     }
104230     case SQLITE_CONFIG_MUTEX: {
104231       /* Specify an alternative mutex implementation */
104232       sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
104233       break;
104234     }
104235     case SQLITE_CONFIG_GETMUTEX: {
104236       /* Retrieve the current mutex implementation */
104237       *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
104238       break;
104239     }
104240 #endif
104241
104242
104243     case SQLITE_CONFIG_MALLOC: {
104244       /* Specify an alternative malloc implementation */
104245       sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
104246       break;
104247     }
104248     case SQLITE_CONFIG_GETMALLOC: {
104249       /* Retrieve the current malloc() implementation */
104250       if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
104251       *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
104252       break;
104253     }
104254     case SQLITE_CONFIG_MEMSTATUS: {
104255       /* Enable or disable the malloc status collection */
104256       sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
104257       break;
104258     }
104259     case SQLITE_CONFIG_SCRATCH: {
104260       /* Designate a buffer for scratch memory space */
104261       sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
104262       sqlite3GlobalConfig.szScratch = va_arg(ap, int);
104263       sqlite3GlobalConfig.nScratch = va_arg(ap, int);
104264       break;
104265     }
104266     case SQLITE_CONFIG_PAGECACHE: {
104267       /* Designate a buffer for page cache memory space */
104268       sqlite3GlobalConfig.pPage = va_arg(ap, void*);
104269       sqlite3GlobalConfig.szPage = va_arg(ap, int);
104270       sqlite3GlobalConfig.nPage = va_arg(ap, int);
104271       break;
104272     }
104273
104274     case SQLITE_CONFIG_PCACHE: {
104275       /* Specify an alternative page cache implementation */
104276       sqlite3GlobalConfig.pcache = *va_arg(ap, sqlite3_pcache_methods*);
104277       break;
104278     }
104279
104280     case SQLITE_CONFIG_GETPCACHE: {
104281       if( sqlite3GlobalConfig.pcache.xInit==0 ){
104282         sqlite3PCacheSetDefault();
104283       }
104284       *va_arg(ap, sqlite3_pcache_methods*) = sqlite3GlobalConfig.pcache;
104285       break;
104286     }
104287
104288 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
104289     case SQLITE_CONFIG_HEAP: {
104290       /* Designate a buffer for heap memory space */
104291       sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
104292       sqlite3GlobalConfig.nHeap = va_arg(ap, int);
104293       sqlite3GlobalConfig.mnReq = va_arg(ap, int);
104294
104295       if( sqlite3GlobalConfig.pHeap==0 ){
104296         /* If the heap pointer is NULL, then restore the malloc implementation
104297         ** back to NULL pointers too.  This will cause the malloc to go
104298         ** back to its default implementation when sqlite3_initialize() is
104299         ** run.
104300         */
104301         memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
104302       }else{
104303         /* The heap pointer is not NULL, then install one of the
104304         ** mem5.c/mem3.c methods. If neither ENABLE_MEMSYS3 nor
104305         ** ENABLE_MEMSYS5 is defined, return an error.
104306         */
104307 #ifdef SQLITE_ENABLE_MEMSYS3
104308         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
104309 #endif
104310 #ifdef SQLITE_ENABLE_MEMSYS5
104311         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
104312 #endif
104313       }
104314       break;
104315     }
104316 #endif
104317
104318     case SQLITE_CONFIG_LOOKASIDE: {
104319       sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
104320       sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
104321       break;
104322     }
104323     
104324     /* Record a pointer to the logger funcction and its first argument.
104325     ** The default is NULL.  Logging is disabled if the function pointer is
104326     ** NULL.
104327     */
104328     case SQLITE_CONFIG_LOG: {
104329       /* MSVC is picky about pulling func ptrs from va lists.
104330       ** http://support.microsoft.com/kb/47961
104331       ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
104332       */
104333       typedef void(*LOGFUNC_t)(void*,int,const char*);
104334       sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
104335       sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
104336       break;
104337     }
104338
104339     default: {
104340       rc = SQLITE_ERROR;
104341       break;
104342     }
104343   }
104344   va_end(ap);
104345   return rc;
104346 }
104347
104348 /*
104349 ** Set up the lookaside buffers for a database connection.
104350 ** Return SQLITE_OK on success.  
104351 ** If lookaside is already active, return SQLITE_BUSY.
104352 **
104353 ** The sz parameter is the number of bytes in each lookaside slot.
104354 ** The cnt parameter is the number of slots.  If pStart is NULL the
104355 ** space for the lookaside memory is obtained from sqlite3_malloc().
104356 ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
104357 ** the lookaside memory.
104358 */
104359 static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
104360   void *pStart;
104361   if( db->lookaside.nOut ){
104362     return SQLITE_BUSY;
104363   }
104364   /* Free any existing lookaside buffer for this handle before
104365   ** allocating a new one so we don't have to have space for 
104366   ** both at the same time.
104367   */
104368   if( db->lookaside.bMalloced ){
104369     sqlite3_free(db->lookaside.pStart);
104370   }
104371   /* The size of a lookaside slot needs to be larger than a pointer
104372   ** to be useful.
104373   */
104374   if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
104375   if( cnt<0 ) cnt = 0;
104376   if( sz==0 || cnt==0 ){
104377     sz = 0;
104378     pStart = 0;
104379   }else if( pBuf==0 ){
104380     sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
104381     sqlite3BeginBenignMalloc();
104382     pStart = sqlite3Malloc( sz*cnt );  /* IMP: R-61949-35727 */
104383     sqlite3EndBenignMalloc();
104384   }else{
104385     sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
104386     pStart = pBuf;
104387   }
104388   db->lookaside.pStart = pStart;
104389   db->lookaside.pFree = 0;
104390   db->lookaside.sz = (u16)sz;
104391   if( pStart ){
104392     int i;
104393     LookasideSlot *p;
104394     assert( sz > (int)sizeof(LookasideSlot*) );
104395     p = (LookasideSlot*)pStart;
104396     for(i=cnt-1; i>=0; i--){
104397       p->pNext = db->lookaside.pFree;
104398       db->lookaside.pFree = p;
104399       p = (LookasideSlot*)&((u8*)p)[sz];
104400     }
104401     db->lookaside.pEnd = p;
104402     db->lookaside.bEnabled = 1;
104403     db->lookaside.bMalloced = pBuf==0 ?1:0;
104404   }else{
104405     db->lookaside.pEnd = 0;
104406     db->lookaside.bEnabled = 0;
104407     db->lookaside.bMalloced = 0;
104408   }
104409   return SQLITE_OK;
104410 }
104411
104412 /*
104413 ** Return the mutex associated with a database connection.
104414 */
104415 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
104416   return db->mutex;
104417 }
104418
104419 /*
104420 ** Configuration settings for an individual database connection
104421 */
104422 SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
104423   va_list ap;
104424   int rc;
104425   va_start(ap, op);
104426   switch( op ){
104427     case SQLITE_DBCONFIG_LOOKASIDE: {
104428       void *pBuf = va_arg(ap, void*); /* IMP: R-21112-12275 */
104429       int sz = va_arg(ap, int);       /* IMP: R-47871-25994 */
104430       int cnt = va_arg(ap, int);      /* IMP: R-04460-53386 */
104431       rc = setupLookaside(db, pBuf, sz, cnt);
104432       break;
104433     }
104434     default: {
104435       rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
104436       break;
104437     }
104438   }
104439   va_end(ap);
104440   return rc;
104441 }
104442
104443
104444 /*
104445 ** Return true if the buffer z[0..n-1] contains all spaces.
104446 */
104447 static int allSpaces(const char *z, int n){
104448   while( n>0 && z[n-1]==' ' ){ n--; }
104449   return n==0;
104450 }
104451
104452 /*
104453 ** This is the default collating function named "BINARY" which is always
104454 ** available.
104455 **
104456 ** If the padFlag argument is not NULL then space padding at the end
104457 ** of strings is ignored.  This implements the RTRIM collation.
104458 */
104459 static int binCollFunc(
104460   void *padFlag,
104461   int nKey1, const void *pKey1,
104462   int nKey2, const void *pKey2
104463 ){
104464   int rc, n;
104465   n = nKey1<nKey2 ? nKey1 : nKey2;
104466   rc = memcmp(pKey1, pKey2, n);
104467   if( rc==0 ){
104468     if( padFlag
104469      && allSpaces(((char*)pKey1)+n, nKey1-n)
104470      && allSpaces(((char*)pKey2)+n, nKey2-n)
104471     ){
104472       /* Leave rc unchanged at 0 */
104473     }else{
104474       rc = nKey1 - nKey2;
104475     }
104476   }
104477   return rc;
104478 }
104479
104480 /*
104481 ** Another built-in collating sequence: NOCASE. 
104482 **
104483 ** This collating sequence is intended to be used for "case independant
104484 ** comparison". SQLite's knowledge of upper and lower case equivalents
104485 ** extends only to the 26 characters used in the English language.
104486 **
104487 ** At the moment there is only a UTF-8 implementation.
104488 */
104489 static int nocaseCollatingFunc(
104490   void *NotUsed,
104491   int nKey1, const void *pKey1,
104492   int nKey2, const void *pKey2
104493 ){
104494   int r = sqlite3StrNICmp(
104495       (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
104496   UNUSED_PARAMETER(NotUsed);
104497   if( 0==r ){
104498     r = nKey1-nKey2;
104499   }
104500   return r;
104501 }
104502
104503 /*
104504 ** Return the ROWID of the most recent insert
104505 */
104506 SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
104507   return db->lastRowid;
104508 }
104509
104510 /*
104511 ** Return the number of changes in the most recent call to sqlite3_exec().
104512 */
104513 SQLITE_API int sqlite3_changes(sqlite3 *db){
104514   return db->nChange;
104515 }
104516
104517 /*
104518 ** Return the number of changes since the database handle was opened.
104519 */
104520 SQLITE_API int sqlite3_total_changes(sqlite3 *db){
104521   return db->nTotalChange;
104522 }
104523
104524 /*
104525 ** Close all open savepoints. This function only manipulates fields of the
104526 ** database handle object, it does not close any savepoints that may be open
104527 ** at the b-tree/pager level.
104528 */
104529 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
104530   while( db->pSavepoint ){
104531     Savepoint *pTmp = db->pSavepoint;
104532     db->pSavepoint = pTmp->pNext;
104533     sqlite3DbFree(db, pTmp);
104534   }
104535   db->nSavepoint = 0;
104536   db->nStatement = 0;
104537   db->isTransactionSavepoint = 0;
104538 }
104539
104540 /*
104541 ** Invoke the destructor function associated with FuncDef p, if any. Except,
104542 ** if this is not the last copy of the function, do not invoke it. Multiple
104543 ** copies of a single function are created when create_function() is called
104544 ** with SQLITE_ANY as the encoding.
104545 */
104546 static void functionDestroy(sqlite3 *db, FuncDef *p){
104547   FuncDestructor *pDestructor = p->pDestructor;
104548   if( pDestructor ){
104549     pDestructor->nRef--;
104550     if( pDestructor->nRef==0 ){
104551       pDestructor->xDestroy(pDestructor->pUserData);
104552       sqlite3DbFree(db, pDestructor);
104553     }
104554   }
104555 }
104556
104557 /*
104558 ** Close an existing SQLite database
104559 */
104560 SQLITE_API int sqlite3_close(sqlite3 *db){
104561   HashElem *i;                    /* Hash table iterator */
104562   int j;
104563
104564   if( !db ){
104565     return SQLITE_OK;
104566   }
104567   if( !sqlite3SafetyCheckSickOrOk(db) ){
104568     return SQLITE_MISUSE_BKPT;
104569   }
104570   sqlite3_mutex_enter(db->mutex);
104571
104572   sqlite3ResetInternalSchema(db, 0);
104573
104574   /* If a transaction is open, the ResetInternalSchema() call above
104575   ** will not have called the xDisconnect() method on any virtual
104576   ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
104577   ** call will do so. We need to do this before the check for active
104578   ** SQL statements below, as the v-table implementation may be storing
104579   ** some prepared statements internally.
104580   */
104581   sqlite3VtabRollback(db);
104582
104583   /* If there are any outstanding VMs, return SQLITE_BUSY. */
104584   if( db->pVdbe ){
104585     sqlite3Error(db, SQLITE_BUSY, 
104586         "unable to close due to unfinalised statements");
104587     sqlite3_mutex_leave(db->mutex);
104588     return SQLITE_BUSY;
104589   }
104590   assert( sqlite3SafetyCheckSickOrOk(db) );
104591
104592   for(j=0; j<db->nDb; j++){
104593     Btree *pBt = db->aDb[j].pBt;
104594     if( pBt && sqlite3BtreeIsInBackup(pBt) ){
104595       sqlite3Error(db, SQLITE_BUSY, 
104596           "unable to close due to unfinished backup operation");
104597       sqlite3_mutex_leave(db->mutex);
104598       return SQLITE_BUSY;
104599     }
104600   }
104601
104602   /* Free any outstanding Savepoint structures. */
104603   sqlite3CloseSavepoints(db);
104604
104605   for(j=0; j<db->nDb; j++){
104606     struct Db *pDb = &db->aDb[j];
104607     if( pDb->pBt ){
104608       sqlite3BtreeClose(pDb->pBt);
104609       pDb->pBt = 0;
104610       if( j!=1 ){
104611         pDb->pSchema = 0;
104612       }
104613     }
104614   }
104615   sqlite3ResetInternalSchema(db, 0);
104616
104617   /* Tell the code in notify.c that the connection no longer holds any
104618   ** locks and does not require any further unlock-notify callbacks.
104619   */
104620   sqlite3ConnectionClosed(db);
104621
104622   assert( db->nDb<=2 );
104623   assert( db->aDb==db->aDbStatic );
104624   for(j=0; j<ArraySize(db->aFunc.a); j++){
104625     FuncDef *pNext, *pHash, *p;
104626     for(p=db->aFunc.a[j]; p; p=pHash){
104627       pHash = p->pHash;
104628       while( p ){
104629         functionDestroy(db, p);
104630         pNext = p->pNext;
104631         sqlite3DbFree(db, p);
104632         p = pNext;
104633       }
104634     }
104635   }
104636   for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
104637     CollSeq *pColl = (CollSeq *)sqliteHashData(i);
104638     /* Invoke any destructors registered for collation sequence user data. */
104639     for(j=0; j<3; j++){
104640       if( pColl[j].xDel ){
104641         pColl[j].xDel(pColl[j].pUser);
104642       }
104643     }
104644     sqlite3DbFree(db, pColl);
104645   }
104646   sqlite3HashClear(&db->aCollSeq);
104647 #ifndef SQLITE_OMIT_VIRTUALTABLE
104648   for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
104649     Module *pMod = (Module *)sqliteHashData(i);
104650     if( pMod->xDestroy ){
104651       pMod->xDestroy(pMod->pAux);
104652     }
104653     sqlite3DbFree(db, pMod);
104654   }
104655   sqlite3HashClear(&db->aModule);
104656 #endif
104657
104658   sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
104659   if( db->pErr ){
104660     sqlite3ValueFree(db->pErr);
104661   }
104662   sqlite3CloseExtensions(db);
104663
104664   db->magic = SQLITE_MAGIC_ERROR;
104665
104666   /* The temp-database schema is allocated differently from the other schema
104667   ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
104668   ** So it needs to be freed here. Todo: Why not roll the temp schema into
104669   ** the same sqliteMalloc() as the one that allocates the database 
104670   ** structure?
104671   */
104672   sqlite3DbFree(db, db->aDb[1].pSchema);
104673   sqlite3_mutex_leave(db->mutex);
104674   db->magic = SQLITE_MAGIC_CLOSED;
104675   sqlite3_mutex_free(db->mutex);
104676   assert( db->lookaside.nOut==0 );  /* Fails on a lookaside memory leak */
104677   if( db->lookaside.bMalloced ){
104678     sqlite3_free(db->lookaside.pStart);
104679   }
104680   sqlite3_free(db);
104681   return SQLITE_OK;
104682 }
104683
104684 /*
104685 ** Rollback all database files.
104686 */
104687 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db){
104688   int i;
104689   int inTrans = 0;
104690   assert( sqlite3_mutex_held(db->mutex) );
104691   sqlite3BeginBenignMalloc();
104692   for(i=0; i<db->nDb; i++){
104693     if( db->aDb[i].pBt ){
104694       if( sqlite3BtreeIsInTrans(db->aDb[i].pBt) ){
104695         inTrans = 1;
104696       }
104697       sqlite3BtreeRollback(db->aDb[i].pBt);
104698       db->aDb[i].inTrans = 0;
104699     }
104700   }
104701   sqlite3VtabRollback(db);
104702   sqlite3EndBenignMalloc();
104703
104704   if( db->flags&SQLITE_InternChanges ){
104705     sqlite3ExpirePreparedStatements(db);
104706     sqlite3ResetInternalSchema(db, 0);
104707   }
104708
104709   /* Any deferred constraint violations have now been resolved. */
104710   db->nDeferredCons = 0;
104711
104712   /* If one has been configured, invoke the rollback-hook callback */
104713   if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
104714     db->xRollbackCallback(db->pRollbackArg);
104715   }
104716 }
104717
104718 /*
104719 ** Return a static string that describes the kind of error specified in the
104720 ** argument.
104721 */
104722 SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
104723   static const char* const aMsg[] = {
104724     /* SQLITE_OK          */ "not an error",
104725     /* SQLITE_ERROR       */ "SQL logic error or missing database",
104726     /* SQLITE_INTERNAL    */ 0,
104727     /* SQLITE_PERM        */ "access permission denied",
104728     /* SQLITE_ABORT       */ "callback requested query abort",
104729     /* SQLITE_BUSY        */ "database is locked",
104730     /* SQLITE_LOCKED      */ "database table is locked",
104731     /* SQLITE_NOMEM       */ "out of memory",
104732     /* SQLITE_READONLY    */ "attempt to write a readonly database",
104733     /* SQLITE_INTERRUPT   */ "interrupted",
104734     /* SQLITE_IOERR       */ "disk I/O error",
104735     /* SQLITE_CORRUPT     */ "database disk image is malformed",
104736     /* SQLITE_NOTFOUND    */ 0,
104737     /* SQLITE_FULL        */ "database or disk is full",
104738     /* SQLITE_CANTOPEN    */ "unable to open database file",
104739     /* SQLITE_PROTOCOL    */ "locking protocol",
104740     /* SQLITE_EMPTY       */ "table contains no data",
104741     /* SQLITE_SCHEMA      */ "database schema has changed",
104742     /* SQLITE_TOOBIG      */ "string or blob too big",
104743     /* SQLITE_CONSTRAINT  */ "constraint failed",
104744     /* SQLITE_MISMATCH    */ "datatype mismatch",
104745     /* SQLITE_MISUSE      */ "library routine called out of sequence",
104746     /* SQLITE_NOLFS       */ "large file support is disabled",
104747     /* SQLITE_AUTH        */ "authorization denied",
104748     /* SQLITE_FORMAT      */ "auxiliary database format error",
104749     /* SQLITE_RANGE       */ "bind or column index out of range",
104750     /* SQLITE_NOTADB      */ "file is encrypted or is not a database",
104751   };
104752   rc &= 0xff;
104753   if( ALWAYS(rc>=0) && rc<(int)(sizeof(aMsg)/sizeof(aMsg[0])) && aMsg[rc]!=0 ){
104754     return aMsg[rc];
104755   }else{
104756     return "unknown error";
104757   }
104758 }
104759
104760 /*
104761 ** This routine implements a busy callback that sleeps and tries
104762 ** again until a timeout value is reached.  The timeout value is
104763 ** an integer number of milliseconds passed in as the first
104764 ** argument.
104765 */
104766 static int sqliteDefaultBusyCallback(
104767  void *ptr,               /* Database connection */
104768  int count                /* Number of times table has been busy */
104769 ){
104770 #if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
104771   static const u8 delays[] =
104772      { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
104773   static const u8 totals[] =
104774      { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
104775 # define NDELAY (sizeof(delays)/sizeof(delays[0]))
104776   sqlite3 *db = (sqlite3 *)ptr;
104777   int timeout = db->busyTimeout;
104778   int delay, prior;
104779
104780   assert( count>=0 );
104781   if( count < NDELAY ){
104782     delay = delays[count];
104783     prior = totals[count];
104784   }else{
104785     delay = delays[NDELAY-1];
104786     prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
104787   }
104788   if( prior + delay > timeout ){
104789     delay = timeout - prior;
104790     if( delay<=0 ) return 0;
104791   }
104792   sqlite3OsSleep(db->pVfs, delay*1000);
104793   return 1;
104794 #else
104795   sqlite3 *db = (sqlite3 *)ptr;
104796   int timeout = ((sqlite3 *)ptr)->busyTimeout;
104797   if( (count+1)*1000 > timeout ){
104798     return 0;
104799   }
104800   sqlite3OsSleep(db->pVfs, 1000000);
104801   return 1;
104802 #endif
104803 }
104804
104805 /*
104806 ** Invoke the given busy handler.
104807 **
104808 ** This routine is called when an operation failed with a lock.
104809 ** If this routine returns non-zero, the lock is retried.  If it
104810 ** returns 0, the operation aborts with an SQLITE_BUSY error.
104811 */
104812 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
104813   int rc;
104814   if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
104815   rc = p->xFunc(p->pArg, p->nBusy);
104816   if( rc==0 ){
104817     p->nBusy = -1;
104818   }else{
104819     p->nBusy++;
104820   }
104821   return rc; 
104822 }
104823
104824 /*
104825 ** This routine sets the busy callback for an Sqlite database to the
104826 ** given callback function with the given argument.
104827 */
104828 SQLITE_API int sqlite3_busy_handler(
104829   sqlite3 *db,
104830   int (*xBusy)(void*,int),
104831   void *pArg
104832 ){
104833   sqlite3_mutex_enter(db->mutex);
104834   db->busyHandler.xFunc = xBusy;
104835   db->busyHandler.pArg = pArg;
104836   db->busyHandler.nBusy = 0;
104837   sqlite3_mutex_leave(db->mutex);
104838   return SQLITE_OK;
104839 }
104840
104841 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
104842 /*
104843 ** This routine sets the progress callback for an Sqlite database to the
104844 ** given callback function with the given argument. The progress callback will
104845 ** be invoked every nOps opcodes.
104846 */
104847 SQLITE_API void sqlite3_progress_handler(
104848   sqlite3 *db, 
104849   int nOps,
104850   int (*xProgress)(void*), 
104851   void *pArg
104852 ){
104853   sqlite3_mutex_enter(db->mutex);
104854   if( nOps>0 ){
104855     db->xProgress = xProgress;
104856     db->nProgressOps = nOps;
104857     db->pProgressArg = pArg;
104858   }else{
104859     db->xProgress = 0;
104860     db->nProgressOps = 0;
104861     db->pProgressArg = 0;
104862   }
104863   sqlite3_mutex_leave(db->mutex);
104864 }
104865 #endif
104866
104867
104868 /*
104869 ** This routine installs a default busy handler that waits for the
104870 ** specified number of milliseconds before returning 0.
104871 */
104872 SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
104873   if( ms>0 ){
104874     db->busyTimeout = ms;
104875     sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
104876   }else{
104877     sqlite3_busy_handler(db, 0, 0);
104878   }
104879   return SQLITE_OK;
104880 }
104881
104882 /*
104883 ** Cause any pending operation to stop at its earliest opportunity.
104884 */
104885 SQLITE_API void sqlite3_interrupt(sqlite3 *db){
104886   db->u1.isInterrupted = 1;
104887 }
104888
104889
104890 /*
104891 ** This function is exactly the same as sqlite3_create_function(), except
104892 ** that it is designed to be called by internal code. The difference is
104893 ** that if a malloc() fails in sqlite3_create_function(), an error code
104894 ** is returned and the mallocFailed flag cleared. 
104895 */
104896 SQLITE_PRIVATE int sqlite3CreateFunc(
104897   sqlite3 *db,
104898   const char *zFunctionName,
104899   int nArg,
104900   int enc,
104901   void *pUserData,
104902   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
104903   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
104904   void (*xFinal)(sqlite3_context*),
104905   FuncDestructor *pDestructor
104906 ){
104907   FuncDef *p;
104908   int nName;
104909
104910   assert( sqlite3_mutex_held(db->mutex) );
104911   if( zFunctionName==0 ||
104912       (xFunc && (xFinal || xStep)) || 
104913       (!xFunc && (xFinal && !xStep)) ||
104914       (!xFunc && (!xFinal && xStep)) ||
104915       (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
104916       (255<(nName = sqlite3Strlen30( zFunctionName))) ){
104917     return SQLITE_MISUSE_BKPT;
104918   }
104919   
104920 #ifndef SQLITE_OMIT_UTF16
104921   /* If SQLITE_UTF16 is specified as the encoding type, transform this
104922   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
104923   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
104924   **
104925   ** If SQLITE_ANY is specified, add three versions of the function
104926   ** to the hash table.
104927   */
104928   if( enc==SQLITE_UTF16 ){
104929     enc = SQLITE_UTF16NATIVE;
104930   }else if( enc==SQLITE_ANY ){
104931     int rc;
104932     rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
104933          pUserData, xFunc, xStep, xFinal, pDestructor);
104934     if( rc==SQLITE_OK ){
104935       rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
104936           pUserData, xFunc, xStep, xFinal, pDestructor);
104937     }
104938     if( rc!=SQLITE_OK ){
104939       return rc;
104940     }
104941     enc = SQLITE_UTF16BE;
104942   }
104943 #else
104944   enc = SQLITE_UTF8;
104945 #endif
104946   
104947   /* Check if an existing function is being overridden or deleted. If so,
104948   ** and there are active VMs, then return SQLITE_BUSY. If a function
104949   ** is being overridden/deleted but there are no active VMs, allow the
104950   ** operation to continue but invalidate all precompiled statements.
104951   */
104952   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
104953   if( p && p->iPrefEnc==enc && p->nArg==nArg ){
104954     if( db->activeVdbeCnt ){
104955       sqlite3Error(db, SQLITE_BUSY, 
104956         "unable to delete/modify user-function due to active statements");
104957       assert( !db->mallocFailed );
104958       return SQLITE_BUSY;
104959     }else{
104960       sqlite3ExpirePreparedStatements(db);
104961     }
104962   }
104963
104964   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
104965   assert(p || db->mallocFailed);
104966   if( !p ){
104967     return SQLITE_NOMEM;
104968   }
104969
104970   /* If an older version of the function with a configured destructor is
104971   ** being replaced invoke the destructor function here. */
104972   functionDestroy(db, p);
104973
104974   if( pDestructor ){
104975     pDestructor->nRef++;
104976   }
104977   p->pDestructor = pDestructor;
104978   p->flags = 0;
104979   p->xFunc = xFunc;
104980   p->xStep = xStep;
104981   p->xFinalize = xFinal;
104982   p->pUserData = pUserData;
104983   p->nArg = (u16)nArg;
104984   return SQLITE_OK;
104985 }
104986
104987 /*
104988 ** Create new user functions.
104989 */
104990 SQLITE_API int sqlite3_create_function(
104991   sqlite3 *db,
104992   const char *zFunc,
104993   int nArg,
104994   int enc,
104995   void *p,
104996   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
104997   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
104998   void (*xFinal)(sqlite3_context*)
104999 ){
105000   return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep,
105001                                     xFinal, 0);
105002 }
105003
105004 SQLITE_API int sqlite3_create_function_v2(
105005   sqlite3 *db,
105006   const char *zFunc,
105007   int nArg,
105008   int enc,
105009   void *p,
105010   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
105011   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
105012   void (*xFinal)(sqlite3_context*),
105013   void (*xDestroy)(void *)
105014 ){
105015   int rc = SQLITE_ERROR;
105016   FuncDestructor *pArg = 0;
105017   sqlite3_mutex_enter(db->mutex);
105018   if( xDestroy ){
105019     pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
105020     if( !pArg ){
105021       xDestroy(p);
105022       goto out;
105023     }
105024     pArg->xDestroy = xDestroy;
105025     pArg->pUserData = p;
105026   }
105027   rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg);
105028   if( pArg && pArg->nRef==0 ){
105029     assert( rc!=SQLITE_OK );
105030     xDestroy(p);
105031     sqlite3DbFree(db, pArg);
105032   }
105033
105034  out:
105035   rc = sqlite3ApiExit(db, rc);
105036   sqlite3_mutex_leave(db->mutex);
105037   return rc;
105038 }
105039
105040 #ifndef SQLITE_OMIT_UTF16
105041 SQLITE_API int sqlite3_create_function16(
105042   sqlite3 *db,
105043   const void *zFunctionName,
105044   int nArg,
105045   int eTextRep,
105046   void *p,
105047   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
105048   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
105049   void (*xFinal)(sqlite3_context*)
105050 ){
105051   int rc;
105052   char *zFunc8;
105053   sqlite3_mutex_enter(db->mutex);
105054   assert( !db->mallocFailed );
105055   zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
105056   rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0);
105057   sqlite3DbFree(db, zFunc8);
105058   rc = sqlite3ApiExit(db, rc);
105059   sqlite3_mutex_leave(db->mutex);
105060   return rc;
105061 }
105062 #endif
105063
105064
105065 /*
105066 ** Declare that a function has been overloaded by a virtual table.
105067 **
105068 ** If the function already exists as a regular global function, then
105069 ** this routine is a no-op.  If the function does not exist, then create
105070 ** a new one that always throws a run-time error.  
105071 **
105072 ** When virtual tables intend to provide an overloaded function, they
105073 ** should call this routine to make sure the global function exists.
105074 ** A global function must exist in order for name resolution to work
105075 ** properly.
105076 */
105077 SQLITE_API int sqlite3_overload_function(
105078   sqlite3 *db,
105079   const char *zName,
105080   int nArg
105081 ){
105082   int nName = sqlite3Strlen30(zName);
105083   int rc;
105084   sqlite3_mutex_enter(db->mutex);
105085   if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
105086     sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
105087                       0, sqlite3InvalidFunction, 0, 0, 0);
105088   }
105089   rc = sqlite3ApiExit(db, SQLITE_OK);
105090   sqlite3_mutex_leave(db->mutex);
105091   return rc;
105092 }
105093
105094 #ifndef SQLITE_OMIT_TRACE
105095 /*
105096 ** Register a trace function.  The pArg from the previously registered trace
105097 ** is returned.  
105098 **
105099 ** A NULL trace function means that no tracing is executes.  A non-NULL
105100 ** trace is a pointer to a function that is invoked at the start of each
105101 ** SQL statement.
105102 */
105103 SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
105104   void *pOld;
105105   sqlite3_mutex_enter(db->mutex);
105106   pOld = db->pTraceArg;
105107   db->xTrace = xTrace;
105108   db->pTraceArg = pArg;
105109   sqlite3_mutex_leave(db->mutex);
105110   return pOld;
105111 }
105112 /*
105113 ** Register a profile function.  The pArg from the previously registered 
105114 ** profile function is returned.  
105115 **
105116 ** A NULL profile function means that no profiling is executes.  A non-NULL
105117 ** profile is a pointer to a function that is invoked at the conclusion of
105118 ** each SQL statement that is run.
105119 */
105120 SQLITE_API void *sqlite3_profile(
105121   sqlite3 *db,
105122   void (*xProfile)(void*,const char*,sqlite_uint64),
105123   void *pArg
105124 ){
105125   void *pOld;
105126   sqlite3_mutex_enter(db->mutex);
105127   pOld = db->pProfileArg;
105128   db->xProfile = xProfile;
105129   db->pProfileArg = pArg;
105130   sqlite3_mutex_leave(db->mutex);
105131   return pOld;
105132 }
105133 #endif /* SQLITE_OMIT_TRACE */
105134
105135 /*** EXPERIMENTAL ***
105136 **
105137 ** Register a function to be invoked when a transaction comments.
105138 ** If the invoked function returns non-zero, then the commit becomes a
105139 ** rollback.
105140 */
105141 SQLITE_API void *sqlite3_commit_hook(
105142   sqlite3 *db,              /* Attach the hook to this database */
105143   int (*xCallback)(void*),  /* Function to invoke on each commit */
105144   void *pArg                /* Argument to the function */
105145 ){
105146   void *pOld;
105147   sqlite3_mutex_enter(db->mutex);
105148   pOld = db->pCommitArg;
105149   db->xCommitCallback = xCallback;
105150   db->pCommitArg = pArg;
105151   sqlite3_mutex_leave(db->mutex);
105152   return pOld;
105153 }
105154
105155 /*
105156 ** Register a callback to be invoked each time a row is updated,
105157 ** inserted or deleted using this database connection.
105158 */
105159 SQLITE_API void *sqlite3_update_hook(
105160   sqlite3 *db,              /* Attach the hook to this database */
105161   void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
105162   void *pArg                /* Argument to the function */
105163 ){
105164   void *pRet;
105165   sqlite3_mutex_enter(db->mutex);
105166   pRet = db->pUpdateArg;
105167   db->xUpdateCallback = xCallback;
105168   db->pUpdateArg = pArg;
105169   sqlite3_mutex_leave(db->mutex);
105170   return pRet;
105171 }
105172
105173 /*
105174 ** Register a callback to be invoked each time a transaction is rolled
105175 ** back by this database connection.
105176 */
105177 SQLITE_API void *sqlite3_rollback_hook(
105178   sqlite3 *db,              /* Attach the hook to this database */
105179   void (*xCallback)(void*), /* Callback function */
105180   void *pArg                /* Argument to the function */
105181 ){
105182   void *pRet;
105183   sqlite3_mutex_enter(db->mutex);
105184   pRet = db->pRollbackArg;
105185   db->xRollbackCallback = xCallback;
105186   db->pRollbackArg = pArg;
105187   sqlite3_mutex_leave(db->mutex);
105188   return pRet;
105189 }
105190
105191 #ifndef SQLITE_OMIT_WAL
105192 /*
105193 ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
105194 ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
105195 ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
105196 ** wal_autocheckpoint()).
105197 */ 
105198 SQLITE_PRIVATE int sqlite3WalDefaultHook(
105199   void *pClientData,     /* Argument */
105200   sqlite3 *db,           /* Connection */
105201   const char *zDb,       /* Database */
105202   int nFrame             /* Size of WAL */
105203 ){
105204   if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
105205     sqlite3BeginBenignMalloc();
105206     sqlite3_wal_checkpoint(db, zDb);
105207     sqlite3EndBenignMalloc();
105208   }
105209   return SQLITE_OK;
105210 }
105211 #endif /* SQLITE_OMIT_WAL */
105212
105213 /*
105214 ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
105215 ** a database after committing a transaction if there are nFrame or
105216 ** more frames in the log file. Passing zero or a negative value as the
105217 ** nFrame parameter disables automatic checkpoints entirely.
105218 **
105219 ** The callback registered by this function replaces any existing callback
105220 ** registered using sqlite3_wal_hook(). Likewise, registering a callback
105221 ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
105222 ** configured by this function.
105223 */
105224 SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
105225 #ifdef SQLITE_OMIT_WAL
105226   UNUSED_PARAMETER(db);
105227   UNUSED_PARAMETER(nFrame);
105228 #else
105229   if( nFrame>0 ){
105230     sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
105231   }else{
105232     sqlite3_wal_hook(db, 0, 0);
105233   }
105234 #endif
105235   return SQLITE_OK;
105236 }
105237
105238 /*
105239 ** Register a callback to be invoked each time a transaction is written
105240 ** into the write-ahead-log by this database connection.
105241 */
105242 SQLITE_API void *sqlite3_wal_hook(
105243   sqlite3 *db,                    /* Attach the hook to this db handle */
105244   int(*xCallback)(void *, sqlite3*, const char*, int),
105245   void *pArg                      /* First argument passed to xCallback() */
105246 ){
105247 #ifndef SQLITE_OMIT_WAL
105248   void *pRet;
105249   sqlite3_mutex_enter(db->mutex);
105250   pRet = db->pWalArg;
105251   db->xWalCallback = xCallback;
105252   db->pWalArg = pArg;
105253   sqlite3_mutex_leave(db->mutex);
105254   return pRet;
105255 #else
105256   return 0;
105257 #endif
105258 }
105259
105260
105261 /*
105262 ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
105263 ** to contains a zero-length string, all attached databases are 
105264 ** checkpointed.
105265 */
105266 SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
105267 #ifdef SQLITE_OMIT_WAL
105268   return SQLITE_OK;
105269 #else
105270   int rc;                         /* Return code */
105271   int iDb = SQLITE_MAX_ATTACHED;  /* sqlite3.aDb[] index of db to checkpoint */
105272
105273   sqlite3_mutex_enter(db->mutex);
105274   if( zDb && zDb[0] ){
105275     iDb = sqlite3FindDbName(db, zDb);
105276   }
105277   if( iDb<0 ){
105278     rc = SQLITE_ERROR;
105279     sqlite3Error(db, SQLITE_ERROR, "unknown database: %s", zDb);
105280   }else{
105281     rc = sqlite3Checkpoint(db, iDb);
105282     sqlite3Error(db, rc, 0);
105283   }
105284   rc = sqlite3ApiExit(db, rc);
105285   sqlite3_mutex_leave(db->mutex);
105286   return rc;
105287 #endif
105288 }
105289
105290 #ifndef SQLITE_OMIT_WAL
105291 /*
105292 ** Run a checkpoint on database iDb. This is a no-op if database iDb is
105293 ** not currently open in WAL mode.
105294 **
105295 ** If a transaction is open on the database being checkpointed, this 
105296 ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If 
105297 ** an error occurs while running the checkpoint, an SQLite error code is 
105298 ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
105299 **
105300 ** The mutex on database handle db should be held by the caller. The mutex
105301 ** associated with the specific b-tree being checkpointed is taken by
105302 ** this function while the checkpoint is running.
105303 **
105304 ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
105305 ** checkpointed. If an error is encountered it is returned immediately -
105306 ** no attempt is made to checkpoint any remaining databases.
105307 */
105308 SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb){
105309   int rc = SQLITE_OK;             /* Return code */
105310   int i;                          /* Used to iterate through attached dbs */
105311
105312   assert( sqlite3_mutex_held(db->mutex) );
105313
105314   for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
105315     if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
105316       rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt);
105317     }
105318   }
105319
105320   return rc;
105321 }
105322 #endif /* SQLITE_OMIT_WAL */
105323
105324 /*
105325 ** This function returns true if main-memory should be used instead of
105326 ** a temporary file for transient pager files and statement journals.
105327 ** The value returned depends on the value of db->temp_store (runtime
105328 ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
105329 ** following table describes the relationship between these two values
105330 ** and this functions return value.
105331 **
105332 **   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
105333 **   -----------------     --------------     ------------------------------
105334 **   0                     any                file      (return 0)
105335 **   1                     1                  file      (return 0)
105336 **   1                     2                  memory    (return 1)
105337 **   1                     0                  file      (return 0)
105338 **   2                     1                  file      (return 0)
105339 **   2                     2                  memory    (return 1)
105340 **   2                     0                  memory    (return 1)
105341 **   3                     any                memory    (return 1)
105342 */
105343 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
105344 #if SQLITE_TEMP_STORE==1
105345   return ( db->temp_store==2 );
105346 #endif
105347 #if SQLITE_TEMP_STORE==2
105348   return ( db->temp_store!=1 );
105349 #endif
105350 #if SQLITE_TEMP_STORE==3
105351   return 1;
105352 #endif
105353 #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
105354   return 0;
105355 #endif
105356 }
105357
105358 /*
105359 ** Return UTF-8 encoded English language explanation of the most recent
105360 ** error.
105361 */
105362 SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
105363   const char *z;
105364   if( !db ){
105365     return sqlite3ErrStr(SQLITE_NOMEM);
105366   }
105367   if( !sqlite3SafetyCheckSickOrOk(db) ){
105368     return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
105369   }
105370   sqlite3_mutex_enter(db->mutex);
105371   if( db->mallocFailed ){
105372     z = sqlite3ErrStr(SQLITE_NOMEM);
105373   }else{
105374     z = (char*)sqlite3_value_text(db->pErr);
105375     assert( !db->mallocFailed );
105376     if( z==0 ){
105377       z = sqlite3ErrStr(db->errCode);
105378     }
105379   }
105380   sqlite3_mutex_leave(db->mutex);
105381   return z;
105382 }
105383
105384 #ifndef SQLITE_OMIT_UTF16
105385 /*
105386 ** Return UTF-16 encoded English language explanation of the most recent
105387 ** error.
105388 */
105389 SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
105390   static const u16 outOfMem[] = {
105391     'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
105392   };
105393   static const u16 misuse[] = {
105394     'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ', 
105395     'r', 'o', 'u', 't', 'i', 'n', 'e', ' ', 
105396     'c', 'a', 'l', 'l', 'e', 'd', ' ', 
105397     'o', 'u', 't', ' ', 
105398     'o', 'f', ' ', 
105399     's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
105400   };
105401
105402   const void *z;
105403   if( !db ){
105404     return (void *)outOfMem;
105405   }
105406   if( !sqlite3SafetyCheckSickOrOk(db) ){
105407     return (void *)misuse;
105408   }
105409   sqlite3_mutex_enter(db->mutex);
105410   if( db->mallocFailed ){
105411     z = (void *)outOfMem;
105412   }else{
105413     z = sqlite3_value_text16(db->pErr);
105414     if( z==0 ){
105415       sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
105416            SQLITE_UTF8, SQLITE_STATIC);
105417       z = sqlite3_value_text16(db->pErr);
105418     }
105419     /* A malloc() may have failed within the call to sqlite3_value_text16()
105420     ** above. If this is the case, then the db->mallocFailed flag needs to
105421     ** be cleared before returning. Do this directly, instead of via
105422     ** sqlite3ApiExit(), to avoid setting the database handle error message.
105423     */
105424     db->mallocFailed = 0;
105425   }
105426   sqlite3_mutex_leave(db->mutex);
105427   return z;
105428 }
105429 #endif /* SQLITE_OMIT_UTF16 */
105430
105431 /*
105432 ** Return the most recent error code generated by an SQLite routine. If NULL is
105433 ** passed to this function, we assume a malloc() failed during sqlite3_open().
105434 */
105435 SQLITE_API int sqlite3_errcode(sqlite3 *db){
105436   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
105437     return SQLITE_MISUSE_BKPT;
105438   }
105439   if( !db || db->mallocFailed ){
105440     return SQLITE_NOMEM;
105441   }
105442   return db->errCode & db->errMask;
105443 }
105444 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
105445   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
105446     return SQLITE_MISUSE_BKPT;
105447   }
105448   if( !db || db->mallocFailed ){
105449     return SQLITE_NOMEM;
105450   }
105451   return db->errCode;
105452 }
105453
105454 /*
105455 ** Create a new collating function for database "db".  The name is zName
105456 ** and the encoding is enc.
105457 */
105458 static int createCollation(
105459   sqlite3* db,
105460   const char *zName, 
105461   u8 enc,
105462   u8 collType,
105463   void* pCtx,
105464   int(*xCompare)(void*,int,const void*,int,const void*),
105465   void(*xDel)(void*)
105466 ){
105467   CollSeq *pColl;
105468   int enc2;
105469   int nName = sqlite3Strlen30(zName);
105470   
105471   assert( sqlite3_mutex_held(db->mutex) );
105472
105473   /* If SQLITE_UTF16 is specified as the encoding type, transform this
105474   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
105475   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
105476   */
105477   enc2 = enc;
105478   testcase( enc2==SQLITE_UTF16 );
105479   testcase( enc2==SQLITE_UTF16_ALIGNED );
105480   if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
105481     enc2 = SQLITE_UTF16NATIVE;
105482   }
105483   if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
105484     return SQLITE_MISUSE_BKPT;
105485   }
105486
105487   /* Check if this call is removing or replacing an existing collation 
105488   ** sequence. If so, and there are active VMs, return busy. If there
105489   ** are no active VMs, invalidate any pre-compiled statements.
105490   */
105491   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
105492   if( pColl && pColl->xCmp ){
105493     if( db->activeVdbeCnt ){
105494       sqlite3Error(db, SQLITE_BUSY, 
105495         "unable to delete/modify collation sequence due to active statements");
105496       return SQLITE_BUSY;
105497     }
105498     sqlite3ExpirePreparedStatements(db);
105499
105500     /* If collation sequence pColl was created directly by a call to
105501     ** sqlite3_create_collation, and not generated by synthCollSeq(),
105502     ** then any copies made by synthCollSeq() need to be invalidated.
105503     ** Also, collation destructor - CollSeq.xDel() - function may need
105504     ** to be called.
105505     */ 
105506     if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
105507       CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
105508       int j;
105509       for(j=0; j<3; j++){
105510         CollSeq *p = &aColl[j];
105511         if( p->enc==pColl->enc ){
105512           if( p->xDel ){
105513             p->xDel(p->pUser);
105514           }
105515           p->xCmp = 0;
105516         }
105517       }
105518     }
105519   }
105520
105521   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
105522   if( pColl ){
105523     pColl->xCmp = xCompare;
105524     pColl->pUser = pCtx;
105525     pColl->xDel = xDel;
105526     pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
105527     pColl->type = collType;
105528   }
105529   sqlite3Error(db, SQLITE_OK, 0);
105530   return SQLITE_OK;
105531 }
105532
105533
105534 /*
105535 ** This array defines hard upper bounds on limit values.  The
105536 ** initializer must be kept in sync with the SQLITE_LIMIT_*
105537 ** #defines in sqlite3.h.
105538 */
105539 static const int aHardLimit[] = {
105540   SQLITE_MAX_LENGTH,
105541   SQLITE_MAX_SQL_LENGTH,
105542   SQLITE_MAX_COLUMN,
105543   SQLITE_MAX_EXPR_DEPTH,
105544   SQLITE_MAX_COMPOUND_SELECT,
105545   SQLITE_MAX_VDBE_OP,
105546   SQLITE_MAX_FUNCTION_ARG,
105547   SQLITE_MAX_ATTACHED,
105548   SQLITE_MAX_LIKE_PATTERN_LENGTH,
105549   SQLITE_MAX_VARIABLE_NUMBER,
105550   SQLITE_MAX_TRIGGER_DEPTH,
105551 };
105552
105553 /*
105554 ** Make sure the hard limits are set to reasonable values
105555 */
105556 #if SQLITE_MAX_LENGTH<100
105557 # error SQLITE_MAX_LENGTH must be at least 100
105558 #endif
105559 #if SQLITE_MAX_SQL_LENGTH<100
105560 # error SQLITE_MAX_SQL_LENGTH must be at least 100
105561 #endif
105562 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
105563 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
105564 #endif
105565 #if SQLITE_MAX_COMPOUND_SELECT<2
105566 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
105567 #endif
105568 #if SQLITE_MAX_VDBE_OP<40
105569 # error SQLITE_MAX_VDBE_OP must be at least 40
105570 #endif
105571 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
105572 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
105573 #endif
105574 #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>30
105575 # error SQLITE_MAX_ATTACHED must be between 0 and 30
105576 #endif
105577 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
105578 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
105579 #endif
105580 #if SQLITE_MAX_COLUMN>32767
105581 # error SQLITE_MAX_COLUMN must not exceed 32767
105582 #endif
105583 #if SQLITE_MAX_TRIGGER_DEPTH<1
105584 # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
105585 #endif
105586
105587
105588 /*
105589 ** Change the value of a limit.  Report the old value.
105590 ** If an invalid limit index is supplied, report -1.
105591 ** Make no changes but still report the old value if the
105592 ** new limit is negative.
105593 **
105594 ** A new lower limit does not shrink existing constructs.
105595 ** It merely prevents new constructs that exceed the limit
105596 ** from forming.
105597 */
105598 SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
105599   int oldLimit;
105600
105601
105602   /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
105603   ** there is a hard upper bound set at compile-time by a C preprocessor
105604   ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
105605   ** "_MAX_".)
105606   */
105607   assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
105608   assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
105609   assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
105610   assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
105611   assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
105612   assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
105613   assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
105614   assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
105615   assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
105616                                                SQLITE_MAX_LIKE_PATTERN_LENGTH );
105617   assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
105618   assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
105619   assert( SQLITE_LIMIT_TRIGGER_DEPTH==(SQLITE_N_LIMIT-1) );
105620
105621
105622   if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
105623     return -1;
105624   }
105625   oldLimit = db->aLimit[limitId];
105626   if( newLimit>=0 ){                   /* IMP: R-52476-28732 */
105627     if( newLimit>aHardLimit[limitId] ){
105628       newLimit = aHardLimit[limitId];  /* IMP: R-51463-25634 */
105629     }
105630     db->aLimit[limitId] = newLimit;
105631   }
105632   return oldLimit;                     /* IMP: R-53341-35419 */
105633 }
105634
105635 /*
105636 ** This routine does the work of opening a database on behalf of
105637 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"  
105638 ** is UTF-8 encoded.
105639 */
105640 static int openDatabase(
105641   const char *zFilename, /* Database filename UTF-8 encoded */
105642   sqlite3 **ppDb,        /* OUT: Returned database handle */
105643   unsigned flags,        /* Operational flags */
105644   const char *zVfs       /* Name of the VFS to use */
105645 ){
105646   sqlite3 *db;
105647   int rc;
105648   int isThreadsafe;
105649
105650   *ppDb = 0;
105651 #ifndef SQLITE_OMIT_AUTOINIT
105652   rc = sqlite3_initialize();
105653   if( rc ) return rc;
105654 #endif
105655
105656   /* Only allow sensible combinations of bits in the flags argument.  
105657   ** Throw an error if any non-sense combination is used.  If we
105658   ** do not block illegal combinations here, it could trigger
105659   ** assert() statements in deeper layers.  Sensible combinations
105660   ** are:
105661   **
105662   **  1:  SQLITE_OPEN_READONLY
105663   **  2:  SQLITE_OPEN_READWRITE
105664   **  6:  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
105665   */
105666   assert( SQLITE_OPEN_READONLY  == 0x01 );
105667   assert( SQLITE_OPEN_READWRITE == 0x02 );
105668   assert( SQLITE_OPEN_CREATE    == 0x04 );
105669   testcase( (1<<(flags&7))==0x02 ); /* READONLY */
105670   testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
105671   testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
105672   if( ((1<<(flags&7)) & 0x46)==0 ) return SQLITE_MISUSE;
105673
105674   if( sqlite3GlobalConfig.bCoreMutex==0 ){
105675     isThreadsafe = 0;
105676   }else if( flags & SQLITE_OPEN_NOMUTEX ){
105677     isThreadsafe = 0;
105678   }else if( flags & SQLITE_OPEN_FULLMUTEX ){
105679     isThreadsafe = 1;
105680   }else{
105681     isThreadsafe = sqlite3GlobalConfig.bFullMutex;
105682   }
105683   if( flags & SQLITE_OPEN_PRIVATECACHE ){
105684     flags &= ~SQLITE_OPEN_SHAREDCACHE;
105685   }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
105686     flags |= SQLITE_OPEN_SHAREDCACHE;
105687   }
105688
105689   /* Remove harmful bits from the flags parameter
105690   **
105691   ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
105692   ** dealt with in the previous code block.  Besides these, the only
105693   ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
105694   ** SQLITE_OPEN_READWRITE, and SQLITE_OPEN_CREATE.  Silently mask
105695   ** off all other flags.
105696   */
105697   flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
105698                SQLITE_OPEN_EXCLUSIVE |
105699                SQLITE_OPEN_MAIN_DB |
105700                SQLITE_OPEN_TEMP_DB | 
105701                SQLITE_OPEN_TRANSIENT_DB | 
105702                SQLITE_OPEN_MAIN_JOURNAL | 
105703                SQLITE_OPEN_TEMP_JOURNAL | 
105704                SQLITE_OPEN_SUBJOURNAL | 
105705                SQLITE_OPEN_MASTER_JOURNAL |
105706                SQLITE_OPEN_NOMUTEX |
105707                SQLITE_OPEN_FULLMUTEX |
105708                SQLITE_OPEN_WAL
105709              );
105710
105711   /* Allocate the sqlite data structure */
105712   db = sqlite3MallocZero( sizeof(sqlite3) );
105713   if( db==0 ) goto opendb_out;
105714   if( isThreadsafe ){
105715     db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
105716     if( db->mutex==0 ){
105717       sqlite3_free(db);
105718       db = 0;
105719       goto opendb_out;
105720     }
105721   }
105722   sqlite3_mutex_enter(db->mutex);
105723   db->errMask = 0xff;
105724   db->nDb = 2;
105725   db->magic = SQLITE_MAGIC_BUSY;
105726   db->aDb = db->aDbStatic;
105727
105728   assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
105729   memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
105730   db->autoCommit = 1;
105731   db->nextAutovac = -1;
105732   db->nextPagesize = 0;
105733   db->flags |= SQLITE_ShortColNames | SQLITE_AutoIndex
105734 #if SQLITE_DEFAULT_FILE_FORMAT<4
105735                  | SQLITE_LegacyFileFmt
105736 #endif
105737 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
105738                  | SQLITE_LoadExtension
105739 #endif
105740 #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
105741                  | SQLITE_RecTriggers
105742 #endif
105743       ;
105744   sqlite3HashInit(&db->aCollSeq);
105745 #ifndef SQLITE_OMIT_VIRTUALTABLE
105746   sqlite3HashInit(&db->aModule);
105747 #endif
105748
105749   db->pVfs = sqlite3_vfs_find(zVfs);
105750   if( !db->pVfs ){
105751     rc = SQLITE_ERROR;
105752     sqlite3Error(db, rc, "no such vfs: %s", zVfs);
105753     goto opendb_out;
105754   }
105755
105756   /* Add the default collation sequence BINARY. BINARY works for both UTF-8
105757   ** and UTF-16, so add a version for each to avoid any unnecessary
105758   ** conversions. The only error that can occur here is a malloc() failure.
105759   */
105760   createCollation(db, "BINARY", SQLITE_UTF8, SQLITE_COLL_BINARY, 0,
105761                   binCollFunc, 0);
105762   createCollation(db, "BINARY", SQLITE_UTF16BE, SQLITE_COLL_BINARY, 0,
105763                   binCollFunc, 0);
105764   createCollation(db, "BINARY", SQLITE_UTF16LE, SQLITE_COLL_BINARY, 0,
105765                   binCollFunc, 0);
105766   createCollation(db, "RTRIM", SQLITE_UTF8, SQLITE_COLL_USER, (void*)1,
105767                   binCollFunc, 0);
105768   if( db->mallocFailed ){
105769     goto opendb_out;
105770   }
105771   db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
105772   assert( db->pDfltColl!=0 );
105773
105774   /* Also add a UTF-8 case-insensitive collation sequence. */
105775   createCollation(db, "NOCASE", SQLITE_UTF8, SQLITE_COLL_NOCASE, 0,
105776                   nocaseCollatingFunc, 0);
105777
105778   /* Open the backend database driver */
105779   db->openFlags = flags;
105780   rc = sqlite3BtreeOpen(zFilename, db, &db->aDb[0].pBt, 0,
105781                         flags | SQLITE_OPEN_MAIN_DB);
105782   if( rc!=SQLITE_OK ){
105783     if( rc==SQLITE_IOERR_NOMEM ){
105784       rc = SQLITE_NOMEM;
105785     }
105786     sqlite3Error(db, rc, 0);
105787     goto opendb_out;
105788   }
105789   db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
105790   db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
105791
105792
105793   /* The default safety_level for the main database is 'full'; for the temp
105794   ** database it is 'NONE'. This matches the pager layer defaults.  
105795   */
105796   db->aDb[0].zName = "main";
105797   db->aDb[0].safety_level = 3;
105798   db->aDb[1].zName = "temp";
105799   db->aDb[1].safety_level = 1;
105800
105801   db->magic = SQLITE_MAGIC_OPEN;
105802   if( db->mallocFailed ){
105803     goto opendb_out;
105804   }
105805
105806   /* Register all built-in functions, but do not attempt to read the
105807   ** database schema yet. This is delayed until the first time the database
105808   ** is accessed.
105809   */
105810   sqlite3Error(db, SQLITE_OK, 0);
105811   sqlite3RegisterBuiltinFunctions(db);
105812
105813   /* Load automatic extensions - extensions that have been registered
105814   ** using the sqlite3_automatic_extension() API.
105815   */
105816   sqlite3AutoLoadExtensions(db);
105817   rc = sqlite3_errcode(db);
105818   if( rc!=SQLITE_OK ){
105819     goto opendb_out;
105820   }
105821
105822 #ifdef SQLITE_ENABLE_FTS1
105823   if( !db->mallocFailed ){
105824     extern int sqlite3Fts1Init(sqlite3*);
105825     rc = sqlite3Fts1Init(db);
105826   }
105827 #endif
105828
105829 #ifdef SQLITE_ENABLE_FTS2
105830   if( !db->mallocFailed && rc==SQLITE_OK ){
105831     extern int sqlite3Fts2Init(sqlite3*);
105832     rc = sqlite3Fts2Init(db);
105833   }
105834 #endif
105835
105836 #ifdef SQLITE_ENABLE_FTS3
105837   if( !db->mallocFailed && rc==SQLITE_OK ){
105838     rc = sqlite3Fts3Init(db);
105839   }
105840 #endif
105841
105842 #ifdef SQLITE_ENABLE_ICU
105843   if( !db->mallocFailed && rc==SQLITE_OK ){
105844     rc = sqlite3IcuInit(db);
105845   }
105846 #endif
105847
105848 #ifdef SQLITE_ENABLE_RTREE
105849   if( !db->mallocFailed && rc==SQLITE_OK){
105850     rc = sqlite3RtreeInit(db);
105851   }
105852 #endif
105853
105854   sqlite3Error(db, rc, 0);
105855
105856   /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
105857   ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
105858   ** mode.  Doing nothing at all also makes NORMAL the default.
105859   */
105860 #ifdef SQLITE_DEFAULT_LOCKING_MODE
105861   db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
105862   sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
105863                           SQLITE_DEFAULT_LOCKING_MODE);
105864 #endif
105865
105866   /* Enable the lookaside-malloc subsystem */
105867   setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
105868                         sqlite3GlobalConfig.nLookaside);
105869
105870   sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
105871
105872 opendb_out:
105873   if( db ){
105874     assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
105875     sqlite3_mutex_leave(db->mutex);
105876   }
105877   rc = sqlite3_errcode(db);
105878   if( rc==SQLITE_NOMEM ){
105879     sqlite3_close(db);
105880     db = 0;
105881   }else if( rc!=SQLITE_OK ){
105882     db->magic = SQLITE_MAGIC_SICK;
105883   }
105884   *ppDb = db;
105885   return sqlite3ApiExit(0, rc);
105886 }
105887
105888 /*
105889 ** Open a new database handle.
105890 */
105891 SQLITE_API int sqlite3_open(
105892   const char *zFilename, 
105893   sqlite3 **ppDb 
105894 ){
105895   return openDatabase(zFilename, ppDb,
105896                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
105897 }
105898 SQLITE_API int sqlite3_open_v2(
105899   const char *filename,   /* Database filename (UTF-8) */
105900   sqlite3 **ppDb,         /* OUT: SQLite db handle */
105901   int flags,              /* Flags */
105902   const char *zVfs        /* Name of VFS module to use */
105903 ){
105904   return openDatabase(filename, ppDb, flags, zVfs);
105905 }
105906
105907 #ifndef SQLITE_OMIT_UTF16
105908 /*
105909 ** Open a new database handle.
105910 */
105911 SQLITE_API int sqlite3_open16(
105912   const void *zFilename, 
105913   sqlite3 **ppDb
105914 ){
105915   char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
105916   sqlite3_value *pVal;
105917   int rc;
105918
105919   assert( zFilename );
105920   assert( ppDb );
105921   *ppDb = 0;
105922 #ifndef SQLITE_OMIT_AUTOINIT
105923   rc = sqlite3_initialize();
105924   if( rc ) return rc;
105925 #endif
105926   pVal = sqlite3ValueNew(0);
105927   sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
105928   zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
105929   if( zFilename8 ){
105930     rc = openDatabase(zFilename8, ppDb,
105931                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
105932     assert( *ppDb || rc==SQLITE_NOMEM );
105933     if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
105934       ENC(*ppDb) = SQLITE_UTF16NATIVE;
105935     }
105936   }else{
105937     rc = SQLITE_NOMEM;
105938   }
105939   sqlite3ValueFree(pVal);
105940
105941   return sqlite3ApiExit(0, rc);
105942 }
105943 #endif /* SQLITE_OMIT_UTF16 */
105944
105945 /*
105946 ** Register a new collation sequence with the database handle db.
105947 */
105948 SQLITE_API int sqlite3_create_collation(
105949   sqlite3* db, 
105950   const char *zName, 
105951   int enc, 
105952   void* pCtx,
105953   int(*xCompare)(void*,int,const void*,int,const void*)
105954 ){
105955   int rc;
105956   sqlite3_mutex_enter(db->mutex);
105957   assert( !db->mallocFailed );
105958   rc = createCollation(db, zName, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, 0);
105959   rc = sqlite3ApiExit(db, rc);
105960   sqlite3_mutex_leave(db->mutex);
105961   return rc;
105962 }
105963
105964 /*
105965 ** Register a new collation sequence with the database handle db.
105966 */
105967 SQLITE_API int sqlite3_create_collation_v2(
105968   sqlite3* db, 
105969   const char *zName, 
105970   int enc, 
105971   void* pCtx,
105972   int(*xCompare)(void*,int,const void*,int,const void*),
105973   void(*xDel)(void*)
105974 ){
105975   int rc;
105976   sqlite3_mutex_enter(db->mutex);
105977   assert( !db->mallocFailed );
105978   rc = createCollation(db, zName, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, xDel);
105979   rc = sqlite3ApiExit(db, rc);
105980   sqlite3_mutex_leave(db->mutex);
105981   return rc;
105982 }
105983
105984 #ifndef SQLITE_OMIT_UTF16
105985 /*
105986 ** Register a new collation sequence with the database handle db.
105987 */
105988 SQLITE_API int sqlite3_create_collation16(
105989   sqlite3* db, 
105990   const void *zName,
105991   int enc, 
105992   void* pCtx,
105993   int(*xCompare)(void*,int,const void*,int,const void*)
105994 ){
105995   int rc = SQLITE_OK;
105996   char *zName8;
105997   sqlite3_mutex_enter(db->mutex);
105998   assert( !db->mallocFailed );
105999   zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
106000   if( zName8 ){
106001     rc = createCollation(db, zName8, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, 0);
106002     sqlite3DbFree(db, zName8);
106003   }
106004   rc = sqlite3ApiExit(db, rc);
106005   sqlite3_mutex_leave(db->mutex);
106006   return rc;
106007 }
106008 #endif /* SQLITE_OMIT_UTF16 */
106009
106010 /*
106011 ** Register a collation sequence factory callback with the database handle
106012 ** db. Replace any previously installed collation sequence factory.
106013 */
106014 SQLITE_API int sqlite3_collation_needed(
106015   sqlite3 *db, 
106016   void *pCollNeededArg, 
106017   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
106018 ){
106019   sqlite3_mutex_enter(db->mutex);
106020   db->xCollNeeded = xCollNeeded;
106021   db->xCollNeeded16 = 0;
106022   db->pCollNeededArg = pCollNeededArg;
106023   sqlite3_mutex_leave(db->mutex);
106024   return SQLITE_OK;
106025 }
106026
106027 #ifndef SQLITE_OMIT_UTF16
106028 /*
106029 ** Register a collation sequence factory callback with the database handle
106030 ** db. Replace any previously installed collation sequence factory.
106031 */
106032 SQLITE_API int sqlite3_collation_needed16(
106033   sqlite3 *db, 
106034   void *pCollNeededArg, 
106035   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
106036 ){
106037   sqlite3_mutex_enter(db->mutex);
106038   db->xCollNeeded = 0;
106039   db->xCollNeeded16 = xCollNeeded16;
106040   db->pCollNeededArg = pCollNeededArg;
106041   sqlite3_mutex_leave(db->mutex);
106042   return SQLITE_OK;
106043 }
106044 #endif /* SQLITE_OMIT_UTF16 */
106045
106046 #ifndef SQLITE_OMIT_DEPRECATED
106047 /*
106048 ** This function is now an anachronism. It used to be used to recover from a
106049 ** malloc() failure, but SQLite now does this automatically.
106050 */
106051 SQLITE_API int sqlite3_global_recover(void){
106052   return SQLITE_OK;
106053 }
106054 #endif
106055
106056 /*
106057 ** Test to see whether or not the database connection is in autocommit
106058 ** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
106059 ** by default.  Autocommit is disabled by a BEGIN statement and reenabled
106060 ** by the next COMMIT or ROLLBACK.
106061 **
106062 ******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
106063 */
106064 SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
106065   return db->autoCommit;
106066 }
106067
106068 /*
106069 ** The following routines are subtitutes for constants SQLITE_CORRUPT,
106070 ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
106071 ** constants.  They server two purposes:
106072 **
106073 **   1.  Serve as a convenient place to set a breakpoint in a debugger
106074 **       to detect when version error conditions occurs.
106075 **
106076 **   2.  Invoke sqlite3_log() to provide the source code location where
106077 **       a low-level error is first detected.
106078 */
106079 SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
106080   testcase( sqlite3GlobalConfig.xLog!=0 );
106081   sqlite3_log(SQLITE_CORRUPT,
106082               "database corruption at line %d of [%.10s]",
106083               lineno, 20+sqlite3_sourceid());
106084   return SQLITE_CORRUPT;
106085 }
106086 SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
106087   testcase( sqlite3GlobalConfig.xLog!=0 );
106088   sqlite3_log(SQLITE_MISUSE, 
106089               "misuse at line %d of [%.10s]",
106090               lineno, 20+sqlite3_sourceid());
106091   return SQLITE_MISUSE;
106092 }
106093 SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
106094   testcase( sqlite3GlobalConfig.xLog!=0 );
106095   sqlite3_log(SQLITE_CANTOPEN, 
106096               "cannot open file at line %d of [%.10s]",
106097               lineno, 20+sqlite3_sourceid());
106098   return SQLITE_CANTOPEN;
106099 }
106100
106101
106102 #ifndef SQLITE_OMIT_DEPRECATED
106103 /*
106104 ** This is a convenience routine that makes sure that all thread-specific
106105 ** data for this thread has been deallocated.
106106 **
106107 ** SQLite no longer uses thread-specific data so this routine is now a
106108 ** no-op.  It is retained for historical compatibility.
106109 */
106110 SQLITE_API void sqlite3_thread_cleanup(void){
106111 }
106112 #endif
106113
106114 /*
106115 ** Return meta information about a specific column of a database table.
106116 ** See comment in sqlite3.h (sqlite.h.in) for details.
106117 */
106118 #ifdef SQLITE_ENABLE_COLUMN_METADATA
106119 SQLITE_API int sqlite3_table_column_metadata(
106120   sqlite3 *db,                /* Connection handle */
106121   const char *zDbName,        /* Database name or NULL */
106122   const char *zTableName,     /* Table name */
106123   const char *zColumnName,    /* Column name */
106124   char const **pzDataType,    /* OUTPUT: Declared data type */
106125   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
106126   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
106127   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
106128   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
106129 ){
106130   int rc;
106131   char *zErrMsg = 0;
106132   Table *pTab = 0;
106133   Column *pCol = 0;
106134   int iCol;
106135
106136   char const *zDataType = 0;
106137   char const *zCollSeq = 0;
106138   int notnull = 0;
106139   int primarykey = 0;
106140   int autoinc = 0;
106141
106142   /* Ensure the database schema has been loaded */
106143   sqlite3_mutex_enter(db->mutex);
106144   sqlite3BtreeEnterAll(db);
106145   rc = sqlite3Init(db, &zErrMsg);
106146   if( SQLITE_OK!=rc ){
106147     goto error_out;
106148   }
106149
106150   /* Locate the table in question */
106151   pTab = sqlite3FindTable(db, zTableName, zDbName);
106152   if( !pTab || pTab->pSelect ){
106153     pTab = 0;
106154     goto error_out;
106155   }
106156
106157   /* Find the column for which info is requested */
106158   if( sqlite3IsRowid(zColumnName) ){
106159     iCol = pTab->iPKey;
106160     if( iCol>=0 ){
106161       pCol = &pTab->aCol[iCol];
106162     }
106163   }else{
106164     for(iCol=0; iCol<pTab->nCol; iCol++){
106165       pCol = &pTab->aCol[iCol];
106166       if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
106167         break;
106168       }
106169     }
106170     if( iCol==pTab->nCol ){
106171       pTab = 0;
106172       goto error_out;
106173     }
106174   }
106175
106176   /* The following block stores the meta information that will be returned
106177   ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
106178   ** and autoinc. At this point there are two possibilities:
106179   ** 
106180   **     1. The specified column name was rowid", "oid" or "_rowid_" 
106181   **        and there is no explicitly declared IPK column. 
106182   **
106183   **     2. The table is not a view and the column name identified an 
106184   **        explicitly declared column. Copy meta information from *pCol.
106185   */ 
106186   if( pCol ){
106187     zDataType = pCol->zType;
106188     zCollSeq = pCol->zColl;
106189     notnull = pCol->notNull!=0;
106190     primarykey  = pCol->isPrimKey!=0;
106191     autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
106192   }else{
106193     zDataType = "INTEGER";
106194     primarykey = 1;
106195   }
106196   if( !zCollSeq ){
106197     zCollSeq = "BINARY";
106198   }
106199
106200 error_out:
106201   sqlite3BtreeLeaveAll(db);
106202
106203   /* Whether the function call succeeded or failed, set the output parameters
106204   ** to whatever their local counterparts contain. If an error did occur,
106205   ** this has the effect of zeroing all output parameters.
106206   */
106207   if( pzDataType ) *pzDataType = zDataType;
106208   if( pzCollSeq ) *pzCollSeq = zCollSeq;
106209   if( pNotNull ) *pNotNull = notnull;
106210   if( pPrimaryKey ) *pPrimaryKey = primarykey;
106211   if( pAutoinc ) *pAutoinc = autoinc;
106212
106213   if( SQLITE_OK==rc && !pTab ){
106214     sqlite3DbFree(db, zErrMsg);
106215     zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
106216         zColumnName);
106217     rc = SQLITE_ERROR;
106218   }
106219   sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
106220   sqlite3DbFree(db, zErrMsg);
106221   rc = sqlite3ApiExit(db, rc);
106222   sqlite3_mutex_leave(db->mutex);
106223   return rc;
106224 }
106225 #endif
106226
106227 /*
106228 ** Sleep for a little while.  Return the amount of time slept.
106229 */
106230 SQLITE_API int sqlite3_sleep(int ms){
106231   sqlite3_vfs *pVfs;
106232   int rc;
106233   pVfs = sqlite3_vfs_find(0);
106234   if( pVfs==0 ) return 0;
106235
106236   /* This function works in milliseconds, but the underlying OsSleep() 
106237   ** API uses microseconds. Hence the 1000's.
106238   */
106239   rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
106240   return rc;
106241 }
106242
106243 /*
106244 ** Enable or disable the extended result codes.
106245 */
106246 SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
106247   sqlite3_mutex_enter(db->mutex);
106248   db->errMask = onoff ? 0xffffffff : 0xff;
106249   sqlite3_mutex_leave(db->mutex);
106250   return SQLITE_OK;
106251 }
106252
106253 /*
106254 ** Invoke the xFileControl method on a particular database.
106255 */
106256 SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
106257   int rc = SQLITE_ERROR;
106258   int iDb;
106259   sqlite3_mutex_enter(db->mutex);
106260   if( zDbName==0 ){
106261     iDb = 0;
106262   }else{
106263     for(iDb=0; iDb<db->nDb; iDb++){
106264       if( strcmp(db->aDb[iDb].zName, zDbName)==0 ) break;
106265     }
106266   }
106267   if( iDb<db->nDb ){
106268     Btree *pBtree = db->aDb[iDb].pBt;
106269     if( pBtree ){
106270       Pager *pPager;
106271       sqlite3_file *fd;
106272       sqlite3BtreeEnter(pBtree);
106273       pPager = sqlite3BtreePager(pBtree);
106274       assert( pPager!=0 );
106275       fd = sqlite3PagerFile(pPager);
106276       assert( fd!=0 );
106277       if( fd->pMethods ){
106278         rc = sqlite3OsFileControl(fd, op, pArg);
106279       }
106280       sqlite3BtreeLeave(pBtree);
106281     }
106282   }
106283   sqlite3_mutex_leave(db->mutex);
106284   return rc;   
106285 }
106286
106287 /*
106288 ** Interface to the testing logic.
106289 */
106290 SQLITE_API int sqlite3_test_control(int op, ...){
106291   int rc = 0;
106292 #ifndef SQLITE_OMIT_BUILTIN_TEST
106293   va_list ap;
106294   va_start(ap, op);
106295   switch( op ){
106296
106297     /*
106298     ** Save the current state of the PRNG.
106299     */
106300     case SQLITE_TESTCTRL_PRNG_SAVE: {
106301       sqlite3PrngSaveState();
106302       break;
106303     }
106304
106305     /*
106306     ** Restore the state of the PRNG to the last state saved using
106307     ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
106308     ** this verb acts like PRNG_RESET.
106309     */
106310     case SQLITE_TESTCTRL_PRNG_RESTORE: {
106311       sqlite3PrngRestoreState();
106312       break;
106313     }
106314
106315     /*
106316     ** Reset the PRNG back to its uninitialized state.  The next call
106317     ** to sqlite3_randomness() will reseed the PRNG using a single call
106318     ** to the xRandomness method of the default VFS.
106319     */
106320     case SQLITE_TESTCTRL_PRNG_RESET: {
106321       sqlite3PrngResetState();
106322       break;
106323     }
106324
106325     /*
106326     **  sqlite3_test_control(BITVEC_TEST, size, program)
106327     **
106328     ** Run a test against a Bitvec object of size.  The program argument
106329     ** is an array of integers that defines the test.  Return -1 on a
106330     ** memory allocation error, 0 on success, or non-zero for an error.
106331     ** See the sqlite3BitvecBuiltinTest() for additional information.
106332     */
106333     case SQLITE_TESTCTRL_BITVEC_TEST: {
106334       int sz = va_arg(ap, int);
106335       int *aProg = va_arg(ap, int*);
106336       rc = sqlite3BitvecBuiltinTest(sz, aProg);
106337       break;
106338     }
106339
106340     /*
106341     **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
106342     **
106343     ** Register hooks to call to indicate which malloc() failures 
106344     ** are benign.
106345     */
106346     case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
106347       typedef void (*void_function)(void);
106348       void_function xBenignBegin;
106349       void_function xBenignEnd;
106350       xBenignBegin = va_arg(ap, void_function);
106351       xBenignEnd = va_arg(ap, void_function);
106352       sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
106353       break;
106354     }
106355
106356     /*
106357     **  sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
106358     **
106359     ** Set the PENDING byte to the value in the argument, if X>0.
106360     ** Make no changes if X==0.  Return the value of the pending byte
106361     ** as it existing before this routine was called.
106362     **
106363     ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
106364     ** an incompatible database file format.  Changing the PENDING byte
106365     ** while any database connection is open results in undefined and
106366     ** dileterious behavior.
106367     */
106368     case SQLITE_TESTCTRL_PENDING_BYTE: {
106369       rc = PENDING_BYTE;
106370 #ifndef SQLITE_OMIT_WSD
106371       {
106372         unsigned int newVal = va_arg(ap, unsigned int);
106373         if( newVal ) sqlite3PendingByte = newVal;
106374       }
106375 #endif
106376       break;
106377     }
106378
106379     /*
106380     **  sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
106381     **
106382     ** This action provides a run-time test to see whether or not
106383     ** assert() was enabled at compile-time.  If X is true and assert()
106384     ** is enabled, then the return value is true.  If X is true and
106385     ** assert() is disabled, then the return value is zero.  If X is
106386     ** false and assert() is enabled, then the assertion fires and the
106387     ** process aborts.  If X is false and assert() is disabled, then the
106388     ** return value is zero.
106389     */
106390     case SQLITE_TESTCTRL_ASSERT: {
106391       volatile int x = 0;
106392       assert( (x = va_arg(ap,int))!=0 );
106393       rc = x;
106394       break;
106395     }
106396
106397
106398     /*
106399     **  sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
106400     **
106401     ** This action provides a run-time test to see how the ALWAYS and
106402     ** NEVER macros were defined at compile-time.
106403     **
106404     ** The return value is ALWAYS(X).  
106405     **
106406     ** The recommended test is X==2.  If the return value is 2, that means
106407     ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
106408     ** default setting.  If the return value is 1, then ALWAYS() is either
106409     ** hard-coded to true or else it asserts if its argument is false.
106410     ** The first behavior (hard-coded to true) is the case if
106411     ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
106412     ** behavior (assert if the argument to ALWAYS() is false) is the case if
106413     ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
106414     **
106415     ** The run-time test procedure might look something like this:
106416     **
106417     **    if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
106418     **      // ALWAYS() and NEVER() are no-op pass-through macros
106419     **    }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
106420     **      // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
106421     **    }else{
106422     **      // ALWAYS(x) is a constant 1.  NEVER(x) is a constant 0.
106423     **    }
106424     */
106425     case SQLITE_TESTCTRL_ALWAYS: {
106426       int x = va_arg(ap,int);
106427       rc = ALWAYS(x);
106428       break;
106429     }
106430
106431     /*   sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
106432     **
106433     ** Set the nReserve size to N for the main database on the database
106434     ** connection db.
106435     */
106436     case SQLITE_TESTCTRL_RESERVE: {
106437       sqlite3 *db = va_arg(ap, sqlite3*);
106438       int x = va_arg(ap,int);
106439       sqlite3_mutex_enter(db->mutex);
106440       sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
106441       sqlite3_mutex_leave(db->mutex);
106442       break;
106443     }
106444
106445     /*  sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
106446     **
106447     ** Enable or disable various optimizations for testing purposes.  The 
106448     ** argument N is a bitmask of optimizations to be disabled.  For normal
106449     ** operation N should be 0.  The idea is that a test program (like the
106450     ** SQL Logic Test or SLT test module) can run the same SQL multiple times
106451     ** with various optimizations disabled to verify that the same answer
106452     ** is obtained in every case.
106453     */
106454     case SQLITE_TESTCTRL_OPTIMIZATIONS: {
106455       sqlite3 *db = va_arg(ap, sqlite3*);
106456       int x = va_arg(ap,int);
106457       db->flags = (x & SQLITE_OptMask) | (db->flags & ~SQLITE_OptMask);
106458       break;
106459     }
106460
106461 #ifdef SQLITE_N_KEYWORD
106462     /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
106463     **
106464     ** If zWord is a keyword recognized by the parser, then return the
106465     ** number of keywords.  Or if zWord is not a keyword, return 0.
106466     ** 
106467     ** This test feature is only available in the amalgamation since
106468     ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
106469     ** is built using separate source files.
106470     */
106471     case SQLITE_TESTCTRL_ISKEYWORD: {
106472       const char *zWord = va_arg(ap, const char*);
106473       int n = sqlite3Strlen30(zWord);
106474       rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
106475       break;
106476     }
106477 #endif 
106478
106479     /* sqlite3_test_control(SQLITE_TESTCTRL_PGHDRSZ)
106480     **
106481     ** Return the size of a pcache header in bytes.
106482     */
106483     case SQLITE_TESTCTRL_PGHDRSZ: {
106484       rc = sizeof(PgHdr);
106485       break;
106486     }
106487
106488     /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
106489     **
106490     ** Pass pFree into sqlite3ScratchFree(). 
106491     ** If sz>0 then allocate a scratch buffer into pNew.  
106492     */
106493     case SQLITE_TESTCTRL_SCRATCHMALLOC: {
106494       void *pFree, **ppNew;
106495       int sz;
106496       sz = va_arg(ap, int);
106497       ppNew = va_arg(ap, void**);
106498       pFree = va_arg(ap, void*);
106499       if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
106500       sqlite3ScratchFree(pFree);
106501       break;
106502     }
106503
106504   }
106505   va_end(ap);
106506 #endif /* SQLITE_OMIT_BUILTIN_TEST */
106507   return rc;
106508 }
106509
106510 /************** End of main.c ************************************************/
106511 /************** Begin file notify.c ******************************************/
106512 /*
106513 ** 2009 March 3
106514 **
106515 ** The author disclaims copyright to this source code.  In place of
106516 ** a legal notice, here is a blessing:
106517 **
106518 **    May you do good and not evil.
106519 **    May you find forgiveness for yourself and forgive others.
106520 **    May you share freely, never taking more than you give.
106521 **
106522 *************************************************************************
106523 **
106524 ** This file contains the implementation of the sqlite3_unlock_notify()
106525 ** API method and its associated functionality.
106526 */
106527
106528 /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
106529 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
106530
106531 /*
106532 ** Public interfaces:
106533 **
106534 **   sqlite3ConnectionBlocked()
106535 **   sqlite3ConnectionUnlocked()
106536 **   sqlite3ConnectionClosed()
106537 **   sqlite3_unlock_notify()
106538 */
106539
106540 #define assertMutexHeld() \
106541   assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
106542
106543 /*
106544 ** Head of a linked list of all sqlite3 objects created by this process
106545 ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
106546 ** is not NULL. This variable may only accessed while the STATIC_MASTER
106547 ** mutex is held.
106548 */
106549 static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
106550
106551 #ifndef NDEBUG
106552 /*
106553 ** This function is a complex assert() that verifies the following 
106554 ** properties of the blocked connections list:
106555 **
106556 **   1) Each entry in the list has a non-NULL value for either 
106557 **      pUnlockConnection or pBlockingConnection, or both.
106558 **
106559 **   2) All entries in the list that share a common value for 
106560 **      xUnlockNotify are grouped together.
106561 **
106562 **   3) If the argument db is not NULL, then none of the entries in the
106563 **      blocked connections list have pUnlockConnection or pBlockingConnection
106564 **      set to db. This is used when closing connection db.
106565 */
106566 static void checkListProperties(sqlite3 *db){
106567   sqlite3 *p;
106568   for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
106569     int seen = 0;
106570     sqlite3 *p2;
106571
106572     /* Verify property (1) */
106573     assert( p->pUnlockConnection || p->pBlockingConnection );
106574
106575     /* Verify property (2) */
106576     for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
106577       if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
106578       assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
106579       assert( db==0 || p->pUnlockConnection!=db );
106580       assert( db==0 || p->pBlockingConnection!=db );
106581     }
106582   }
106583 }
106584 #else
106585 # define checkListProperties(x)
106586 #endif
106587
106588 /*
106589 ** Remove connection db from the blocked connections list. If connection
106590 ** db is not currently a part of the list, this function is a no-op.
106591 */
106592 static void removeFromBlockedList(sqlite3 *db){
106593   sqlite3 **pp;
106594   assertMutexHeld();
106595   for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
106596     if( *pp==db ){
106597       *pp = (*pp)->pNextBlocked;
106598       break;
106599     }
106600   }
106601 }
106602
106603 /*
106604 ** Add connection db to the blocked connections list. It is assumed
106605 ** that it is not already a part of the list.
106606 */
106607 static void addToBlockedList(sqlite3 *db){
106608   sqlite3 **pp;
106609   assertMutexHeld();
106610   for(
106611     pp=&sqlite3BlockedList; 
106612     *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify; 
106613     pp=&(*pp)->pNextBlocked
106614   );
106615   db->pNextBlocked = *pp;
106616   *pp = db;
106617 }
106618
106619 /*
106620 ** Obtain the STATIC_MASTER mutex.
106621 */
106622 static void enterMutex(void){
106623   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
106624   checkListProperties(0);
106625 }
106626
106627 /*
106628 ** Release the STATIC_MASTER mutex.
106629 */
106630 static void leaveMutex(void){
106631   assertMutexHeld();
106632   checkListProperties(0);
106633   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
106634 }
106635
106636 /*
106637 ** Register an unlock-notify callback.
106638 **
106639 ** This is called after connection "db" has attempted some operation
106640 ** but has received an SQLITE_LOCKED error because another connection
106641 ** (call it pOther) in the same process was busy using the same shared
106642 ** cache.  pOther is found by looking at db->pBlockingConnection.
106643 **
106644 ** If there is no blocking connection, the callback is invoked immediately,
106645 ** before this routine returns.
106646 **
106647 ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
106648 ** a deadlock.
106649 **
106650 ** Otherwise, make arrangements to invoke xNotify when pOther drops
106651 ** its locks.
106652 **
106653 ** Each call to this routine overrides any prior callbacks registered
106654 ** on the same "db".  If xNotify==0 then any prior callbacks are immediately
106655 ** cancelled.
106656 */
106657 SQLITE_API int sqlite3_unlock_notify(
106658   sqlite3 *db,
106659   void (*xNotify)(void **, int),
106660   void *pArg
106661 ){
106662   int rc = SQLITE_OK;
106663
106664   sqlite3_mutex_enter(db->mutex);
106665   enterMutex();
106666
106667   if( xNotify==0 ){
106668     removeFromBlockedList(db);
106669     db->pBlockingConnection = 0;
106670     db->pUnlockConnection = 0;
106671     db->xUnlockNotify = 0;
106672     db->pUnlockArg = 0;
106673   }else if( 0==db->pBlockingConnection ){
106674     /* The blocking transaction has been concluded. Or there never was a 
106675     ** blocking transaction. In either case, invoke the notify callback
106676     ** immediately. 
106677     */
106678     xNotify(&pArg, 1);
106679   }else{
106680     sqlite3 *p;
106681
106682     for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
106683     if( p ){
106684       rc = SQLITE_LOCKED;              /* Deadlock detected. */
106685     }else{
106686       db->pUnlockConnection = db->pBlockingConnection;
106687       db->xUnlockNotify = xNotify;
106688       db->pUnlockArg = pArg;
106689       removeFromBlockedList(db);
106690       addToBlockedList(db);
106691     }
106692   }
106693
106694   leaveMutex();
106695   assert( !db->mallocFailed );
106696   sqlite3Error(db, rc, (rc?"database is deadlocked":0));
106697   sqlite3_mutex_leave(db->mutex);
106698   return rc;
106699 }
106700
106701 /*
106702 ** This function is called while stepping or preparing a statement 
106703 ** associated with connection db. The operation will return SQLITE_LOCKED
106704 ** to the user because it requires a lock that will not be available
106705 ** until connection pBlocker concludes its current transaction.
106706 */
106707 SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
106708   enterMutex();
106709   if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
106710     addToBlockedList(db);
106711   }
106712   db->pBlockingConnection = pBlocker;
106713   leaveMutex();
106714 }
106715
106716 /*
106717 ** This function is called when
106718 ** the transaction opened by database db has just finished. Locks held 
106719 ** by database connection db have been released.
106720 **
106721 ** This function loops through each entry in the blocked connections
106722 ** list and does the following:
106723 **
106724 **   1) If the sqlite3.pBlockingConnection member of a list entry is
106725 **      set to db, then set pBlockingConnection=0.
106726 **
106727 **   2) If the sqlite3.pUnlockConnection member of a list entry is
106728 **      set to db, then invoke the configured unlock-notify callback and
106729 **      set pUnlockConnection=0.
106730 **
106731 **   3) If the two steps above mean that pBlockingConnection==0 and
106732 **      pUnlockConnection==0, remove the entry from the blocked connections
106733 **      list.
106734 */
106735 SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
106736   void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
106737   int nArg = 0;                            /* Number of entries in aArg[] */
106738   sqlite3 **pp;                            /* Iterator variable */
106739   void **aArg;               /* Arguments to the unlock callback */
106740   void **aDyn = 0;           /* Dynamically allocated space for aArg[] */
106741   void *aStatic[16];         /* Starter space for aArg[].  No malloc required */
106742
106743   aArg = aStatic;
106744   enterMutex();         /* Enter STATIC_MASTER mutex */
106745
106746   /* This loop runs once for each entry in the blocked-connections list. */
106747   for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
106748     sqlite3 *p = *pp;
106749
106750     /* Step 1. */
106751     if( p->pBlockingConnection==db ){
106752       p->pBlockingConnection = 0;
106753     }
106754
106755     /* Step 2. */
106756     if( p->pUnlockConnection==db ){
106757       assert( p->xUnlockNotify );
106758       if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
106759         xUnlockNotify(aArg, nArg);
106760         nArg = 0;
106761       }
106762
106763       sqlite3BeginBenignMalloc();
106764       assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
106765       assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
106766       if( (!aDyn && nArg==(int)ArraySize(aStatic))
106767        || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
106768       ){
106769         /* The aArg[] array needs to grow. */
106770         void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
106771         if( pNew ){
106772           memcpy(pNew, aArg, nArg*sizeof(void *));
106773           sqlite3_free(aDyn);
106774           aDyn = aArg = pNew;
106775         }else{
106776           /* This occurs when the array of context pointers that need to
106777           ** be passed to the unlock-notify callback is larger than the
106778           ** aStatic[] array allocated on the stack and the attempt to 
106779           ** allocate a larger array from the heap has failed.
106780           **
106781           ** This is a difficult situation to handle. Returning an error
106782           ** code to the caller is insufficient, as even if an error code
106783           ** is returned the transaction on connection db will still be
106784           ** closed and the unlock-notify callbacks on blocked connections
106785           ** will go unissued. This might cause the application to wait
106786           ** indefinitely for an unlock-notify callback that will never 
106787           ** arrive.
106788           **
106789           ** Instead, invoke the unlock-notify callback with the context
106790           ** array already accumulated. We can then clear the array and
106791           ** begin accumulating any further context pointers without 
106792           ** requiring any dynamic allocation. This is sub-optimal because
106793           ** it means that instead of one callback with a large array of
106794           ** context pointers the application will receive two or more
106795           ** callbacks with smaller arrays of context pointers, which will
106796           ** reduce the applications ability to prioritize multiple 
106797           ** connections. But it is the best that can be done under the
106798           ** circumstances.
106799           */
106800           xUnlockNotify(aArg, nArg);
106801           nArg = 0;
106802         }
106803       }
106804       sqlite3EndBenignMalloc();
106805
106806       aArg[nArg++] = p->pUnlockArg;
106807       xUnlockNotify = p->xUnlockNotify;
106808       p->pUnlockConnection = 0;
106809       p->xUnlockNotify = 0;
106810       p->pUnlockArg = 0;
106811     }
106812
106813     /* Step 3. */
106814     if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
106815       /* Remove connection p from the blocked connections list. */
106816       *pp = p->pNextBlocked;
106817       p->pNextBlocked = 0;
106818     }else{
106819       pp = &p->pNextBlocked;
106820     }
106821   }
106822
106823   if( nArg!=0 ){
106824     xUnlockNotify(aArg, nArg);
106825   }
106826   sqlite3_free(aDyn);
106827   leaveMutex();         /* Leave STATIC_MASTER mutex */
106828 }
106829
106830 /*
106831 ** This is called when the database connection passed as an argument is 
106832 ** being closed. The connection is removed from the blocked list.
106833 */
106834 SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
106835   sqlite3ConnectionUnlocked(db);
106836   enterMutex();
106837   removeFromBlockedList(db);
106838   checkListProperties(db);
106839   leaveMutex();
106840 }
106841 #endif
106842
106843 /************** End of notify.c **********************************************/
106844 /************** Begin file fts3.c ********************************************/
106845 /*
106846 ** 2006 Oct 10
106847 **
106848 ** The author disclaims copyright to this source code.  In place of
106849 ** a legal notice, here is a blessing:
106850 **
106851 **    May you do good and not evil.
106852 **    May you find forgiveness for yourself and forgive others.
106853 **    May you share freely, never taking more than you give.
106854 **
106855 ******************************************************************************
106856 **
106857 ** This is an SQLite module implementing full-text search.
106858 */
106859
106860 /*
106861 ** The code in this file is only compiled if:
106862 **
106863 **     * The FTS3 module is being built as an extension
106864 **       (in which case SQLITE_CORE is not defined), or
106865 **
106866 **     * The FTS3 module is being built into the core of
106867 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
106868 */
106869
106870 /* The full-text index is stored in a series of b+tree (-like)
106871 ** structures called segments which map terms to doclists.  The
106872 ** structures are like b+trees in layout, but are constructed from the
106873 ** bottom up in optimal fashion and are not updatable.  Since trees
106874 ** are built from the bottom up, things will be described from the
106875 ** bottom up.
106876 **
106877 **
106878 **** Varints ****
106879 ** The basic unit of encoding is a variable-length integer called a
106880 ** varint.  We encode variable-length integers in little-endian order
106881 ** using seven bits * per byte as follows:
106882 **
106883 ** KEY:
106884 **         A = 0xxxxxxx    7 bits of data and one flag bit
106885 **         B = 1xxxxxxx    7 bits of data and one flag bit
106886 **
106887 **  7 bits - A
106888 ** 14 bits - BA
106889 ** 21 bits - BBA
106890 ** and so on.
106891 **
106892 ** This is similar in concept to how sqlite encodes "varints" but
106893 ** the encoding is not the same.  SQLite varints are big-endian
106894 ** are are limited to 9 bytes in length whereas FTS3 varints are
106895 ** little-endian and can be up to 10 bytes in length (in theory).
106896 **
106897 ** Example encodings:
106898 **
106899 **     1:    0x01
106900 **   127:    0x7f
106901 **   128:    0x81 0x00
106902 **
106903 **
106904 **** Document lists ****
106905 ** A doclist (document list) holds a docid-sorted list of hits for a
106906 ** given term.  Doclists hold docids and associated token positions.
106907 ** A docid is the unique integer identifier for a single document.
106908 ** A position is the index of a word within the document.  The first 
106909 ** word of the document has a position of 0.
106910 **
106911 ** FTS3 used to optionally store character offsets using a compile-time
106912 ** option.  But that functionality is no longer supported.
106913 **
106914 ** A doclist is stored like this:
106915 **
106916 ** array {
106917 **   varint docid;
106918 **   array {                (position list for column 0)
106919 **     varint position;     (2 more than the delta from previous position)
106920 **   }
106921 **   array {
106922 **     varint POS_COLUMN;   (marks start of position list for new column)
106923 **     varint column;       (index of new column)
106924 **     array {
106925 **       varint position;   (2 more than the delta from previous position)
106926 **     }
106927 **   }
106928 **   varint POS_END;        (marks end of positions for this document.
106929 ** }
106930 **
106931 ** Here, array { X } means zero or more occurrences of X, adjacent in
106932 ** memory.  A "position" is an index of a token in the token stream
106933 ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur 
106934 ** in the same logical place as the position element, and act as sentinals
106935 ** ending a position list array.  POS_END is 0.  POS_COLUMN is 1.
106936 ** The positions numbers are not stored literally but rather as two more
106937 ** than the difference from the prior position, or the just the position plus
106938 ** 2 for the first position.  Example:
106939 **
106940 **   label:       A B C D E  F  G H   I  J K
106941 **   value:     123 5 9 1 1 14 35 0 234 72 0
106942 **
106943 ** The 123 value is the first docid.  For column zero in this document
106944 ** there are two matches at positions 3 and 10 (5-2 and 9-2+3).  The 1
106945 ** at D signals the start of a new column; the 1 at E indicates that the
106946 ** new column is column number 1.  There are two positions at 12 and 45
106947 ** (14-2 and 35-2+12).  The 0 at H indicate the end-of-document.  The
106948 ** 234 at I is the next docid.  It has one position 72 (72-2) and then
106949 ** terminates with the 0 at K.
106950 **
106951 ** A "position-list" is the list of positions for multiple columns for
106952 ** a single docid.  A "column-list" is the set of positions for a single
106953 ** column.  Hence, a position-list consists of one or more column-lists,
106954 ** a document record consists of a docid followed by a position-list and
106955 ** a doclist consists of one or more document records.
106956 **
106957 ** A bare doclist omits the position information, becoming an 
106958 ** array of varint-encoded docids.
106959 **
106960 **** Segment leaf nodes ****
106961 ** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
106962 ** nodes are written using LeafWriter, and read using LeafReader (to
106963 ** iterate through a single leaf node's data) and LeavesReader (to
106964 ** iterate through a segment's entire leaf layer).  Leaf nodes have
106965 ** the format:
106966 **
106967 ** varint iHeight;             (height from leaf level, always 0)
106968 ** varint nTerm;               (length of first term)
106969 ** char pTerm[nTerm];          (content of first term)
106970 ** varint nDoclist;            (length of term's associated doclist)
106971 ** char pDoclist[nDoclist];    (content of doclist)
106972 ** array {
106973 **                             (further terms are delta-encoded)
106974 **   varint nPrefix;           (length of prefix shared with previous term)
106975 **   varint nSuffix;           (length of unshared suffix)
106976 **   char pTermSuffix[nSuffix];(unshared suffix of next term)
106977 **   varint nDoclist;          (length of term's associated doclist)
106978 **   char pDoclist[nDoclist];  (content of doclist)
106979 ** }
106980 **
106981 ** Here, array { X } means zero or more occurrences of X, adjacent in
106982 ** memory.
106983 **
106984 ** Leaf nodes are broken into blocks which are stored contiguously in
106985 ** the %_segments table in sorted order.  This means that when the end
106986 ** of a node is reached, the next term is in the node with the next
106987 ** greater node id.
106988 **
106989 ** New data is spilled to a new leaf node when the current node
106990 ** exceeds LEAF_MAX bytes (default 2048).  New data which itself is
106991 ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
106992 ** node (a leaf node with a single term and doclist).  The goal of
106993 ** these settings is to pack together groups of small doclists while
106994 ** making it efficient to directly access large doclists.  The
106995 ** assumption is that large doclists represent terms which are more
106996 ** likely to be query targets.
106997 **
106998 ** TODO(shess) It may be useful for blocking decisions to be more
106999 ** dynamic.  For instance, it may make more sense to have a 2.5k leaf
107000 ** node rather than splitting into 2k and .5k nodes.  My intuition is
107001 ** that this might extend through 2x or 4x the pagesize.
107002 **
107003 **
107004 **** Segment interior nodes ****
107005 ** Segment interior nodes store blockids for subtree nodes and terms
107006 ** to describe what data is stored by the each subtree.  Interior
107007 ** nodes are written using InteriorWriter, and read using
107008 ** InteriorReader.  InteriorWriters are created as needed when
107009 ** SegmentWriter creates new leaf nodes, or when an interior node
107010 ** itself grows too big and must be split.  The format of interior
107011 ** nodes:
107012 **
107013 ** varint iHeight;           (height from leaf level, always >0)
107014 ** varint iBlockid;          (block id of node's leftmost subtree)
107015 ** optional {
107016 **   varint nTerm;           (length of first term)
107017 **   char pTerm[nTerm];      (content of first term)
107018 **   array {
107019 **                                (further terms are delta-encoded)
107020 **     varint nPrefix;            (length of shared prefix with previous term)
107021 **     varint nSuffix;            (length of unshared suffix)
107022 **     char pTermSuffix[nSuffix]; (unshared suffix of next term)
107023 **   }
107024 ** }
107025 **
107026 ** Here, optional { X } means an optional element, while array { X }
107027 ** means zero or more occurrences of X, adjacent in memory.
107028 **
107029 ** An interior node encodes n terms separating n+1 subtrees.  The
107030 ** subtree blocks are contiguous, so only the first subtree's blockid
107031 ** is encoded.  The subtree at iBlockid will contain all terms less
107032 ** than the first term encoded (or all terms if no term is encoded).
107033 ** Otherwise, for terms greater than or equal to pTerm[i] but less
107034 ** than pTerm[i+1], the subtree for that term will be rooted at
107035 ** iBlockid+i.  Interior nodes only store enough term data to
107036 ** distinguish adjacent children (if the rightmost term of the left
107037 ** child is "something", and the leftmost term of the right child is
107038 ** "wicked", only "w" is stored).
107039 **
107040 ** New data is spilled to a new interior node at the same height when
107041 ** the current node exceeds INTERIOR_MAX bytes (default 2048).
107042 ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
107043 ** interior nodes and making the tree too skinny.  The interior nodes
107044 ** at a given height are naturally tracked by interior nodes at
107045 ** height+1, and so on.
107046 **
107047 **
107048 **** Segment directory ****
107049 ** The segment directory in table %_segdir stores meta-information for
107050 ** merging and deleting segments, and also the root node of the
107051 ** segment's tree.
107052 **
107053 ** The root node is the top node of the segment's tree after encoding
107054 ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
107055 ** This could be either a leaf node or an interior node.  If the top
107056 ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
107057 ** and a new root interior node is generated (which should always fit
107058 ** within ROOT_MAX because it only needs space for 2 varints, the
107059 ** height and the blockid of the previous root).
107060 **
107061 ** The meta-information in the segment directory is:
107062 **   level               - segment level (see below)
107063 **   idx                 - index within level
107064 **                       - (level,idx uniquely identify a segment)
107065 **   start_block         - first leaf node
107066 **   leaves_end_block    - last leaf node
107067 **   end_block           - last block (including interior nodes)
107068 **   root                - contents of root node
107069 **
107070 ** If the root node is a leaf node, then start_block,
107071 ** leaves_end_block, and end_block are all 0.
107072 **
107073 **
107074 **** Segment merging ****
107075 ** To amortize update costs, segments are grouped into levels and
107076 ** merged in batches.  Each increase in level represents exponentially
107077 ** more documents.
107078 **
107079 ** New documents (actually, document updates) are tokenized and
107080 ** written individually (using LeafWriter) to a level 0 segment, with
107081 ** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all
107082 ** level 0 segments are merged into a single level 1 segment.  Level 1
107083 ** is populated like level 0, and eventually MERGE_COUNT level 1
107084 ** segments are merged to a single level 2 segment (representing
107085 ** MERGE_COUNT^2 updates), and so on.
107086 **
107087 ** A segment merge traverses all segments at a given level in
107088 ** parallel, performing a straightforward sorted merge.  Since segment
107089 ** leaf nodes are written in to the %_segments table in order, this
107090 ** merge traverses the underlying sqlite disk structures efficiently.
107091 ** After the merge, all segment blocks from the merged level are
107092 ** deleted.
107093 **
107094 ** MERGE_COUNT controls how often we merge segments.  16 seems to be
107095 ** somewhat of a sweet spot for insertion performance.  32 and 64 show
107096 ** very similar performance numbers to 16 on insertion, though they're
107097 ** a tiny bit slower (perhaps due to more overhead in merge-time
107098 ** sorting).  8 is about 20% slower than 16, 4 about 50% slower than
107099 ** 16, 2 about 66% slower than 16.
107100 **
107101 ** At query time, high MERGE_COUNT increases the number of segments
107102 ** which need to be scanned and merged.  For instance, with 100k docs
107103 ** inserted:
107104 **
107105 **    MERGE_COUNT   segments
107106 **       16           25
107107 **        8           12
107108 **        4           10
107109 **        2            6
107110 **
107111 ** This appears to have only a moderate impact on queries for very
107112 ** frequent terms (which are somewhat dominated by segment merge
107113 ** costs), and infrequent and non-existent terms still seem to be fast
107114 ** even with many segments.
107115 **
107116 ** TODO(shess) That said, it would be nice to have a better query-side
107117 ** argument for MERGE_COUNT of 16.  Also, it is possible/likely that
107118 ** optimizations to things like doclist merging will swing the sweet
107119 ** spot around.
107120 **
107121 **
107122 **
107123 **** Handling of deletions and updates ****
107124 ** Since we're using a segmented structure, with no docid-oriented
107125 ** index into the term index, we clearly cannot simply update the term
107126 ** index when a document is deleted or updated.  For deletions, we
107127 ** write an empty doclist (varint(docid) varint(POS_END)), for updates
107128 ** we simply write the new doclist.  Segment merges overwrite older
107129 ** data for a particular docid with newer data, so deletes or updates
107130 ** will eventually overtake the earlier data and knock it out.  The
107131 ** query logic likewise merges doclists so that newer data knocks out
107132 ** older data.
107133 **
107134 ** TODO(shess) Provide a VACUUM type operation to clear out all
107135 ** deletions and duplications.  This would basically be a forced merge
107136 ** into a single segment.
107137 */
107138
107139 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
107140
107141 #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
107142 # define SQLITE_CORE 1
107143 #endif
107144
107145 /************** Include fts3Int.h in the middle of fts3.c ********************/
107146 /************** Begin file fts3Int.h *****************************************/
107147 /*
107148 ** 2009 Nov 12
107149 **
107150 ** The author disclaims copyright to this source code.  In place of
107151 ** a legal notice, here is a blessing:
107152 **
107153 **    May you do good and not evil.
107154 **    May you find forgiveness for yourself and forgive others.
107155 **    May you share freely, never taking more than you give.
107156 **
107157 ******************************************************************************
107158 **
107159 */
107160
107161 #ifndef _FTSINT_H
107162 #define _FTSINT_H
107163
107164 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
107165 # define NDEBUG 1
107166 #endif
107167
107168 /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
107169 /************** Begin file fts3_tokenizer.h **********************************/
107170 /*
107171 ** 2006 July 10
107172 **
107173 ** The author disclaims copyright to this source code.
107174 **
107175 *************************************************************************
107176 ** Defines the interface to tokenizers used by fulltext-search.  There
107177 ** are three basic components:
107178 **
107179 ** sqlite3_tokenizer_module is a singleton defining the tokenizer
107180 ** interface functions.  This is essentially the class structure for
107181 ** tokenizers.
107182 **
107183 ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
107184 ** including customization information defined at creation time.
107185 **
107186 ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
107187 ** tokens from a particular input.
107188 */
107189 #ifndef _FTS3_TOKENIZER_H_
107190 #define _FTS3_TOKENIZER_H_
107191
107192 /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
107193 ** If tokenizers are to be allowed to call sqlite3_*() functions, then
107194 ** we will need a way to register the API consistently.
107195 */
107196
107197 /*
107198 ** Structures used by the tokenizer interface. When a new tokenizer
107199 ** implementation is registered, the caller provides a pointer to
107200 ** an sqlite3_tokenizer_module containing pointers to the callback
107201 ** functions that make up an implementation.
107202 **
107203 ** When an fts3 table is created, it passes any arguments passed to
107204 ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
107205 ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
107206 ** implementation. The xCreate() function in turn returns an 
107207 ** sqlite3_tokenizer structure representing the specific tokenizer to
107208 ** be used for the fts3 table (customized by the tokenizer clause arguments).
107209 **
107210 ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
107211 ** method is called. It returns an sqlite3_tokenizer_cursor object
107212 ** that may be used to tokenize a specific input buffer based on
107213 ** the tokenization rules supplied by a specific sqlite3_tokenizer
107214 ** object.
107215 */
107216 typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
107217 typedef struct sqlite3_tokenizer sqlite3_tokenizer;
107218 typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
107219
107220 struct sqlite3_tokenizer_module {
107221
107222   /*
107223   ** Structure version. Should always be set to 0.
107224   */
107225   int iVersion;
107226
107227   /*
107228   ** Create a new tokenizer. The values in the argv[] array are the
107229   ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
107230   ** TABLE statement that created the fts3 table. For example, if
107231   ** the following SQL is executed:
107232   **
107233   **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
107234   **
107235   ** then argc is set to 2, and the argv[] array contains pointers
107236   ** to the strings "arg1" and "arg2".
107237   **
107238   ** This method should return either SQLITE_OK (0), or an SQLite error 
107239   ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
107240   ** to point at the newly created tokenizer structure. The generic
107241   ** sqlite3_tokenizer.pModule variable should not be initialised by
107242   ** this callback. The caller will do so.
107243   */
107244   int (*xCreate)(
107245     int argc,                           /* Size of argv array */
107246     const char *const*argv,             /* Tokenizer argument strings */
107247     sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
107248   );
107249
107250   /*
107251   ** Destroy an existing tokenizer. The fts3 module calls this method
107252   ** exactly once for each successful call to xCreate().
107253   */
107254   int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
107255
107256   /*
107257   ** Create a tokenizer cursor to tokenize an input buffer. The caller
107258   ** is responsible for ensuring that the input buffer remains valid
107259   ** until the cursor is closed (using the xClose() method). 
107260   */
107261   int (*xOpen)(
107262     sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
107263     const char *pInput, int nBytes,      /* Input buffer */
107264     sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
107265   );
107266
107267   /*
107268   ** Destroy an existing tokenizer cursor. The fts3 module calls this 
107269   ** method exactly once for each successful call to xOpen().
107270   */
107271   int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
107272
107273   /*
107274   ** Retrieve the next token from the tokenizer cursor pCursor. This
107275   ** method should either return SQLITE_OK and set the values of the
107276   ** "OUT" variables identified below, or SQLITE_DONE to indicate that
107277   ** the end of the buffer has been reached, or an SQLite error code.
107278   **
107279   ** *ppToken should be set to point at a buffer containing the 
107280   ** normalized version of the token (i.e. after any case-folding and/or
107281   ** stemming has been performed). *pnBytes should be set to the length
107282   ** of this buffer in bytes. The input text that generated the token is
107283   ** identified by the byte offsets returned in *piStartOffset and
107284   ** *piEndOffset. *piStartOffset should be set to the index of the first
107285   ** byte of the token in the input buffer. *piEndOffset should be set
107286   ** to the index of the first byte just past the end of the token in
107287   ** the input buffer.
107288   **
107289   ** The buffer *ppToken is set to point at is managed by the tokenizer
107290   ** implementation. It is only required to be valid until the next call
107291   ** to xNext() or xClose(). 
107292   */
107293   /* TODO(shess) current implementation requires pInput to be
107294   ** nul-terminated.  This should either be fixed, or pInput/nBytes
107295   ** should be converted to zInput.
107296   */
107297   int (*xNext)(
107298     sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
107299     const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
107300     int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
107301     int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
107302     int *piPosition      /* OUT: Number of tokens returned before this one */
107303   );
107304 };
107305
107306 struct sqlite3_tokenizer {
107307   const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
107308   /* Tokenizer implementations will typically add additional fields */
107309 };
107310
107311 struct sqlite3_tokenizer_cursor {
107312   sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
107313   /* Tokenizer implementations will typically add additional fields */
107314 };
107315
107316 int fts3_global_term_cnt(int iTerm, int iCol);
107317 int fts3_term_cnt(int iTerm, int iCol);
107318
107319
107320 #endif /* _FTS3_TOKENIZER_H_ */
107321
107322 /************** End of fts3_tokenizer.h **************************************/
107323 /************** Continuing where we left off in fts3Int.h ********************/
107324 /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
107325 /************** Begin file fts3_hash.h ***************************************/
107326 /*
107327 ** 2001 September 22
107328 **
107329 ** The author disclaims copyright to this source code.  In place of
107330 ** a legal notice, here is a blessing:
107331 **
107332 **    May you do good and not evil.
107333 **    May you find forgiveness for yourself and forgive others.
107334 **    May you share freely, never taking more than you give.
107335 **
107336 *************************************************************************
107337 ** This is the header file for the generic hash-table implemenation
107338 ** used in SQLite.  We've modified it slightly to serve as a standalone
107339 ** hash table implementation for the full-text indexing module.
107340 **
107341 */
107342 #ifndef _FTS3_HASH_H_
107343 #define _FTS3_HASH_H_
107344
107345 /* Forward declarations of structures. */
107346 typedef struct Fts3Hash Fts3Hash;
107347 typedef struct Fts3HashElem Fts3HashElem;
107348
107349 /* A complete hash table is an instance of the following structure.
107350 ** The internals of this structure are intended to be opaque -- client
107351 ** code should not attempt to access or modify the fields of this structure
107352 ** directly.  Change this structure only by using the routines below.
107353 ** However, many of the "procedures" and "functions" for modifying and
107354 ** accessing this structure are really macros, so we can't really make
107355 ** this structure opaque.
107356 */
107357 struct Fts3Hash {
107358   char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
107359   char copyKey;           /* True if copy of key made on insert */
107360   int count;              /* Number of entries in this table */
107361   Fts3HashElem *first;    /* The first element of the array */
107362   int htsize;             /* Number of buckets in the hash table */
107363   struct _fts3ht {        /* the hash table */
107364     int count;               /* Number of entries with this hash */
107365     Fts3HashElem *chain;     /* Pointer to first entry with this hash */
107366   } *ht;
107367 };
107368
107369 /* Each element in the hash table is an instance of the following 
107370 ** structure.  All elements are stored on a single doubly-linked list.
107371 **
107372 ** Again, this structure is intended to be opaque, but it can't really
107373 ** be opaque because it is used by macros.
107374 */
107375 struct Fts3HashElem {
107376   Fts3HashElem *next, *prev; /* Next and previous elements in the table */
107377   void *data;                /* Data associated with this element */
107378   void *pKey; int nKey;      /* Key associated with this element */
107379 };
107380
107381 /*
107382 ** There are 2 different modes of operation for a hash table:
107383 **
107384 **   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long
107385 **                           (including the null-terminator, if any).  Case
107386 **                           is respected in comparisons.
107387 **
107388 **   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long. 
107389 **                           memcmp() is used to compare keys.
107390 **
107391 ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.  
107392 */
107393 #define FTS3_HASH_STRING    1
107394 #define FTS3_HASH_BINARY    2
107395
107396 /*
107397 ** Access routines.  To delete, insert a NULL pointer.
107398 */
107399 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
107400 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
107401 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
107402 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
107403 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
107404
107405 /*
107406 ** Shorthand for the functions above
107407 */
107408 #define fts3HashInit     sqlite3Fts3HashInit
107409 #define fts3HashInsert   sqlite3Fts3HashInsert
107410 #define fts3HashFind     sqlite3Fts3HashFind
107411 #define fts3HashClear    sqlite3Fts3HashClear
107412 #define fts3HashFindElem sqlite3Fts3HashFindElem
107413
107414 /*
107415 ** Macros for looping over all elements of a hash table.  The idiom is
107416 ** like this:
107417 **
107418 **   Fts3Hash h;
107419 **   Fts3HashElem *p;
107420 **   ...
107421 **   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
107422 **     SomeStructure *pData = fts3HashData(p);
107423 **     // do something with pData
107424 **   }
107425 */
107426 #define fts3HashFirst(H)  ((H)->first)
107427 #define fts3HashNext(E)   ((E)->next)
107428 #define fts3HashData(E)   ((E)->data)
107429 #define fts3HashKey(E)    ((E)->pKey)
107430 #define fts3HashKeysize(E) ((E)->nKey)
107431
107432 /*
107433 ** Number of entries in a hash table
107434 */
107435 #define fts3HashCount(H)  ((H)->count)
107436
107437 #endif /* _FTS3_HASH_H_ */
107438
107439 /************** End of fts3_hash.h *******************************************/
107440 /************** Continuing where we left off in fts3Int.h ********************/
107441
107442 /*
107443 ** This constant controls how often segments are merged. Once there are
107444 ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
107445 ** segment of level N+1.
107446 */
107447 #define FTS3_MERGE_COUNT 16
107448
107449 /*
107450 ** This is the maximum amount of data (in bytes) to store in the 
107451 ** Fts3Table.pendingTerms hash table. Normally, the hash table is
107452 ** populated as documents are inserted/updated/deleted in a transaction
107453 ** and used to create a new segment when the transaction is committed.
107454 ** However if this limit is reached midway through a transaction, a new 
107455 ** segment is created and the hash table cleared immediately.
107456 */
107457 #define FTS3_MAX_PENDING_DATA (1*1024*1024)
107458
107459 /*
107460 ** Macro to return the number of elements in an array. SQLite has a
107461 ** similar macro called ArraySize(). Use a different name to avoid
107462 ** a collision when building an amalgamation with built-in FTS3.
107463 */
107464 #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
107465
107466 /*
107467 ** Maximum length of a varint encoded integer. The varint format is different
107468 ** from that used by SQLite, so the maximum length is 10, not 9.
107469 */
107470 #define FTS3_VARINT_MAX 10
107471
107472 /*
107473 ** The testcase() macro is only used by the amalgamation.  If undefined,
107474 ** make it a no-op.
107475 */
107476 #ifndef testcase
107477 # define testcase(X)
107478 #endif
107479
107480 /*
107481 ** Terminator values for position-lists and column-lists.
107482 */
107483 #define POS_COLUMN  (1)     /* Column-list terminator */
107484 #define POS_END     (0)     /* Position-list terminator */ 
107485
107486 /*
107487 ** This section provides definitions to allow the
107488 ** FTS3 extension to be compiled outside of the 
107489 ** amalgamation.
107490 */
107491 #ifndef SQLITE_AMALGAMATION
107492 /*
107493 ** Macros indicating that conditional expressions are always true or
107494 ** false.
107495 */
107496 # define ALWAYS(x) (x)
107497 # define NEVER(X)  (x)
107498 /*
107499 ** Internal types used by SQLite.
107500 */
107501 typedef unsigned char u8;         /* 1-byte (or larger) unsigned integer */
107502 typedef short int i16;            /* 2-byte (or larger) signed integer */
107503 typedef unsigned int u32;         /* 4-byte unsigned integer */
107504 typedef sqlite3_uint64 u64;       /* 8-byte unsigned integer */
107505 /*
107506 ** Macro used to suppress compiler warnings for unused parameters.
107507 */
107508 #define UNUSED_PARAMETER(x) (void)(x)
107509 #endif
107510
107511 typedef struct Fts3Table Fts3Table;
107512 typedef struct Fts3Cursor Fts3Cursor;
107513 typedef struct Fts3Expr Fts3Expr;
107514 typedef struct Fts3Phrase Fts3Phrase;
107515 typedef struct Fts3SegReader Fts3SegReader;
107516 typedef struct Fts3SegFilter Fts3SegFilter;
107517
107518 /*
107519 ** A connection to a fulltext index is an instance of the following
107520 ** structure. The xCreate and xConnect methods create an instance
107521 ** of this structure and xDestroy and xDisconnect free that instance.
107522 ** All other methods receive a pointer to the structure as one of their
107523 ** arguments.
107524 */
107525 struct Fts3Table {
107526   sqlite3_vtab base;              /* Base class used by SQLite core */
107527   sqlite3 *db;                    /* The database connection */
107528   const char *zDb;                /* logical database name */
107529   const char *zName;              /* virtual table name */
107530   int nColumn;                    /* number of named columns in virtual table */
107531   char **azColumn;                /* column names.  malloced */
107532   sqlite3_tokenizer *pTokenizer;  /* tokenizer for inserts and queries */
107533
107534   /* Precompiled statements used by the implementation. Each of these 
107535   ** statements is run and reset within a single virtual table API call. 
107536   */
107537   sqlite3_stmt *aStmt[25];
107538
107539   /* Pointer to string containing the SQL:
107540   **
107541   ** "SELECT block FROM %_segments WHERE blockid BETWEEN ? AND ? 
107542   **    ORDER BY blockid"
107543   */
107544   char *zSelectLeaves;
107545   int nLeavesStmt;                /* Valid statements in aLeavesStmt */
107546   int nLeavesTotal;               /* Total number of prepared leaves stmts */
107547   int nLeavesAlloc;               /* Allocated size of aLeavesStmt */
107548   sqlite3_stmt **aLeavesStmt;     /* Array of prepared zSelectLeaves stmts */
107549
107550   int nNodeSize;                  /* Soft limit for node size */
107551   u8 bHasContent;                 /* True if %_content table exists */
107552   u8 bHasDocsize;                 /* True if %_docsize table exists */
107553
107554   /* The following hash table is used to buffer pending index updates during
107555   ** transactions. Variable nPendingData estimates the memory size of the 
107556   ** pending data, including hash table overhead, but not malloc overhead. 
107557   ** When nPendingData exceeds nMaxPendingData, the buffer is flushed 
107558   ** automatically. Variable iPrevDocid is the docid of the most recently
107559   ** inserted record.
107560   */
107561   int nMaxPendingData;
107562   int nPendingData;
107563   sqlite_int64 iPrevDocid;
107564   Fts3Hash pendingTerms;
107565 };
107566
107567 /*
107568 ** When the core wants to read from the virtual table, it creates a
107569 ** virtual table cursor (an instance of the following structure) using
107570 ** the xOpen method. Cursors are destroyed using the xClose method.
107571 */
107572 struct Fts3Cursor {
107573   sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
107574   i16 eSearch;                    /* Search strategy (see below) */
107575   u8 isEof;                       /* True if at End Of Results */
107576   u8 isRequireSeek;               /* True if must seek pStmt to %_content row */
107577   sqlite3_stmt *pStmt;            /* Prepared statement in use by the cursor */
107578   Fts3Expr *pExpr;                /* Parsed MATCH query string */
107579   sqlite3_int64 iPrevId;          /* Previous id read from aDoclist */
107580   char *pNextId;                  /* Pointer into the body of aDoclist */
107581   char *aDoclist;                 /* List of docids for full-text queries */
107582   int nDoclist;                   /* Size of buffer at aDoclist */
107583   int isMatchinfoNeeded;          /* True when aMatchinfo[] needs filling in */
107584   u32 *aMatchinfo;                /* Information about most recent match */
107585 };
107586
107587 /*
107588 ** The Fts3Cursor.eSearch member is always set to one of the following.
107589 ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
107590 ** FTS3_FULLTEXT_SEARCH.  If so, then Fts3Cursor.eSearch - 2 is the index
107591 ** of the column to be searched.  For example, in
107592 **
107593 **     CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
107594 **     SELECT docid FROM ex1 WHERE b MATCH 'one two three';
107595 ** 
107596 ** Because the LHS of the MATCH operator is 2nd column "b",
107597 ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1.  (+0 for a,
107598 ** +1 for b, +2 for c, +3 for d.)  If the LHS of MATCH were "ex1" 
107599 ** indicating that all columns should be searched,
107600 ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
107601 */
107602 #define FTS3_FULLSCAN_SEARCH 0    /* Linear scan of %_content table */
107603 #define FTS3_DOCID_SEARCH    1    /* Lookup by rowid on %_content table */
107604 #define FTS3_FULLTEXT_SEARCH 2    /* Full-text index search */
107605
107606 /*
107607 ** A "phrase" is a sequence of one or more tokens that must match in
107608 ** sequence.  A single token is the base case and the most common case.
107609 ** For a sequence of tokens contained in "...", nToken will be the number
107610 ** of tokens in the string.
107611 */
107612 struct Fts3Phrase {
107613   int nToken;                /* Number of tokens in the phrase */
107614   int iColumn;               /* Index of column this phrase must match */
107615   int isNot;                 /* Phrase prefixed by unary not (-) operator */
107616   struct PhraseToken {
107617     char *z;                 /* Text of the token */
107618     int n;                   /* Number of bytes in buffer pointed to by z */
107619     int isPrefix;            /* True if token ends in with a "*" character */
107620   } aToken[1];               /* One entry for each token in the phrase */
107621 };
107622
107623 /*
107624 ** A tree of these objects forms the RHS of a MATCH operator.
107625 **
107626 ** If Fts3Expr.eType is either FTSQUERY_NEAR or FTSQUERY_PHRASE and isLoaded
107627 ** is true, then aDoclist points to a malloced buffer, size nDoclist bytes, 
107628 ** containing the results of the NEAR or phrase query in FTS3 doclist
107629 ** format. As usual, the initial "Length" field found in doclists stored
107630 ** on disk is omitted from this buffer.
107631 **
107632 ** Variable pCurrent always points to the start of a docid field within
107633 ** aDoclist. Since the doclist is usually scanned in docid order, this can
107634 ** be used to accelerate seeking to the required docid within the doclist.
107635 */
107636 struct Fts3Expr {
107637   int eType;                 /* One of the FTSQUERY_XXX values defined below */
107638   int nNear;                 /* Valid if eType==FTSQUERY_NEAR */
107639   Fts3Expr *pParent;         /* pParent->pLeft==this or pParent->pRight==this */
107640   Fts3Expr *pLeft;           /* Left operand */
107641   Fts3Expr *pRight;          /* Right operand */
107642   Fts3Phrase *pPhrase;       /* Valid if eType==FTSQUERY_PHRASE */
107643
107644   int isLoaded;              /* True if aDoclist/nDoclist are initialized. */
107645   char *aDoclist;            /* Buffer containing doclist */
107646   int nDoclist;              /* Size of aDoclist in bytes */
107647
107648   sqlite3_int64 iCurrent;
107649   char *pCurrent;
107650 };
107651
107652 /*
107653 ** Candidate values for Fts3Query.eType. Note that the order of the first
107654 ** four values is in order of precedence when parsing expressions. For 
107655 ** example, the following:
107656 **
107657 **   "a OR b AND c NOT d NEAR e"
107658 **
107659 ** is equivalent to:
107660 **
107661 **   "a OR (b AND (c NOT (d NEAR e)))"
107662 */
107663 #define FTSQUERY_NEAR   1
107664 #define FTSQUERY_NOT    2
107665 #define FTSQUERY_AND    3
107666 #define FTSQUERY_OR     4
107667 #define FTSQUERY_PHRASE 5
107668
107669
107670 /* fts3_init.c */
107671 SQLITE_PRIVATE int sqlite3Fts3DeleteVtab(int, sqlite3_vtab *);
107672 SQLITE_PRIVATE int sqlite3Fts3InitVtab(int, sqlite3*, void*, int, const char*const*, 
107673                         sqlite3_vtab **, char **);
107674
107675 /* fts3_write.c */
107676 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
107677 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
107678 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
107679 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
107680 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(Fts3Table *,int, sqlite3_int64,
107681   sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
107682 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(Fts3Table*,const char*,int,int,Fts3SegReader**);
107683 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3Table *, Fts3SegReader *);
107684 SQLITE_PRIVATE int sqlite3Fts3SegReaderIterate(
107685   Fts3Table *, Fts3SegReader **, int, Fts3SegFilter *,
107686   int (*)(Fts3Table *, void *, char *, int, char *, int),  void *
107687 );
107688 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char const**, int*);
107689 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, sqlite3_stmt **);
107690 SQLITE_PRIVATE int sqlite3Fts3MatchinfoDocsizeLocal(Fts3Cursor*, u32*);
107691 SQLITE_PRIVATE int sqlite3Fts3MatchinfoDocsizeGlobal(Fts3Cursor*, u32*);
107692 SQLITE_PRIVATE int sqlite3Fts3ReadLock(Fts3Table *);
107693
107694 /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
107695 #define FTS3_SEGMENT_REQUIRE_POS   0x00000001
107696 #define FTS3_SEGMENT_IGNORE_EMPTY  0x00000002
107697 #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
107698 #define FTS3_SEGMENT_PREFIX        0x00000008
107699
107700 /* Type passed as 4th argument to SegmentReaderIterate() */
107701 struct Fts3SegFilter {
107702   const char *zTerm;
107703   int nTerm;
107704   int iCol;
107705   int flags;
107706 };
107707
107708 /* fts3.c */
107709 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
107710 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
107711 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
107712 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
107713 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
107714
107715 SQLITE_PRIVATE char *sqlite3Fts3FindPositions(Fts3Expr *, sqlite3_int64, int);
107716 SQLITE_PRIVATE int sqlite3Fts3ExprLoadDoclist(Fts3Table *, Fts3Expr *);
107717 SQLITE_PRIVATE int sqlite3Fts3ExprNearTrim(Fts3Expr *, Fts3Expr *, int);
107718
107719 /* fts3_tokenizer.c */
107720 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
107721 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
107722 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, 
107723   const char *, sqlite3_tokenizer **, const char **, char **
107724 );
107725
107726 /* fts3_snippet.c */
107727 SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
107728 SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
107729   const char *, const char *, int, int
107730 );
107731 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *);
107732
107733 /* fts3_expr.c */
107734 SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, 
107735   char **, int, int, const char *, int, Fts3Expr **
107736 );
107737 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
107738 #ifdef SQLITE_TEST
107739 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
107740 #endif
107741
107742 #endif /* _FTSINT_H */
107743
107744 /************** End of fts3Int.h *********************************************/
107745 /************** Continuing where we left off in fts3.c ***********************/
107746
107747
107748 #ifndef SQLITE_CORE 
107749   SQLITE_EXTENSION_INIT1
107750 #endif
107751
107752 /* 
107753 ** Write a 64-bit variable-length integer to memory starting at p[0].
107754 ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
107755 ** The number of bytes written is returned.
107756 */
107757 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
107758   unsigned char *q = (unsigned char *) p;
107759   sqlite_uint64 vu = v;
107760   do{
107761     *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
107762     vu >>= 7;
107763   }while( vu!=0 );
107764   q[-1] &= 0x7f;  /* turn off high bit in final byte */
107765   assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
107766   return (int) (q - (unsigned char *)p);
107767 }
107768
107769 /* 
107770 ** Read a 64-bit variable-length integer from memory starting at p[0].
107771 ** Return the number of bytes read, or 0 on error.
107772 ** The value is stored in *v.
107773 */
107774 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
107775   const unsigned char *q = (const unsigned char *) p;
107776   sqlite_uint64 x = 0, y = 1;
107777   while( (*q&0x80)==0x80 && q-(unsigned char *)p<FTS3_VARINT_MAX ){
107778     x += y * (*q++ & 0x7f);
107779     y <<= 7;
107780   }
107781   x += y * (*q++);
107782   *v = (sqlite_int64) x;
107783   return (int) (q - (unsigned char *)p);
107784 }
107785
107786 /*
107787 ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
107788 ** 32-bit integer before it is returned.
107789 */
107790 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
107791  sqlite_int64 i;
107792  int ret = sqlite3Fts3GetVarint(p, &i);
107793  *pi = (int) i;
107794  return ret;
107795 }
107796
107797 /*
107798 ** Return the number of bytes required to encode v as a varint
107799 */
107800 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
107801   int i = 0;
107802   do{
107803     i++;
107804     v >>= 7;
107805   }while( v!=0 );
107806   return i;
107807 }
107808
107809 /*
107810 ** Convert an SQL-style quoted string into a normal string by removing
107811 ** the quote characters.  The conversion is done in-place.  If the
107812 ** input does not begin with a quote character, then this routine
107813 ** is a no-op.
107814 **
107815 ** Examples:
107816 **
107817 **     "abc"   becomes   abc
107818 **     'xyz'   becomes   xyz
107819 **     [pqr]   becomes   pqr
107820 **     `mno`   becomes   mno
107821 **
107822 */
107823 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
107824   char quote;                     /* Quote character (if any ) */
107825
107826   quote = z[0];
107827   if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
107828     int iIn = 1;                  /* Index of next byte to read from input */
107829     int iOut = 0;                 /* Index of next byte to write to output */
107830
107831     /* If the first byte was a '[', then the close-quote character is a ']' */
107832     if( quote=='[' ) quote = ']';  
107833
107834     while( ALWAYS(z[iIn]) ){
107835       if( z[iIn]==quote ){
107836         if( z[iIn+1]!=quote ) break;
107837         z[iOut++] = quote;
107838         iIn += 2;
107839       }else{
107840         z[iOut++] = z[iIn++];
107841       }
107842     }
107843     z[iOut] = '\0';
107844   }
107845 }
107846
107847 /*
107848 ** Read a single varint from the doclist at *pp and advance *pp to point
107849 ** to the first byte past the end of the varint.  Add the value of the varint
107850 ** to *pVal.
107851 */
107852 static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
107853   sqlite3_int64 iVal;
107854   *pp += sqlite3Fts3GetVarint(*pp, &iVal);
107855   *pVal += iVal;
107856 }
107857
107858 /*
107859 ** As long as *pp has not reached its end (pEnd), then do the same
107860 ** as fts3GetDeltaVarint(): read a single varint and add it to *pVal.
107861 ** But if we have reached the end of the varint, just set *pp=0 and
107862 ** leave *pVal unchanged.
107863 */
107864 static void fts3GetDeltaVarint2(char **pp, char *pEnd, sqlite3_int64 *pVal){
107865   if( *pp>=pEnd ){
107866     *pp = 0;
107867   }else{
107868     fts3GetDeltaVarint(pp, pVal);
107869   }
107870 }
107871
107872 /*
107873 ** The xDisconnect() virtual table method.
107874 */
107875 static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
107876   Fts3Table *p = (Fts3Table *)pVtab;
107877   int i;
107878
107879   assert( p->nPendingData==0 );
107880
107881   /* Free any prepared statements held */
107882   for(i=0; i<SizeofArray(p->aStmt); i++){
107883     sqlite3_finalize(p->aStmt[i]);
107884   }
107885   for(i=0; i<p->nLeavesStmt; i++){
107886     sqlite3_finalize(p->aLeavesStmt[i]);
107887   }
107888   sqlite3_free(p->zSelectLeaves);
107889   sqlite3_free(p->aLeavesStmt);
107890
107891   /* Invoke the tokenizer destructor to free the tokenizer. */
107892   p->pTokenizer->pModule->xDestroy(p->pTokenizer);
107893
107894   sqlite3_free(p);
107895   return SQLITE_OK;
107896 }
107897
107898 /*
107899 ** Construct one or more SQL statements from the format string given
107900 ** and then evaluate those statements.  The success code is writting
107901 ** into *pRc.
107902 **
107903 ** If *pRc is initially non-zero then this routine is a no-op.
107904 */
107905 static void fts3DbExec(
107906   int *pRc,              /* Success code */
107907   sqlite3 *db,           /* Database in which to run SQL */
107908   const char *zFormat,   /* Format string for SQL */
107909   ...                    /* Arguments to the format string */
107910 ){
107911   va_list ap;
107912   char *zSql;
107913   if( *pRc ) return;
107914   va_start(ap, zFormat);
107915   zSql = sqlite3_vmprintf(zFormat, ap);
107916   va_end(ap);
107917   if( zSql==0 ){
107918     *pRc = SQLITE_NOMEM;
107919   }else{
107920     *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
107921     sqlite3_free(zSql);
107922   }
107923 }
107924
107925 /*
107926 ** The xDestroy() virtual table method.
107927 */
107928 static int fts3DestroyMethod(sqlite3_vtab *pVtab){
107929   int rc = SQLITE_OK;              /* Return code */
107930   Fts3Table *p = (Fts3Table *)pVtab;
107931   sqlite3 *db = p->db;
107932
107933   /* Drop the shadow tables */
107934   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", p->zDb, p->zName);
107935   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", p->zDb,p->zName);
107936   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", p->zDb, p->zName);
107937   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", p->zDb, p->zName);
107938   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", p->zDb, p->zName);
107939
107940   /* If everything has worked, invoke fts3DisconnectMethod() to free the
107941   ** memory associated with the Fts3Table structure and return SQLITE_OK.
107942   ** Otherwise, return an SQLite error code.
107943   */
107944   return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
107945 }
107946
107947
107948 /*
107949 ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
107950 ** passed as the first argument. This is done as part of the xConnect()
107951 ** and xCreate() methods.
107952 */
107953 static int fts3DeclareVtab(Fts3Table *p){
107954   int i;                          /* Iterator variable */
107955   int rc;                         /* Return code */
107956   char *zSql;                     /* SQL statement passed to declare_vtab() */
107957   char *zCols;                    /* List of user defined columns */
107958
107959   /* Create a list of user columns for the virtual table */
107960   zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
107961   for(i=1; zCols && i<p->nColumn; i++){
107962     zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
107963   }
107964
107965   /* Create the whole "CREATE TABLE" statement to pass to SQLite */
107966   zSql = sqlite3_mprintf(
107967       "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN)", zCols, p->zName
107968   );
107969
107970   if( !zCols || !zSql ){
107971     rc = SQLITE_NOMEM;
107972   }else{
107973     rc = sqlite3_declare_vtab(p->db, zSql);
107974   }
107975
107976   sqlite3_free(zSql);
107977   sqlite3_free(zCols);
107978   return rc;
107979 }
107980
107981 /*
107982 ** Create the backing store tables (%_content, %_segments and %_segdir)
107983 ** required by the FTS3 table passed as the only argument. This is done
107984 ** as part of the vtab xCreate() method.
107985 **
107986 ** If the p->bHasDocsize boolean is true (indicating that this is an
107987 ** FTS4 table, not an FTS3 table) then also create the %_docsize and
107988 ** %_stat tables required by FTS4.
107989 */
107990 static int fts3CreateTables(Fts3Table *p){
107991   int rc = SQLITE_OK;             /* Return code */
107992   int i;                          /* Iterator variable */
107993   char *zContentCols;             /* Columns of %_content table */
107994   sqlite3 *db = p->db;            /* The database connection */
107995
107996   /* Create a list of user columns for the content table */
107997   if( p->bHasContent ){
107998     zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
107999     for(i=0; zContentCols && i<p->nColumn; i++){
108000       char *z = p->azColumn[i];
108001       zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
108002     }
108003     if( zContentCols==0 ) rc = SQLITE_NOMEM;
108004
108005     /* Create the content table */
108006     fts3DbExec(&rc, db, 
108007        "CREATE TABLE %Q.'%q_content'(%s)",
108008        p->zDb, p->zName, zContentCols
108009     );
108010     sqlite3_free(zContentCols);
108011   }
108012   /* Create other tables */
108013   fts3DbExec(&rc, db, 
108014       "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
108015       p->zDb, p->zName
108016   );
108017   fts3DbExec(&rc, db, 
108018       "CREATE TABLE %Q.'%q_segdir'("
108019         "level INTEGER,"
108020         "idx INTEGER,"
108021         "start_block INTEGER,"
108022         "leaves_end_block INTEGER,"
108023         "end_block INTEGER,"
108024         "root BLOB,"
108025         "PRIMARY KEY(level, idx)"
108026       ");",
108027       p->zDb, p->zName
108028   );
108029   if( p->bHasDocsize ){
108030     fts3DbExec(&rc, db, 
108031         "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
108032         p->zDb, p->zName
108033     );
108034     fts3DbExec(&rc, db, 
108035         "CREATE TABLE %Q.'%q_stat'(id INTEGER PRIMARY KEY, value BLOB);",
108036         p->zDb, p->zName
108037     );
108038   }
108039   return rc;
108040 }
108041
108042 /*
108043 ** An sqlite3_exec() callback for fts3TableExists.
108044 */
108045 static int fts3TableExistsCallback(void *pArg, int n, char **pp1, char **pp2){
108046   UNUSED_PARAMETER(n);
108047   UNUSED_PARAMETER(pp1);
108048   UNUSED_PARAMETER(pp2);
108049   *(int*)pArg = 1;
108050   return 1;
108051 }
108052
108053 /*
108054 ** Determine if a table currently exists in the database.
108055 */
108056 static void fts3TableExists(
108057   int *pRc,             /* Success code */
108058   sqlite3 *db,          /* The database connection to test */
108059   const char *zDb,      /* ATTACHed database within the connection */
108060   const char *zName,    /* Name of the FTS3 table */
108061   const char *zSuffix,  /* Shadow table extension */
108062   u8 *pResult           /* Write results here */
108063 ){
108064   int rc = SQLITE_OK;
108065   int res = 0;
108066   char *zSql;
108067   if( *pRc ) return;
108068   zSql = sqlite3_mprintf(
108069     "SELECT 1 FROM %Q.sqlite_master WHERE name='%q%s'",
108070     zDb, zName, zSuffix
108071   );    
108072   rc = sqlite3_exec(db, zSql, fts3TableExistsCallback, &res, 0);
108073   sqlite3_free(zSql);
108074   *pResult = (u8)(res & 0xff);
108075   if( rc!=SQLITE_ABORT ) *pRc = rc;
108076 }
108077
108078 /*
108079 ** This function is the implementation of both the xConnect and xCreate
108080 ** methods of the FTS3 virtual table.
108081 **
108082 ** The argv[] array contains the following:
108083 **
108084 **   argv[0]   -> module name  ("fts3" or "fts4")
108085 **   argv[1]   -> database name
108086 **   argv[2]   -> table name
108087 **   argv[...] -> "column name" and other module argument fields.
108088 */
108089 static int fts3InitVtab(
108090   int isCreate,                   /* True for xCreate, false for xConnect */
108091   sqlite3 *db,                    /* The SQLite database connection */
108092   void *pAux,                     /* Hash table containing tokenizers */
108093   int argc,                       /* Number of elements in argv array */
108094   const char * const *argv,       /* xCreate/xConnect argument array */
108095   sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
108096   char **pzErr                    /* Write any error message here */
108097 ){
108098   Fts3Hash *pHash = (Fts3Hash *)pAux;
108099   Fts3Table *p;                   /* Pointer to allocated vtab */
108100   int rc;                         /* Return code */
108101   int i;                          /* Iterator variable */
108102   int nByte;                      /* Size of allocation used for *p */
108103   int iCol;                       /* Column index */
108104   int nString = 0;                /* Bytes required to hold all column names */
108105   int nCol = 0;                   /* Number of columns in the FTS table */
108106   char *zCsr;                     /* Space for holding column names */
108107   int nDb;                        /* Bytes required to hold database name */
108108   int nName;                      /* Bytes required to hold table name */
108109
108110   const char *zTokenizer = 0;               /* Name of tokenizer to use */
108111   sqlite3_tokenizer *pTokenizer = 0;        /* Tokenizer for this table */
108112
108113   nDb = (int)strlen(argv[1]) + 1;
108114   nName = (int)strlen(argv[2]) + 1;
108115   for(i=3; i<argc; i++){
108116     char const *z = argv[i];
108117     rc = sqlite3Fts3InitTokenizer(pHash, z, &pTokenizer, &zTokenizer, pzErr);
108118     if( rc!=SQLITE_OK ){
108119       return rc;
108120     }
108121     if( z!=zTokenizer ){
108122       nString += (int)(strlen(z) + 1);
108123     }
108124   }
108125   nCol = argc - 3 - (zTokenizer!=0);
108126   if( zTokenizer==0 ){
108127     rc = sqlite3Fts3InitTokenizer(pHash, 0, &pTokenizer, 0, pzErr);
108128     if( rc!=SQLITE_OK ){
108129       return rc;
108130     }
108131     assert( pTokenizer );
108132   }
108133
108134   if( nCol==0 ){
108135     nCol = 1;
108136   }
108137
108138   /* Allocate and populate the Fts3Table structure. */
108139   nByte = sizeof(Fts3Table) +              /* Fts3Table */
108140           nCol * sizeof(char *) +              /* azColumn */
108141           nName +                              /* zName */
108142           nDb +                                /* zDb */
108143           nString;                             /* Space for azColumn strings */
108144   p = (Fts3Table*)sqlite3_malloc(nByte);
108145   if( p==0 ){
108146     rc = SQLITE_NOMEM;
108147     goto fts3_init_out;
108148   }
108149   memset(p, 0, nByte);
108150
108151   p->db = db;
108152   p->nColumn = nCol;
108153   p->nPendingData = 0;
108154   p->azColumn = (char **)&p[1];
108155   p->pTokenizer = pTokenizer;
108156   p->nNodeSize = 1000;
108157   p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
108158   zCsr = (char *)&p->azColumn[nCol];
108159
108160   fts3HashInit(&p->pendingTerms, FTS3_HASH_STRING, 1);
108161
108162   /* Fill in the zName and zDb fields of the vtab structure. */
108163   p->zName = zCsr;
108164   memcpy(zCsr, argv[2], nName);
108165   zCsr += nName;
108166   p->zDb = zCsr;
108167   memcpy(zCsr, argv[1], nDb);
108168   zCsr += nDb;
108169
108170   /* Fill in the azColumn array */
108171   iCol = 0;
108172   for(i=3; i<argc; i++){
108173     if( argv[i]!=zTokenizer ){
108174       char *z; 
108175       int n;
108176       z = (char *)sqlite3Fts3NextToken(argv[i], &n);
108177       memcpy(zCsr, z, n);
108178       zCsr[n] = '\0';
108179       sqlite3Fts3Dequote(zCsr);
108180       p->azColumn[iCol++] = zCsr;
108181       zCsr += n+1;
108182       assert( zCsr <= &((char *)p)[nByte] );
108183     }
108184   }
108185   if( iCol==0 ){
108186     assert( nCol==1 );
108187     p->azColumn[0] = "content";
108188   }
108189
108190   /* If this is an xCreate call, create the underlying tables in the 
108191   ** database. TODO: For xConnect(), it could verify that said tables exist.
108192   */
108193   if( isCreate ){
108194     p->bHasContent = 1;
108195     p->bHasDocsize = argv[0][3]=='4';
108196     rc = fts3CreateTables(p);
108197   }else{
108198     rc = SQLITE_OK;
108199     fts3TableExists(&rc, db, argv[1], argv[2], "_content", &p->bHasContent);
108200     fts3TableExists(&rc, db, argv[1], argv[2], "_docsize", &p->bHasDocsize);
108201   }
108202   if( rc!=SQLITE_OK ) goto fts3_init_out;
108203
108204   rc = fts3DeclareVtab(p);
108205   if( rc!=SQLITE_OK ) goto fts3_init_out;
108206
108207   *ppVTab = &p->base;
108208
108209 fts3_init_out:
108210   assert( p || (pTokenizer && rc!=SQLITE_OK) );
108211   if( rc!=SQLITE_OK ){
108212     if( p ){
108213       fts3DisconnectMethod((sqlite3_vtab *)p);
108214     }else{
108215       pTokenizer->pModule->xDestroy(pTokenizer);
108216     }
108217   }
108218   return rc;
108219 }
108220
108221 /*
108222 ** The xConnect() and xCreate() methods for the virtual table. All the
108223 ** work is done in function fts3InitVtab().
108224 */
108225 static int fts3ConnectMethod(
108226   sqlite3 *db,                    /* Database connection */
108227   void *pAux,                     /* Pointer to tokenizer hash table */
108228   int argc,                       /* Number of elements in argv array */
108229   const char * const *argv,       /* xCreate/xConnect argument array */
108230   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
108231   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
108232 ){
108233   return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
108234 }
108235 static int fts3CreateMethod(
108236   sqlite3 *db,                    /* Database connection */
108237   void *pAux,                     /* Pointer to tokenizer hash table */
108238   int argc,                       /* Number of elements in argv array */
108239   const char * const *argv,       /* xCreate/xConnect argument array */
108240   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
108241   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
108242 ){
108243   return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
108244 }
108245
108246 /* 
108247 ** Implementation of the xBestIndex method for FTS3 tables. There
108248 ** are three possible strategies, in order of preference:
108249 **
108250 **   1. Direct lookup by rowid or docid. 
108251 **   2. Full-text search using a MATCH operator on a non-docid column.
108252 **   3. Linear scan of %_content table.
108253 */
108254 static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
108255   Fts3Table *p = (Fts3Table *)pVTab;
108256   int i;                          /* Iterator variable */
108257   int iCons = -1;                 /* Index of constraint to use */
108258
108259   /* By default use a full table scan. This is an expensive option,
108260   ** so search through the constraints to see if a more efficient 
108261   ** strategy is possible.
108262   */
108263   pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
108264   pInfo->estimatedCost = 500000;
108265   for(i=0; i<pInfo->nConstraint; i++){
108266     struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
108267     if( pCons->usable==0 ) continue;
108268
108269     /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
108270     if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ 
108271      && (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1 )
108272     ){
108273       pInfo->idxNum = FTS3_DOCID_SEARCH;
108274       pInfo->estimatedCost = 1.0;
108275       iCons = i;
108276     }
108277
108278     /* A MATCH constraint. Use a full-text search.
108279     **
108280     ** If there is more than one MATCH constraint available, use the first
108281     ** one encountered. If there is both a MATCH constraint and a direct
108282     ** rowid/docid lookup, prefer the MATCH strategy. This is done even 
108283     ** though the rowid/docid lookup is faster than a MATCH query, selecting
108284     ** it would lead to an "unable to use function MATCH in the requested 
108285     ** context" error.
108286     */
108287     if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH 
108288      && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
108289     ){
108290       pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
108291       pInfo->estimatedCost = 2.0;
108292       iCons = i;
108293       break;
108294     }
108295   }
108296
108297   if( iCons>=0 ){
108298     pInfo->aConstraintUsage[iCons].argvIndex = 1;
108299     pInfo->aConstraintUsage[iCons].omit = 1;
108300   } 
108301   return SQLITE_OK;
108302 }
108303
108304 /*
108305 ** Implementation of xOpen method.
108306 */
108307 static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
108308   sqlite3_vtab_cursor *pCsr;               /* Allocated cursor */
108309
108310   UNUSED_PARAMETER(pVTab);
108311
108312   /* Allocate a buffer large enough for an Fts3Cursor structure. If the
108313   ** allocation succeeds, zero it and return SQLITE_OK. Otherwise, 
108314   ** if the allocation fails, return SQLITE_NOMEM.
108315   */
108316   *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
108317   if( !pCsr ){
108318     return SQLITE_NOMEM;
108319   }
108320   memset(pCsr, 0, sizeof(Fts3Cursor));
108321   return SQLITE_OK;
108322 }
108323
108324 /*
108325 ** Close the cursor.  For additional information see the documentation
108326 ** on the xClose method of the virtual table interface.
108327 */
108328 static int fulltextClose(sqlite3_vtab_cursor *pCursor){
108329   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
108330   sqlite3_finalize(pCsr->pStmt);
108331   sqlite3Fts3ExprFree(pCsr->pExpr);
108332   sqlite3_free(pCsr->aDoclist);
108333   sqlite3_free(pCsr->aMatchinfo);
108334   sqlite3_free(pCsr);
108335   return SQLITE_OK;
108336 }
108337
108338 /*
108339 ** Position the pCsr->pStmt statement so that it is on the row
108340 ** of the %_content table that contains the last match.  Return
108341 ** SQLITE_OK on success.  
108342 */
108343 static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
108344   if( pCsr->isRequireSeek ){
108345     pCsr->isRequireSeek = 0;
108346     sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
108347     if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
108348       return SQLITE_OK;
108349     }else{
108350       int rc = sqlite3_reset(pCsr->pStmt);
108351       if( rc==SQLITE_OK ){
108352         /* If no row was found and no error has occured, then the %_content
108353         ** table is missing a row that is present in the full-text index.
108354         ** The data structures are corrupt.
108355         */
108356         rc = SQLITE_CORRUPT;
108357       }
108358       pCsr->isEof = 1;
108359       if( pContext ){
108360         sqlite3_result_error_code(pContext, rc);
108361       }
108362       return rc;
108363     }
108364   }else{
108365     return SQLITE_OK;
108366   }
108367 }
108368
108369 /*
108370 ** Advance the cursor to the next row in the %_content table that
108371 ** matches the search criteria.  For a MATCH search, this will be
108372 ** the next row that matches.  For a full-table scan, this will be
108373 ** simply the next row in the %_content table.  For a docid lookup,
108374 ** this routine simply sets the EOF flag.
108375 **
108376 ** Return SQLITE_OK if nothing goes wrong.  SQLITE_OK is returned
108377 ** even if we reach end-of-file.  The fts3EofMethod() will be called
108378 ** subsequently to determine whether or not an EOF was hit.
108379 */
108380 static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
108381   int rc = SQLITE_OK;             /* Return code */
108382   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
108383
108384   if( pCsr->aDoclist==0 ){
108385     if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
108386       pCsr->isEof = 1;
108387       rc = sqlite3_reset(pCsr->pStmt);
108388     }
108389   }else if( pCsr->pNextId>=&pCsr->aDoclist[pCsr->nDoclist] ){
108390     pCsr->isEof = 1;
108391   }else{
108392     sqlite3_reset(pCsr->pStmt);
108393     fts3GetDeltaVarint(&pCsr->pNextId, &pCsr->iPrevId);
108394     pCsr->isRequireSeek = 1;
108395     pCsr->isMatchinfoNeeded = 1;
108396   }
108397   return rc;
108398 }
108399
108400
108401 /*
108402 ** The buffer pointed to by argument zNode (size nNode bytes) contains the
108403 ** root node of a b-tree segment. The segment is guaranteed to be at least
108404 ** one level high (i.e. the root node is not also a leaf). If successful,
108405 ** this function locates the leaf node of the segment that may contain the 
108406 ** term specified by arguments zTerm and nTerm and writes its block number 
108407 ** to *piLeaf.
108408 **
108409 ** It is possible that the returned leaf node does not contain the specified
108410 ** term. However, if the segment does contain said term, it is stored on
108411 ** the identified leaf node. Because this function only inspects interior
108412 ** segment nodes (and never loads leaf nodes into memory), it is not possible
108413 ** to be sure.
108414 **
108415 ** If an error occurs, an error code other than SQLITE_OK is returned.
108416 */ 
108417 static int fts3SelectLeaf(
108418   Fts3Table *p,                   /* Virtual table handle */
108419   const char *zTerm,              /* Term to select leaves for */
108420   int nTerm,                      /* Size of term zTerm in bytes */
108421   const char *zNode,              /* Buffer containing segment interior node */
108422   int nNode,                      /* Size of buffer at zNode */
108423   sqlite3_int64 *piLeaf           /* Selected leaf node */
108424 ){
108425   int rc = SQLITE_OK;             /* Return code */
108426   const char *zCsr = zNode;       /* Cursor to iterate through node */
108427   const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
108428   char *zBuffer = 0;              /* Buffer to load terms into */
108429   int nAlloc = 0;                 /* Size of allocated buffer */
108430
108431   while( 1 ){
108432     int isFirstTerm = 1;          /* True when processing first term on page */
108433     int iHeight;                  /* Height of this node in tree */
108434     sqlite3_int64 iChild;         /* Block id of child node to descend to */
108435     int nBlock;                   /* Size of child node in bytes */
108436
108437     zCsr += sqlite3Fts3GetVarint32(zCsr, &iHeight);
108438     zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
108439   
108440     while( zCsr<zEnd ){
108441       int cmp;                    /* memcmp() result */
108442       int nSuffix;                /* Size of term suffix */
108443       int nPrefix = 0;            /* Size of term prefix */
108444       int nBuffer;                /* Total term size */
108445   
108446       /* Load the next term on the node into zBuffer */
108447       if( !isFirstTerm ){
108448         zCsr += sqlite3Fts3GetVarint32(zCsr, &nPrefix);
108449       }
108450       isFirstTerm = 0;
108451       zCsr += sqlite3Fts3GetVarint32(zCsr, &nSuffix);
108452       if( nPrefix+nSuffix>nAlloc ){
108453         char *zNew;
108454         nAlloc = (nPrefix+nSuffix) * 2;
108455         zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
108456         if( !zNew ){
108457           sqlite3_free(zBuffer);
108458           return SQLITE_NOMEM;
108459         }
108460         zBuffer = zNew;
108461       }
108462       memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
108463       nBuffer = nPrefix + nSuffix;
108464       zCsr += nSuffix;
108465   
108466       /* Compare the term we are searching for with the term just loaded from
108467       ** the interior node. If the specified term is greater than or equal
108468       ** to the term from the interior node, then all terms on the sub-tree 
108469       ** headed by node iChild are smaller than zTerm. No need to search 
108470       ** iChild.
108471       **
108472       ** If the interior node term is larger than the specified term, then
108473       ** the tree headed by iChild may contain the specified term.
108474       */
108475       cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
108476       if( cmp<0 || (cmp==0 && nBuffer>nTerm) ) break;
108477       iChild++;
108478     };
108479
108480     /* If (iHeight==1), the children of this interior node are leaves. The
108481     ** specified term may be present on leaf node iChild.
108482     */
108483     if( iHeight==1 ){
108484       *piLeaf = iChild;
108485       break;
108486     }
108487
108488     /* Descend to interior node iChild. */
108489     rc = sqlite3Fts3ReadBlock(p, iChild, &zCsr, &nBlock);
108490     if( rc!=SQLITE_OK ) break;
108491     zEnd = &zCsr[nBlock];
108492   }
108493   sqlite3_free(zBuffer);
108494   return rc;
108495 }
108496
108497 /*
108498 ** This function is used to create delta-encoded serialized lists of FTS3 
108499 ** varints. Each call to this function appends a single varint to a list.
108500 */
108501 static void fts3PutDeltaVarint(
108502   char **pp,                      /* IN/OUT: Output pointer */
108503   sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
108504   sqlite3_int64 iVal              /* Write this value to the list */
108505 ){
108506   assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
108507   *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
108508   *piPrev = iVal;
108509 }
108510
108511 /*
108512 ** When this function is called, *ppPoslist is assumed to point to the 
108513 ** start of a position-list. After it returns, *ppPoslist points to the
108514 ** first byte after the position-list.
108515 **
108516 ** A position list is list of positions (delta encoded) and columns for 
108517 ** a single document record of a doclist.  So, in other words, this
108518 ** routine advances *ppPoslist so that it points to the next docid in
108519 ** the doclist, or to the first byte past the end of the doclist.
108520 **
108521 ** If pp is not NULL, then the contents of the position list are copied
108522 ** to *pp. *pp is set to point to the first byte past the last byte copied
108523 ** before this function returns.
108524 */
108525 static void fts3PoslistCopy(char **pp, char **ppPoslist){
108526   char *pEnd = *ppPoslist;
108527   char c = 0;
108528
108529   /* The end of a position list is marked by a zero encoded as an FTS3 
108530   ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
108531   ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
108532   ** of some other, multi-byte, value.
108533   **
108534   ** The following while-loop moves pEnd to point to the first byte that is not 
108535   ** immediately preceded by a byte with the 0x80 bit set. Then increments
108536   ** pEnd once more so that it points to the byte immediately following the
108537   ** last byte in the position-list.
108538   */
108539   while( *pEnd | c ){
108540     c = *pEnd++ & 0x80;
108541     testcase( c!=0 && (*pEnd)==0 );
108542   }
108543   pEnd++;  /* Advance past the POS_END terminator byte */
108544
108545   if( pp ){
108546     int n = (int)(pEnd - *ppPoslist);
108547     char *p = *pp;
108548     memcpy(p, *ppPoslist, n);
108549     p += n;
108550     *pp = p;
108551   }
108552   *ppPoslist = pEnd;
108553 }
108554
108555 /*
108556 ** When this function is called, *ppPoslist is assumed to point to the 
108557 ** start of a column-list. After it returns, *ppPoslist points to the
108558 ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
108559 **
108560 ** A column-list is list of delta-encoded positions for a single column
108561 ** within a single document within a doclist.
108562 **
108563 ** The column-list is terminated either by a POS_COLUMN varint (1) or
108564 ** a POS_END varint (0).  This routine leaves *ppPoslist pointing to
108565 ** the POS_COLUMN or POS_END that terminates the column-list.
108566 **
108567 ** If pp is not NULL, then the contents of the column-list are copied
108568 ** to *pp. *pp is set to point to the first byte past the last byte copied
108569 ** before this function returns.  The POS_COLUMN or POS_END terminator
108570 ** is not copied into *pp.
108571 */
108572 static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
108573   char *pEnd = *ppPoslist;
108574   char c = 0;
108575
108576   /* A column-list is terminated by either a 0x01 or 0x00 byte that is
108577   ** not part of a multi-byte varint.
108578   */
108579   while( 0xFE & (*pEnd | c) ){
108580     c = *pEnd++ & 0x80;
108581     testcase( c!=0 && ((*pEnd)&0xfe)==0 );
108582   }
108583   if( pp ){
108584     int n = (int)(pEnd - *ppPoslist);
108585     char *p = *pp;
108586     memcpy(p, *ppPoslist, n);
108587     p += n;
108588     *pp = p;
108589   }
108590   *ppPoslist = pEnd;
108591 }
108592
108593 /*
108594 ** Value used to signify the end of an position-list. This is safe because
108595 ** it is not possible to have a document with 2^31 terms.
108596 */
108597 #define POSITION_LIST_END 0x7fffffff
108598
108599 /*
108600 ** This function is used to help parse position-lists. When this function is
108601 ** called, *pp may point to the start of the next varint in the position-list
108602 ** being parsed, or it may point to 1 byte past the end of the position-list
108603 ** (in which case **pp will be a terminator bytes POS_END (0) or
108604 ** (1)).
108605 **
108606 ** If *pp points past the end of the current position-list, set *pi to 
108607 ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
108608 ** increment the current value of *pi by the value read, and set *pp to
108609 ** point to the next value before returning.
108610 **
108611 ** Before calling this routine *pi must be initialized to the value of
108612 ** the previous position, or zero if we are reading the first position
108613 ** in the position-list.  Because positions are delta-encoded, the value
108614 ** of the previous position is needed in order to compute the value of
108615 ** the next position.
108616 */
108617 static void fts3ReadNextPos(
108618   char **pp,                    /* IN/OUT: Pointer into position-list buffer */
108619   sqlite3_int64 *pi             /* IN/OUT: Value read from position-list */
108620 ){
108621   if( (**pp)&0xFE ){
108622     fts3GetDeltaVarint(pp, pi);
108623     *pi -= 2;
108624   }else{
108625     *pi = POSITION_LIST_END;
108626   }
108627 }
108628
108629 /*
108630 ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
108631 ** the value of iCol encoded as a varint to *pp.   This will start a new
108632 ** column list.
108633 **
108634 ** Set *pp to point to the byte just after the last byte written before 
108635 ** returning (do not modify it if iCol==0). Return the total number of bytes
108636 ** written (0 if iCol==0).
108637 */
108638 static int fts3PutColNumber(char **pp, int iCol){
108639   int n = 0;                      /* Number of bytes written */
108640   if( iCol ){
108641     char *p = *pp;                /* Output pointer */
108642     n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
108643     *p = 0x01;
108644     *pp = &p[n];
108645   }
108646   return n;
108647 }
108648
108649 /*
108650 ** Compute the union of two position lists.  The output written
108651 ** into *pp contains all positions of both *pp1 and *pp2 in sorted
108652 ** order and with any duplicates removed.  All pointers are
108653 ** updated appropriately.   The caller is responsible for insuring
108654 ** that there is enough space in *pp to hold the complete output.
108655 */
108656 static void fts3PoslistMerge(
108657   char **pp,                      /* Output buffer */
108658   char **pp1,                     /* Left input list */
108659   char **pp2                      /* Right input list */
108660 ){
108661   char *p = *pp;
108662   char *p1 = *pp1;
108663   char *p2 = *pp2;
108664
108665   while( *p1 || *p2 ){
108666     int iCol1;         /* The current column index in pp1 */
108667     int iCol2;         /* The current column index in pp2 */
108668
108669     if( *p1==POS_COLUMN ) sqlite3Fts3GetVarint32(&p1[1], &iCol1);
108670     else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
108671     else iCol1 = 0;
108672
108673     if( *p2==POS_COLUMN ) sqlite3Fts3GetVarint32(&p2[1], &iCol2);
108674     else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
108675     else iCol2 = 0;
108676
108677     if( iCol1==iCol2 ){
108678       sqlite3_int64 i1 = 0;       /* Last position from pp1 */
108679       sqlite3_int64 i2 = 0;       /* Last position from pp2 */
108680       sqlite3_int64 iPrev = 0;
108681       int n = fts3PutColNumber(&p, iCol1);
108682       p1 += n;
108683       p2 += n;
108684
108685       /* At this point, both p1 and p2 point to the start of column-lists
108686       ** for the same column (the column with index iCol1 and iCol2).
108687       ** A column-list is a list of non-negative delta-encoded varints, each 
108688       ** incremented by 2 before being stored. Each list is terminated by a
108689       ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
108690       ** and writes the results to buffer p. p is left pointing to the byte
108691       ** after the list written. No terminator (POS_END or POS_COLUMN) is
108692       ** written to the output.
108693       */
108694       fts3GetDeltaVarint(&p1, &i1);
108695       fts3GetDeltaVarint(&p2, &i2);
108696       do {
108697         fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2); 
108698         iPrev -= 2;
108699         if( i1==i2 ){
108700           fts3ReadNextPos(&p1, &i1);
108701           fts3ReadNextPos(&p2, &i2);
108702         }else if( i1<i2 ){
108703           fts3ReadNextPos(&p1, &i1);
108704         }else{
108705           fts3ReadNextPos(&p2, &i2);
108706         }
108707       }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
108708     }else if( iCol1<iCol2 ){
108709       p1 += fts3PutColNumber(&p, iCol1);
108710       fts3ColumnlistCopy(&p, &p1);
108711     }else{
108712       p2 += fts3PutColNumber(&p, iCol2);
108713       fts3ColumnlistCopy(&p, &p2);
108714     }
108715   }
108716
108717   *p++ = POS_END;
108718   *pp = p;
108719   *pp1 = p1 + 1;
108720   *pp2 = p2 + 1;
108721 }
108722
108723 /*
108724 ** nToken==1 searches for adjacent positions.
108725 */
108726 static int fts3PoslistPhraseMerge(
108727   char **pp,                      /* Output buffer */
108728   int nToken,                     /* Maximum difference in token positions */
108729   int isSaveLeft,                 /* Save the left position */
108730   char **pp1,                     /* Left input list */
108731   char **pp2                      /* Right input list */
108732 ){
108733   char *p = (pp ? *pp : 0);
108734   char *p1 = *pp1;
108735   char *p2 = *pp2;
108736
108737   int iCol1 = 0;
108738   int iCol2 = 0;
108739   assert( *p1!=0 && *p2!=0 );
108740   if( *p1==POS_COLUMN ){ 
108741     p1++;
108742     p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
108743   }
108744   if( *p2==POS_COLUMN ){ 
108745     p2++;
108746     p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
108747   }
108748
108749   while( 1 ){
108750     if( iCol1==iCol2 ){
108751       char *pSave = p;
108752       sqlite3_int64 iPrev = 0;
108753       sqlite3_int64 iPos1 = 0;
108754       sqlite3_int64 iPos2 = 0;
108755
108756       if( pp && iCol1 ){
108757         *p++ = POS_COLUMN;
108758         p += sqlite3Fts3PutVarint(p, iCol1);
108759       }
108760
108761       assert( *p1!=POS_END && *p1!=POS_COLUMN );
108762       assert( *p2!=POS_END && *p2!=POS_COLUMN );
108763       fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
108764       fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
108765
108766       while( 1 ){
108767         if( iPos2>iPos1 && iPos2<=iPos1+nToken ){
108768           sqlite3_int64 iSave;
108769           if( !pp ){
108770             fts3PoslistCopy(0, &p2);
108771             fts3PoslistCopy(0, &p1);
108772             *pp1 = p1;
108773             *pp2 = p2;
108774             return 1;
108775           }
108776           iSave = isSaveLeft ? iPos1 : iPos2;
108777           fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
108778           pSave = 0;
108779         }
108780         if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
108781           if( (*p2&0xFE)==0 ) break;
108782           fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
108783         }else{
108784           if( (*p1&0xFE)==0 ) break;
108785           fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
108786         }
108787       }
108788
108789       if( pSave ){
108790         assert( pp && p );
108791         p = pSave;
108792       }
108793
108794       fts3ColumnlistCopy(0, &p1);
108795       fts3ColumnlistCopy(0, &p2);
108796       assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
108797       if( 0==*p1 || 0==*p2 ) break;
108798
108799       p1++;
108800       p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
108801       p2++;
108802       p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
108803     }
108804
108805     /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
108806     ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
108807     ** end of the position list, or the 0x01 that precedes the next 
108808     ** column-number in the position list. 
108809     */
108810     else if( iCol1<iCol2 ){
108811       fts3ColumnlistCopy(0, &p1);
108812       if( 0==*p1 ) break;
108813       p1++;
108814       p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
108815     }else{
108816       fts3ColumnlistCopy(0, &p2);
108817       if( 0==*p2 ) break;
108818       p2++;
108819       p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
108820     }
108821   }
108822
108823   fts3PoslistCopy(0, &p2);
108824   fts3PoslistCopy(0, &p1);
108825   *pp1 = p1;
108826   *pp2 = p2;
108827   if( !pp || *pp==p ){
108828     return 0;
108829   }
108830   *p++ = 0x00;
108831   *pp = p;
108832   return 1;
108833 }
108834
108835 /*
108836 ** Merge two position-lists as required by the NEAR operator.
108837 */
108838 static int fts3PoslistNearMerge(
108839   char **pp,                      /* Output buffer */
108840   char *aTmp,                     /* Temporary buffer space */
108841   int nRight,                     /* Maximum difference in token positions */
108842   int nLeft,                      /* Maximum difference in token positions */
108843   char **pp1,                     /* IN/OUT: Left input list */
108844   char **pp2                      /* IN/OUT: Right input list */
108845 ){
108846   char *p1 = *pp1;
108847   char *p2 = *pp2;
108848
108849   if( !pp ){
108850     if( fts3PoslistPhraseMerge(0, nRight, 0, pp1, pp2) ) return 1;
108851     *pp1 = p1;
108852     *pp2 = p2;
108853     return fts3PoslistPhraseMerge(0, nLeft, 0, pp2, pp1);
108854   }else{
108855     char *pTmp1 = aTmp;
108856     char *pTmp2;
108857     char *aTmp2;
108858     int res = 1;
108859
108860     fts3PoslistPhraseMerge(&pTmp1, nRight, 0, pp1, pp2);
108861     aTmp2 = pTmp2 = pTmp1;
108862     *pp1 = p1;
108863     *pp2 = p2;
108864     fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, pp2, pp1);
108865     if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
108866       fts3PoslistMerge(pp, &aTmp, &aTmp2);
108867     }else if( pTmp1!=aTmp ){
108868       fts3PoslistCopy(pp, &aTmp);
108869     }else if( pTmp2!=aTmp2 ){
108870       fts3PoslistCopy(pp, &aTmp2);
108871     }else{
108872       res = 0;
108873     }
108874
108875     return res;
108876   }
108877 }
108878
108879 /*
108880 ** Values that may be used as the first parameter to fts3DoclistMerge().
108881 */
108882 #define MERGE_NOT        2        /* D + D -> D */
108883 #define MERGE_AND        3        /* D + D -> D */
108884 #define MERGE_OR         4        /* D + D -> D */
108885 #define MERGE_POS_OR     5        /* P + P -> P */
108886 #define MERGE_PHRASE     6        /* P + P -> D */
108887 #define MERGE_POS_PHRASE 7        /* P + P -> P */
108888 #define MERGE_NEAR       8        /* P + P -> D */
108889 #define MERGE_POS_NEAR   9        /* P + P -> P */
108890
108891 /*
108892 ** Merge the two doclists passed in buffer a1 (size n1 bytes) and a2
108893 ** (size n2 bytes). The output is written to pre-allocated buffer aBuffer,
108894 ** which is guaranteed to be large enough to hold the results. The number
108895 ** of bytes written to aBuffer is stored in *pnBuffer before returning.
108896 **
108897 ** If successful, SQLITE_OK is returned. Otherwise, if a malloc error
108898 ** occurs while allocating a temporary buffer as part of the merge operation,
108899 ** SQLITE_NOMEM is returned.
108900 */
108901 static int fts3DoclistMerge(
108902   int mergetype,                  /* One of the MERGE_XXX constants */
108903   int nParam1,                    /* Used by MERGE_NEAR and MERGE_POS_NEAR */
108904   int nParam2,                    /* Used by MERGE_NEAR and MERGE_POS_NEAR */
108905   char *aBuffer,                  /* Pre-allocated output buffer */
108906   int *pnBuffer,                  /* OUT: Bytes written to aBuffer */
108907   char *a1,                       /* Buffer containing first doclist */
108908   int n1,                         /* Size of buffer a1 */
108909   char *a2,                       /* Buffer containing second doclist */
108910   int n2                          /* Size of buffer a2 */
108911 ){
108912   sqlite3_int64 i1 = 0;
108913   sqlite3_int64 i2 = 0;
108914   sqlite3_int64 iPrev = 0;
108915
108916   char *p = aBuffer;
108917   char *p1 = a1;
108918   char *p2 = a2;
108919   char *pEnd1 = &a1[n1];
108920   char *pEnd2 = &a2[n2];
108921
108922   assert( mergetype==MERGE_OR     || mergetype==MERGE_POS_OR 
108923        || mergetype==MERGE_AND    || mergetype==MERGE_NOT
108924        || mergetype==MERGE_PHRASE || mergetype==MERGE_POS_PHRASE
108925        || mergetype==MERGE_NEAR   || mergetype==MERGE_POS_NEAR
108926   );
108927
108928   if( !aBuffer ){
108929     *pnBuffer = 0;
108930     return SQLITE_NOMEM;
108931   }
108932
108933   /* Read the first docid from each doclist */
108934   fts3GetDeltaVarint2(&p1, pEnd1, &i1);
108935   fts3GetDeltaVarint2(&p2, pEnd2, &i2);
108936
108937   switch( mergetype ){
108938     case MERGE_OR:
108939     case MERGE_POS_OR:
108940       while( p1 || p2 ){
108941         if( p2 && p1 && i1==i2 ){
108942           fts3PutDeltaVarint(&p, &iPrev, i1);
108943           if( mergetype==MERGE_POS_OR ) fts3PoslistMerge(&p, &p1, &p2);
108944           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
108945           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
108946         }else if( !p2 || (p1 && i1<i2) ){
108947           fts3PutDeltaVarint(&p, &iPrev, i1);
108948           if( mergetype==MERGE_POS_OR ) fts3PoslistCopy(&p, &p1);
108949           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
108950         }else{
108951           fts3PutDeltaVarint(&p, &iPrev, i2);
108952           if( mergetype==MERGE_POS_OR ) fts3PoslistCopy(&p, &p2);
108953           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
108954         }
108955       }
108956       break;
108957
108958     case MERGE_AND:
108959       while( p1 && p2 ){
108960         if( i1==i2 ){
108961           fts3PutDeltaVarint(&p, &iPrev, i1);
108962           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
108963           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
108964         }else if( i1<i2 ){
108965           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
108966         }else{
108967           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
108968         }
108969       }
108970       break;
108971
108972     case MERGE_NOT:
108973       while( p1 ){
108974         if( p2 && i1==i2 ){
108975           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
108976           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
108977         }else if( !p2 || i1<i2 ){
108978           fts3PutDeltaVarint(&p, &iPrev, i1);
108979           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
108980         }else{
108981           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
108982         }
108983       }
108984       break;
108985
108986     case MERGE_POS_PHRASE:
108987     case MERGE_PHRASE: {
108988       char **ppPos = (mergetype==MERGE_PHRASE ? 0 : &p);
108989       while( p1 && p2 ){
108990         if( i1==i2 ){
108991           char *pSave = p;
108992           sqlite3_int64 iPrevSave = iPrev;
108993           fts3PutDeltaVarint(&p, &iPrev, i1);
108994           if( 0==fts3PoslistPhraseMerge(ppPos, 1, 0, &p1, &p2) ){
108995             p = pSave;
108996             iPrev = iPrevSave;
108997           }
108998           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
108999           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
109000         }else if( i1<i2 ){
109001           fts3PoslistCopy(0, &p1);
109002           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
109003         }else{
109004           fts3PoslistCopy(0, &p2);
109005           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
109006         }
109007       }
109008       break;
109009     }
109010
109011     default: assert( mergetype==MERGE_POS_NEAR || mergetype==MERGE_NEAR ); {
109012       char *aTmp = 0;
109013       char **ppPos = 0;
109014
109015       if( mergetype==MERGE_POS_NEAR ){
109016         ppPos = &p;
109017         aTmp = sqlite3_malloc(2*(n1+n2+1));
109018         if( !aTmp ){
109019           return SQLITE_NOMEM;
109020         }
109021       }
109022
109023       while( p1 && p2 ){
109024         if( i1==i2 ){
109025           char *pSave = p;
109026           sqlite3_int64 iPrevSave = iPrev;
109027           fts3PutDeltaVarint(&p, &iPrev, i1);
109028
109029           if( !fts3PoslistNearMerge(ppPos, aTmp, nParam1, nParam2, &p1, &p2) ){
109030             iPrev = iPrevSave;
109031             p = pSave;
109032           }
109033
109034           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
109035           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
109036         }else if( i1<i2 ){
109037           fts3PoslistCopy(0, &p1);
109038           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
109039         }else{
109040           fts3PoslistCopy(0, &p2);
109041           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
109042         }
109043       }
109044       sqlite3_free(aTmp);
109045       break;
109046     }
109047   }
109048
109049   *pnBuffer = (int)(p-aBuffer);
109050   return SQLITE_OK;
109051 }
109052
109053 /* 
109054 ** A pointer to an instance of this structure is used as the context 
109055 ** argument to sqlite3Fts3SegReaderIterate()
109056 */
109057 typedef struct TermSelect TermSelect;
109058 struct TermSelect {
109059   int isReqPos;
109060   char *aaOutput[16];             /* Malloc'd output buffer */
109061   int anOutput[16];               /* Size of output in bytes */
109062 };
109063
109064 /*
109065 ** Merge all doclists in the TermSelect.aaOutput[] array into a single
109066 ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
109067 ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
109068 **
109069 ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
109070 ** the responsibility of the caller to free any doclists left in the
109071 ** TermSelect.aaOutput[] array.
109072 */
109073 static int fts3TermSelectMerge(TermSelect *pTS){
109074   int mergetype = (pTS->isReqPos ? MERGE_POS_OR : MERGE_OR);
109075   char *aOut = 0;
109076   int nOut = 0;
109077   int i;
109078
109079   /* Loop through the doclists in the aaOutput[] array. Merge them all
109080   ** into a single doclist.
109081   */
109082   for(i=0; i<SizeofArray(pTS->aaOutput); i++){
109083     if( pTS->aaOutput[i] ){
109084       if( !aOut ){
109085         aOut = pTS->aaOutput[i];
109086         nOut = pTS->anOutput[i];
109087         pTS->aaOutput[0] = 0;
109088       }else{
109089         int nNew = nOut + pTS->anOutput[i];
109090         char *aNew = sqlite3_malloc(nNew);
109091         if( !aNew ){
109092           sqlite3_free(aOut);
109093           return SQLITE_NOMEM;
109094         }
109095         fts3DoclistMerge(mergetype, 0, 0,
109096             aNew, &nNew, pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut
109097         );
109098         sqlite3_free(pTS->aaOutput[i]);
109099         sqlite3_free(aOut);
109100         pTS->aaOutput[i] = 0;
109101         aOut = aNew;
109102         nOut = nNew;
109103       }
109104     }
109105   }
109106
109107   pTS->aaOutput[0] = aOut;
109108   pTS->anOutput[0] = nOut;
109109   return SQLITE_OK;
109110 }
109111
109112 /*
109113 ** This function is used as the sqlite3Fts3SegReaderIterate() callback when
109114 ** querying the full-text index for a doclist associated with a term or
109115 ** term-prefix.
109116 */
109117 static int fts3TermSelectCb(
109118   Fts3Table *p,                   /* Virtual table object */
109119   void *pContext,                 /* Pointer to TermSelect structure */
109120   char *zTerm,
109121   int nTerm,
109122   char *aDoclist,
109123   int nDoclist
109124 ){
109125   TermSelect *pTS = (TermSelect *)pContext;
109126
109127   UNUSED_PARAMETER(p);
109128   UNUSED_PARAMETER(zTerm);
109129   UNUSED_PARAMETER(nTerm);
109130
109131   if( pTS->aaOutput[0]==0 ){
109132     /* If this is the first term selected, copy the doclist to the output
109133     ** buffer using memcpy(). TODO: Add a way to transfer control of the
109134     ** aDoclist buffer from the caller so as to avoid the memcpy().
109135     */
109136     pTS->aaOutput[0] = sqlite3_malloc(nDoclist);
109137     pTS->anOutput[0] = nDoclist;
109138     if( pTS->aaOutput[0] ){
109139       memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
109140     }else{
109141       return SQLITE_NOMEM;
109142     }
109143   }else{
109144     int mergetype = (pTS->isReqPos ? MERGE_POS_OR : MERGE_OR);
109145     char *aMerge = aDoclist;
109146     int nMerge = nDoclist;
109147     int iOut;
109148
109149     for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
109150       char *aNew;
109151       int nNew;
109152       if( pTS->aaOutput[iOut]==0 ){
109153         assert( iOut>0 );
109154         pTS->aaOutput[iOut] = aMerge;
109155         pTS->anOutput[iOut] = nMerge;
109156         break;
109157       }
109158
109159       nNew = nMerge + pTS->anOutput[iOut];
109160       aNew = sqlite3_malloc(nNew);
109161       if( !aNew ){
109162         if( aMerge!=aDoclist ){
109163           sqlite3_free(aMerge);
109164         }
109165         return SQLITE_NOMEM;
109166       }
109167       fts3DoclistMerge(mergetype, 0, 0,
109168           aNew, &nNew, pTS->aaOutput[iOut], pTS->anOutput[iOut], aMerge, nMerge
109169       );
109170
109171       if( iOut>0 ) sqlite3_free(aMerge);
109172       sqlite3_free(pTS->aaOutput[iOut]);
109173       pTS->aaOutput[iOut] = 0;
109174
109175       aMerge = aNew;
109176       nMerge = nNew;
109177       if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
109178         pTS->aaOutput[iOut] = aMerge;
109179         pTS->anOutput[iOut] = nMerge;
109180       }
109181     }
109182   }
109183   return SQLITE_OK;
109184 }
109185
109186 /*
109187 ** This function retreives the doclist for the specified term (or term
109188 ** prefix) from the database. 
109189 **
109190 ** The returned doclist may be in one of two formats, depending on the 
109191 ** value of parameter isReqPos. If isReqPos is zero, then the doclist is
109192 ** a sorted list of delta-compressed docids (a bare doclist). If isReqPos
109193 ** is non-zero, then the returned list is in the same format as is stored 
109194 ** in the database without the found length specifier at the start of on-disk
109195 ** doclists.
109196 */
109197 static int fts3TermSelect(
109198   Fts3Table *p,                   /* Virtual table handle */
109199   int iColumn,                    /* Column to query (or -ve for all columns) */
109200   const char *zTerm,              /* Term to query for */
109201   int nTerm,                      /* Size of zTerm in bytes */
109202   int isPrefix,                   /* True for a prefix search */
109203   int isReqPos,                   /* True to include position lists in output */
109204   int *pnOut,                     /* OUT: Size of buffer at *ppOut */
109205   char **ppOut                    /* OUT: Malloced result buffer */
109206 ){
109207   int i;
109208   TermSelect tsc;
109209   Fts3SegFilter filter;           /* Segment term filter configuration */
109210   Fts3SegReader **apSegment;      /* Array of segments to read data from */
109211   int nSegment = 0;               /* Size of apSegment array */
109212   int nAlloc = 16;                /* Allocated size of segment array */
109213   int rc;                         /* Return code */
109214   sqlite3_stmt *pStmt = 0;        /* SQL statement to scan %_segdir table */
109215   int iAge = 0;                   /* Used to assign ages to segments */
109216
109217   apSegment = (Fts3SegReader **)sqlite3_malloc(sizeof(Fts3SegReader*)*nAlloc);
109218   if( !apSegment ) return SQLITE_NOMEM;
109219   rc = sqlite3Fts3SegReaderPending(p, zTerm, nTerm, isPrefix, &apSegment[0]);
109220   if( rc!=SQLITE_OK ) goto finished;
109221   if( apSegment[0] ){
109222     nSegment = 1;
109223   }
109224
109225   /* Loop through the entire %_segdir table. For each segment, create a
109226   ** Fts3SegReader to iterate through the subset of the segment leaves
109227   ** that may contain a term that matches zTerm/nTerm. For non-prefix
109228   ** searches, this is always a single leaf. For prefix searches, this
109229   ** may be a contiguous block of leaves.
109230   **
109231   ** The code in this loop does not actually load any leaves into memory
109232   ** (unless the root node happens to be a leaf). It simply examines the
109233   ** b-tree structure to determine which leaves need to be inspected.
109234   */
109235   rc = sqlite3Fts3AllSegdirs(p, &pStmt);
109236   while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
109237     Fts3SegReader *pNew = 0;
109238     int nRoot = sqlite3_column_bytes(pStmt, 4);
109239     char const *zRoot = sqlite3_column_blob(pStmt, 4);
109240     if( sqlite3_column_int64(pStmt, 1)==0 ){
109241       /* The entire segment is stored on the root node (which must be a
109242       ** leaf). Do not bother inspecting any data in this case, just
109243       ** create a Fts3SegReader to scan the single leaf. 
109244       */
109245       rc = sqlite3Fts3SegReaderNew(p, iAge, 0, 0, 0, zRoot, nRoot, &pNew);
109246     }else{
109247       int rc2;                    /* Return value of sqlite3Fts3ReadBlock() */
109248       sqlite3_int64 i1;           /* Blockid of leaf that may contain zTerm */
109249       rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &i1);
109250       if( rc==SQLITE_OK ){
109251         sqlite3_int64 i2 = sqlite3_column_int64(pStmt, 2);
109252         rc = sqlite3Fts3SegReaderNew(p, iAge, i1, i2, 0, 0, 0, &pNew);
109253       }
109254
109255       /* The following call to ReadBlock() serves to reset the SQL statement
109256       ** used to retrieve blocks of data from the %_segments table. If it is
109257       ** not reset here, then it may remain classified as an active statement 
109258       ** by SQLite, which may lead to "DROP TABLE" or "DETACH" commands 
109259       ** failing.
109260       */ 
109261       rc2 = sqlite3Fts3ReadBlock(p, 0, 0, 0);
109262       if( rc==SQLITE_OK ){
109263         rc = rc2;
109264       }
109265     }
109266     iAge++;
109267
109268     /* If a new Fts3SegReader was allocated, add it to the apSegment array. */
109269     assert( pNew!=0 || rc!=SQLITE_OK );
109270     if( pNew ){
109271       if( nSegment==nAlloc ){
109272         Fts3SegReader **pArray;
109273         nAlloc += 16;
109274         pArray = (Fts3SegReader **)sqlite3_realloc(
109275             apSegment, nAlloc*sizeof(Fts3SegReader *)
109276         );
109277         if( !pArray ){
109278           sqlite3Fts3SegReaderFree(p, pNew);
109279           rc = SQLITE_NOMEM;
109280           goto finished;
109281         }
109282         apSegment = pArray;
109283       }
109284       apSegment[nSegment++] = pNew;
109285     }
109286   }
109287   if( rc!=SQLITE_DONE ){
109288     assert( rc!=SQLITE_OK );
109289     goto finished;
109290   }
109291
109292   memset(&tsc, 0, sizeof(TermSelect));
109293   tsc.isReqPos = isReqPos;
109294
109295   filter.flags = FTS3_SEGMENT_IGNORE_EMPTY 
109296         | (isPrefix ? FTS3_SEGMENT_PREFIX : 0)
109297         | (isReqPos ? FTS3_SEGMENT_REQUIRE_POS : 0)
109298         | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
109299   filter.iCol = iColumn;
109300   filter.zTerm = zTerm;
109301   filter.nTerm = nTerm;
109302
109303   rc = sqlite3Fts3SegReaderIterate(p, apSegment, nSegment, &filter,
109304       fts3TermSelectCb, (void *)&tsc
109305   );
109306   if( rc==SQLITE_OK ){
109307     rc = fts3TermSelectMerge(&tsc);
109308   }
109309
109310   if( rc==SQLITE_OK ){
109311     *ppOut = tsc.aaOutput[0];
109312     *pnOut = tsc.anOutput[0];
109313   }else{
109314     for(i=0; i<SizeofArray(tsc.aaOutput); i++){
109315       sqlite3_free(tsc.aaOutput[i]);
109316     }
109317   }
109318
109319 finished:
109320   sqlite3_reset(pStmt);
109321   for(i=0; i<nSegment; i++){
109322     sqlite3Fts3SegReaderFree(p, apSegment[i]);
109323   }
109324   sqlite3_free(apSegment);
109325   return rc;
109326 }
109327
109328
109329 /* 
109330 ** Return a DocList corresponding to the phrase *pPhrase.
109331 */
109332 static int fts3PhraseSelect(
109333   Fts3Table *p,                   /* Virtual table handle */
109334   Fts3Phrase *pPhrase,            /* Phrase to return a doclist for */
109335   int isReqPos,                   /* True if output should contain positions */
109336   char **paOut,                   /* OUT: Pointer to malloc'd result buffer */
109337   int *pnOut                      /* OUT: Size of buffer at *paOut */
109338 ){
109339   char *pOut = 0;
109340   int nOut = 0;
109341   int rc = SQLITE_OK;
109342   int ii;
109343   int iCol = pPhrase->iColumn;
109344   int isTermPos = (pPhrase->nToken>1 || isReqPos);
109345
109346   for(ii=0; ii<pPhrase->nToken; ii++){
109347     struct PhraseToken *pTok = &pPhrase->aToken[ii];
109348     char *z = pTok->z;            /* Next token of the phrase */
109349     int n = pTok->n;              /* Size of z in bytes */
109350     int isPrefix = pTok->isPrefix;/* True if token is a prefix */
109351     char *pList;                  /* Pointer to token doclist */
109352     int nList;                    /* Size of buffer at pList */
109353
109354     rc = fts3TermSelect(p, iCol, z, n, isPrefix, isTermPos, &nList, &pList);
109355     if( rc!=SQLITE_OK ) break;
109356
109357     if( ii==0 ){
109358       pOut = pList;
109359       nOut = nList;
109360     }else{
109361       /* Merge the new term list and the current output. If this is the
109362       ** last term in the phrase, and positions are not required in the
109363       ** output of this function, the positions can be dropped as part
109364       ** of this merge. Either way, the result of this merge will be
109365       ** smaller than nList bytes. The code in fts3DoclistMerge() is written
109366       ** so that it is safe to use pList as the output as well as an input
109367       ** in this case.
109368       */
109369       int mergetype = MERGE_POS_PHRASE;
109370       if( ii==pPhrase->nToken-1 && !isReqPos ){
109371         mergetype = MERGE_PHRASE;
109372       }
109373       fts3DoclistMerge(mergetype, 0, 0, pList, &nOut, pOut, nOut, pList, nList);
109374       sqlite3_free(pOut);
109375       pOut = pList;
109376     }
109377     assert( nOut==0 || pOut!=0 );
109378   }
109379
109380   if( rc==SQLITE_OK ){
109381     *paOut = pOut;
109382     *pnOut = nOut;
109383   }else{
109384     sqlite3_free(pOut);
109385   }
109386   return rc;
109387 }
109388
109389 static int fts3NearMerge(
109390   int mergetype,                  /* MERGE_POS_NEAR or MERGE_NEAR */
109391   int nNear,                      /* Parameter to NEAR operator */
109392   int nTokenLeft,                 /* Number of tokens in LHS phrase arg */
109393   char *aLeft,                    /* Doclist for LHS (incl. positions) */
109394   int nLeft,                      /* Size of LHS doclist in bytes */
109395   int nTokenRight,                /* As nTokenLeft */
109396   char *aRight,                   /* As aLeft */
109397   int nRight,                     /* As nRight */
109398   char **paOut,                   /* OUT: Results of merge (malloced) */
109399   int *pnOut                      /* OUT: Sized of output buffer */
109400 ){
109401   char *aOut;
109402   int rc;
109403
109404   assert( mergetype==MERGE_POS_NEAR || MERGE_NEAR );
109405
109406   aOut = sqlite3_malloc(nLeft+nRight+1);
109407   if( aOut==0 ){
109408     rc = SQLITE_NOMEM;
109409   }else{
109410     rc = fts3DoclistMerge(mergetype, nNear+nTokenRight, nNear+nTokenLeft, 
109411       aOut, pnOut, aLeft, nLeft, aRight, nRight
109412     );
109413     if( rc!=SQLITE_OK ){
109414       sqlite3_free(aOut);
109415       aOut = 0;
109416     }
109417   }
109418
109419   *paOut = aOut;
109420   return rc;
109421 }
109422
109423 SQLITE_PRIVATE int sqlite3Fts3ExprNearTrim(Fts3Expr *pLeft, Fts3Expr *pRight, int nNear){
109424   int rc;
109425   if( pLeft->aDoclist==0 || pRight->aDoclist==0 ){
109426     sqlite3_free(pLeft->aDoclist);
109427     sqlite3_free(pRight->aDoclist);
109428     pRight->aDoclist = 0;
109429     pLeft->aDoclist = 0;
109430     rc = SQLITE_OK;
109431   }else{
109432     char *aOut;
109433     int nOut;
109434
109435     rc = fts3NearMerge(MERGE_POS_NEAR, nNear, 
109436         pLeft->pPhrase->nToken, pLeft->aDoclist, pLeft->nDoclist,
109437         pRight->pPhrase->nToken, pRight->aDoclist, pRight->nDoclist,
109438         &aOut, &nOut
109439     );
109440     if( rc!=SQLITE_OK ) return rc;
109441     sqlite3_free(pRight->aDoclist);
109442     pRight->aDoclist = aOut;
109443     pRight->nDoclist = nOut;
109444
109445     rc = fts3NearMerge(MERGE_POS_NEAR, nNear, 
109446         pRight->pPhrase->nToken, pRight->aDoclist, pRight->nDoclist,
109447         pLeft->pPhrase->nToken, pLeft->aDoclist, pLeft->nDoclist,
109448         &aOut, &nOut
109449     );
109450     sqlite3_free(pLeft->aDoclist);
109451     pLeft->aDoclist = aOut;
109452     pLeft->nDoclist = nOut;
109453   }
109454   return rc;
109455 }
109456
109457 /*
109458 ** Evaluate the full-text expression pExpr against fts3 table pTab. Store
109459 ** the resulting doclist in *paOut and *pnOut.  This routine mallocs for
109460 ** the space needed to store the output.  The caller is responsible for
109461 ** freeing the space when it has finished.
109462 */
109463 static int evalFts3Expr(
109464   Fts3Table *p,                   /* Virtual table handle */
109465   Fts3Expr *pExpr,                /* Parsed fts3 expression */
109466   char **paOut,                   /* OUT: Pointer to malloc'd result buffer */
109467   int *pnOut,                     /* OUT: Size of buffer at *paOut */
109468   int isReqPos                    /* Require positions in output buffer */
109469 ){
109470   int rc = SQLITE_OK;             /* Return code */
109471
109472   /* Zero the output parameters. */
109473   *paOut = 0;
109474   *pnOut = 0;
109475
109476   if( pExpr ){
109477     assert( pExpr->eType==FTSQUERY_PHRASE 
109478          || pExpr->eType==FTSQUERY_NEAR 
109479          || isReqPos==0
109480     );
109481     if( pExpr->eType==FTSQUERY_PHRASE ){
109482       rc = fts3PhraseSelect(p, pExpr->pPhrase, 
109483           isReqPos || (pExpr->pParent && pExpr->pParent->eType==FTSQUERY_NEAR),
109484           paOut, pnOut
109485       );
109486     }else{
109487       char *aLeft;
109488       char *aRight;
109489       int nLeft;
109490       int nRight;
109491
109492       if( 0==(rc = evalFts3Expr(p, pExpr->pRight, &aRight, &nRight, isReqPos))
109493        && 0==(rc = evalFts3Expr(p, pExpr->pLeft, &aLeft, &nLeft, isReqPos))
109494       ){
109495         assert( pExpr->eType==FTSQUERY_NEAR || pExpr->eType==FTSQUERY_OR     
109496             || pExpr->eType==FTSQUERY_AND  || pExpr->eType==FTSQUERY_NOT
109497         );
109498         switch( pExpr->eType ){
109499           case FTSQUERY_NEAR: {
109500             Fts3Expr *pLeft;
109501             Fts3Expr *pRight;
109502             int mergetype = isReqPos ? MERGE_POS_NEAR : MERGE_NEAR;
109503            
109504             if( pExpr->pParent && pExpr->pParent->eType==FTSQUERY_NEAR ){
109505               mergetype = MERGE_POS_NEAR;
109506             }
109507             pLeft = pExpr->pLeft;
109508             while( pLeft->eType==FTSQUERY_NEAR ){ 
109509               pLeft=pLeft->pRight;
109510             }
109511             pRight = pExpr->pRight;
109512             assert( pRight->eType==FTSQUERY_PHRASE );
109513             assert( pLeft->eType==FTSQUERY_PHRASE );
109514
109515             rc = fts3NearMerge(mergetype, pExpr->nNear, 
109516                 pLeft->pPhrase->nToken, aLeft, nLeft,
109517                 pRight->pPhrase->nToken, aRight, nRight,
109518                 paOut, pnOut
109519             );
109520             sqlite3_free(aLeft);
109521             break;
109522           }
109523
109524           case FTSQUERY_OR: {
109525             /* Allocate a buffer for the output. The maximum size is the
109526             ** sum of the sizes of the two input buffers. The +1 term is
109527             ** so that a buffer of zero bytes is never allocated - this can
109528             ** cause fts3DoclistMerge() to incorrectly return SQLITE_NOMEM.
109529             */
109530             char *aBuffer = sqlite3_malloc(nRight+nLeft+1);
109531             rc = fts3DoclistMerge(MERGE_OR, 0, 0, aBuffer, pnOut,
109532                 aLeft, nLeft, aRight, nRight
109533             );
109534             *paOut = aBuffer;
109535             sqlite3_free(aLeft);
109536             break;
109537           }
109538
109539           default: {
109540             assert( FTSQUERY_NOT==MERGE_NOT && FTSQUERY_AND==MERGE_AND );
109541             fts3DoclistMerge(pExpr->eType, 0, 0, aLeft, pnOut,
109542                 aLeft, nLeft, aRight, nRight
109543             );
109544             *paOut = aLeft;
109545             break;
109546           }
109547         }
109548       }
109549       sqlite3_free(aRight);
109550     }
109551   }
109552
109553   return rc;
109554 }
109555
109556 /*
109557 ** This is the xFilter interface for the virtual table.  See
109558 ** the virtual table xFilter method documentation for additional
109559 ** information.
109560 **
109561 ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
109562 ** the %_content table.
109563 **
109564 ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
109565 ** in the %_content table.
109566 **
109567 ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index.  The
109568 ** column on the left-hand side of the MATCH operator is column
109569 ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed.  argv[0] is the right-hand
109570 ** side of the MATCH operator.
109571 */
109572 /* TODO(shess) Upgrade the cursor initialization and destruction to
109573 ** account for fts3FilterMethod() being called multiple times on the
109574 ** same cursor. The current solution is very fragile. Apply fix to
109575 ** fts3 as appropriate.
109576 */
109577 static int fts3FilterMethod(
109578   sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
109579   int idxNum,                     /* Strategy index */
109580   const char *idxStr,             /* Unused */
109581   int nVal,                       /* Number of elements in apVal */
109582   sqlite3_value **apVal           /* Arguments for the indexing scheme */
109583 ){
109584   const char *azSql[] = {
109585     "SELECT * FROM %Q.'%q_content' WHERE docid = ?", /* non-full-table-scan */
109586     "SELECT * FROM %Q.'%q_content'",                 /* full-table-scan */
109587   };
109588   int rc;                         /* Return code */
109589   char *zSql;                     /* SQL statement used to access %_content */
109590   Fts3Table *p = (Fts3Table *)pCursor->pVtab;
109591   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
109592
109593   UNUSED_PARAMETER(idxStr);
109594   UNUSED_PARAMETER(nVal);
109595
109596   assert( idxNum>=0 && idxNum<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
109597   assert( nVal==0 || nVal==1 );
109598   assert( (nVal==0)==(idxNum==FTS3_FULLSCAN_SEARCH) );
109599
109600   /* In case the cursor has been used before, clear it now. */
109601   sqlite3_finalize(pCsr->pStmt);
109602   sqlite3_free(pCsr->aDoclist);
109603   sqlite3Fts3ExprFree(pCsr->pExpr);
109604   memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
109605
109606   /* Compile a SELECT statement for this cursor. For a full-table-scan, the
109607   ** statement loops through all rows of the %_content table. For a
109608   ** full-text query or docid lookup, the statement retrieves a single
109609   ** row by docid.
109610   */
109611   zSql = sqlite3_mprintf(azSql[idxNum==FTS3_FULLSCAN_SEARCH], p->zDb, p->zName);
109612   if( !zSql ){
109613     rc = SQLITE_NOMEM;
109614   }else{
109615     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
109616     sqlite3_free(zSql);
109617   }
109618   if( rc!=SQLITE_OK ) return rc;
109619   pCsr->eSearch = (i16)idxNum;
109620
109621   if( idxNum==FTS3_DOCID_SEARCH ){
109622     rc = sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
109623   }else if( idxNum!=FTS3_FULLSCAN_SEARCH ){
109624     int iCol = idxNum-FTS3_FULLTEXT_SEARCH;
109625     const char *zQuery = (const char *)sqlite3_value_text(apVal[0]);
109626
109627     if( zQuery==0 && sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
109628       return SQLITE_NOMEM;
109629     }
109630
109631     rc = sqlite3Fts3ExprParse(p->pTokenizer, p->azColumn, p->nColumn, 
109632         iCol, zQuery, -1, &pCsr->pExpr
109633     );
109634     if( rc!=SQLITE_OK ){
109635       if( rc==SQLITE_ERROR ){
109636         p->base.zErrMsg = sqlite3_mprintf("malformed MATCH expression: [%s]",
109637                                           zQuery);
109638       }
109639       return rc;
109640     }
109641
109642     rc = sqlite3Fts3ReadLock(p);
109643     if( rc!=SQLITE_OK ) return rc;
109644
109645     rc = evalFts3Expr(p, pCsr->pExpr, &pCsr->aDoclist, &pCsr->nDoclist, 0);
109646     pCsr->pNextId = pCsr->aDoclist;
109647     pCsr->iPrevId = 0;
109648   }
109649
109650   if( rc!=SQLITE_OK ) return rc;
109651   return fts3NextMethod(pCursor);
109652 }
109653
109654 /* 
109655 ** This is the xEof method of the virtual table. SQLite calls this 
109656 ** routine to find out if it has reached the end of a result set.
109657 */
109658 static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
109659   return ((Fts3Cursor *)pCursor)->isEof;
109660 }
109661
109662 /* 
109663 ** This is the xRowid method. The SQLite core calls this routine to
109664 ** retrieve the rowid for the current row of the result set. fts3
109665 ** exposes %_content.docid as the rowid for the virtual table. The
109666 ** rowid should be written to *pRowid.
109667 */
109668 static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
109669   Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
109670   if( pCsr->aDoclist ){
109671     *pRowid = pCsr->iPrevId;
109672   }else{
109673     *pRowid = sqlite3_column_int64(pCsr->pStmt, 0);
109674   }
109675   return SQLITE_OK;
109676 }
109677
109678 /* 
109679 ** This is the xColumn method, called by SQLite to request a value from
109680 ** the row that the supplied cursor currently points to.
109681 */
109682 static int fts3ColumnMethod(
109683   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
109684   sqlite3_context *pContext,      /* Context for sqlite3_result_xxx() calls */
109685   int iCol                        /* Index of column to read value from */
109686 ){
109687   int rc;                         /* Return Code */
109688   Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
109689   Fts3Table *p = (Fts3Table *)pCursor->pVtab;
109690
109691   /* The column value supplied by SQLite must be in range. */
109692   assert( iCol>=0 && iCol<=p->nColumn+1 );
109693
109694   if( iCol==p->nColumn+1 ){
109695     /* This call is a request for the "docid" column. Since "docid" is an 
109696     ** alias for "rowid", use the xRowid() method to obtain the value.
109697     */
109698     sqlite3_int64 iRowid;
109699     rc = fts3RowidMethod(pCursor, &iRowid);
109700     sqlite3_result_int64(pContext, iRowid);
109701   }else if( iCol==p->nColumn ){
109702     /* The extra column whose name is the same as the table.
109703     ** Return a blob which is a pointer to the cursor.
109704     */
109705     sqlite3_result_blob(pContext, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
109706     rc = SQLITE_OK;
109707   }else{
109708     rc = fts3CursorSeek(0, pCsr);
109709     if( rc==SQLITE_OK ){
109710       sqlite3_result_value(pContext, sqlite3_column_value(pCsr->pStmt, iCol+1));
109711     }
109712   }
109713   return rc;
109714 }
109715
109716 /* 
109717 ** This function is the implementation of the xUpdate callback used by 
109718 ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
109719 ** inserted, updated or deleted.
109720 */
109721 static int fts3UpdateMethod(
109722   sqlite3_vtab *pVtab,            /* Virtual table handle */
109723   int nArg,                       /* Size of argument array */
109724   sqlite3_value **apVal,          /* Array of arguments */
109725   sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
109726 ){
109727   return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
109728 }
109729
109730 /*
109731 ** Implementation of xSync() method. Flush the contents of the pending-terms
109732 ** hash-table to the database.
109733 */
109734 static int fts3SyncMethod(sqlite3_vtab *pVtab){
109735   return sqlite3Fts3PendingTermsFlush((Fts3Table *)pVtab);
109736 }
109737
109738 /*
109739 ** Implementation of xBegin() method. This is a no-op.
109740 */
109741 static int fts3BeginMethod(sqlite3_vtab *pVtab){
109742   UNUSED_PARAMETER(pVtab);
109743   assert( ((Fts3Table *)pVtab)->nPendingData==0 );
109744   return SQLITE_OK;
109745 }
109746
109747 /*
109748 ** Implementation of xCommit() method. This is a no-op. The contents of
109749 ** the pending-terms hash-table have already been flushed into the database
109750 ** by fts3SyncMethod().
109751 */
109752 static int fts3CommitMethod(sqlite3_vtab *pVtab){
109753   UNUSED_PARAMETER(pVtab);
109754   assert( ((Fts3Table *)pVtab)->nPendingData==0 );
109755   return SQLITE_OK;
109756 }
109757
109758 /*
109759 ** Implementation of xRollback(). Discard the contents of the pending-terms
109760 ** hash-table. Any changes made to the database are reverted by SQLite.
109761 */
109762 static int fts3RollbackMethod(sqlite3_vtab *pVtab){
109763   sqlite3Fts3PendingTermsClear((Fts3Table *)pVtab);
109764   return SQLITE_OK;
109765 }
109766
109767 /*
109768 ** Load the doclist associated with expression pExpr to pExpr->aDoclist.
109769 ** The loaded doclist contains positions as well as the document ids.
109770 ** This is used by the matchinfo(), snippet() and offsets() auxillary
109771 ** functions.
109772 */
109773 SQLITE_PRIVATE int sqlite3Fts3ExprLoadDoclist(Fts3Table *pTab, Fts3Expr *pExpr){
109774   return evalFts3Expr(pTab, pExpr, &pExpr->aDoclist, &pExpr->nDoclist, 1);
109775 }
109776
109777 /*
109778 ** After ExprLoadDoclist() (see above) has been called, this function is
109779 ** used to iterate/search through the position lists that make up the doclist
109780 ** stored in pExpr->aDoclist.
109781 */
109782 SQLITE_PRIVATE char *sqlite3Fts3FindPositions(
109783   Fts3Expr *pExpr,                /* Access this expressions doclist */
109784   sqlite3_int64 iDocid,           /* Docid associated with requested pos-list */
109785   int iCol                        /* Column of requested pos-list */
109786 ){
109787   assert( pExpr->isLoaded );
109788   if( pExpr->aDoclist ){
109789     char *pEnd = &pExpr->aDoclist[pExpr->nDoclist];
109790     char *pCsr = pExpr->pCurrent;
109791
109792     assert( pCsr );
109793     while( pCsr<pEnd ){
109794       if( pExpr->iCurrent<iDocid ){
109795         fts3PoslistCopy(0, &pCsr);
109796         if( pCsr<pEnd ){
109797           fts3GetDeltaVarint(&pCsr, &pExpr->iCurrent);
109798         }
109799         pExpr->pCurrent = pCsr;
109800       }else{
109801         if( pExpr->iCurrent==iDocid ){
109802           int iThis = 0;
109803           if( iCol<0 ){
109804             /* If iCol is negative, return a pointer to the start of the
109805             ** position-list (instead of a pointer to the start of a list
109806             ** of offsets associated with a specific column).
109807             */
109808             return pCsr;
109809           }
109810           while( iThis<iCol ){
109811             fts3ColumnlistCopy(0, &pCsr);
109812             if( *pCsr==0x00 ) return 0;
109813             pCsr++;
109814             pCsr += sqlite3Fts3GetVarint32(pCsr, &iThis);
109815           }
109816           if( iCol==iThis && (*pCsr&0xFE) ) return pCsr;
109817         }
109818         return 0;
109819       }
109820     }
109821   }
109822
109823   return 0;
109824 }
109825
109826 /*
109827 ** Helper function used by the implementation of the overloaded snippet(),
109828 ** offsets() and optimize() SQL functions.
109829 **
109830 ** If the value passed as the third argument is a blob of size
109831 ** sizeof(Fts3Cursor*), then the blob contents are copied to the 
109832 ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
109833 ** message is written to context pContext and SQLITE_ERROR returned. The
109834 ** string passed via zFunc is used as part of the error message.
109835 */
109836 static int fts3FunctionArg(
109837   sqlite3_context *pContext,      /* SQL function call context */
109838   const char *zFunc,              /* Function name */
109839   sqlite3_value *pVal,            /* argv[0] passed to function */
109840   Fts3Cursor **ppCsr         /* OUT: Store cursor handle here */
109841 ){
109842   Fts3Cursor *pRet;
109843   if( sqlite3_value_type(pVal)!=SQLITE_BLOB 
109844    || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
109845   ){
109846     char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
109847     sqlite3_result_error(pContext, zErr, -1);
109848     sqlite3_free(zErr);
109849     return SQLITE_ERROR;
109850   }
109851   memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
109852   *ppCsr = pRet;
109853   return SQLITE_OK;
109854 }
109855
109856 /*
109857 ** Implementation of the snippet() function for FTS3
109858 */
109859 static void fts3SnippetFunc(
109860   sqlite3_context *pContext,      /* SQLite function call context */
109861   int nVal,                       /* Size of apVal[] array */
109862   sqlite3_value **apVal           /* Array of arguments */
109863 ){
109864   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
109865   const char *zStart = "<b>";
109866   const char *zEnd = "</b>";
109867   const char *zEllipsis = "<b>...</b>";
109868   int iCol = -1;
109869   int nToken = 15;                /* Default number of tokens in snippet */
109870
109871   /* There must be at least one argument passed to this function (otherwise
109872   ** the non-overloaded version would have been called instead of this one).
109873   */
109874   assert( nVal>=1 );
109875
109876   if( nVal>6 ){
109877     sqlite3_result_error(pContext, 
109878         "wrong number of arguments to function snippet()", -1);
109879     return;
109880   }
109881   if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
109882
109883   switch( nVal ){
109884     case 6: nToken = sqlite3_value_int(apVal[5]);
109885     case 5: iCol = sqlite3_value_int(apVal[4]);
109886     case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
109887     case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
109888     case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
109889   }
109890   if( !zEllipsis || !zEnd || !zStart ){
109891     sqlite3_result_error_nomem(pContext);
109892   }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
109893     sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
109894   }
109895 }
109896
109897 /*
109898 ** Implementation of the offsets() function for FTS3
109899 */
109900 static void fts3OffsetsFunc(
109901   sqlite3_context *pContext,      /* SQLite function call context */
109902   int nVal,                       /* Size of argument array */
109903   sqlite3_value **apVal           /* Array of arguments */
109904 ){
109905   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
109906
109907   UNUSED_PARAMETER(nVal);
109908
109909   assert( nVal==1 );
109910   if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
109911   assert( pCsr );
109912   if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
109913     sqlite3Fts3Offsets(pContext, pCsr);
109914   }
109915 }
109916
109917 /* 
109918 ** Implementation of the special optimize() function for FTS3. This 
109919 ** function merges all segments in the database to a single segment.
109920 ** Example usage is:
109921 **
109922 **   SELECT optimize(t) FROM t LIMIT 1;
109923 **
109924 ** where 't' is the name of an FTS3 table.
109925 */
109926 static void fts3OptimizeFunc(
109927   sqlite3_context *pContext,      /* SQLite function call context */
109928   int nVal,                       /* Size of argument array */
109929   sqlite3_value **apVal           /* Array of arguments */
109930 ){
109931   int rc;                         /* Return code */
109932   Fts3Table *p;                   /* Virtual table handle */
109933   Fts3Cursor *pCursor;            /* Cursor handle passed through apVal[0] */
109934
109935   UNUSED_PARAMETER(nVal);
109936
109937   assert( nVal==1 );
109938   if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
109939   p = (Fts3Table *)pCursor->base.pVtab;
109940   assert( p );
109941
109942   rc = sqlite3Fts3Optimize(p);
109943
109944   switch( rc ){
109945     case SQLITE_OK:
109946       sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
109947       break;
109948     case SQLITE_DONE:
109949       sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
109950       break;
109951     default:
109952       sqlite3_result_error_code(pContext, rc);
109953       break;
109954   }
109955 }
109956
109957 /*
109958 ** Implementation of the matchinfo() function for FTS3
109959 */
109960 static void fts3MatchinfoFunc(
109961   sqlite3_context *pContext,      /* SQLite function call context */
109962   int nVal,                       /* Size of argument array */
109963   sqlite3_value **apVal           /* Array of arguments */
109964 ){
109965   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
109966
109967   if( nVal!=1 ){
109968     sqlite3_result_error(pContext,
109969         "wrong number of arguments to function matchinfo()", -1);
109970     return;
109971   }
109972
109973   if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
109974     sqlite3Fts3Matchinfo(pContext, pCsr);
109975   }
109976 }
109977
109978 /*
109979 ** This routine implements the xFindFunction method for the FTS3
109980 ** virtual table.
109981 */
109982 static int fts3FindFunctionMethod(
109983   sqlite3_vtab *pVtab,            /* Virtual table handle */
109984   int nArg,                       /* Number of SQL function arguments */
109985   const char *zName,              /* Name of SQL function */
109986   void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
109987   void **ppArg                    /* Unused */
109988 ){
109989   struct Overloaded {
109990     const char *zName;
109991     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
109992   } aOverload[] = {
109993     { "snippet", fts3SnippetFunc },
109994     { "offsets", fts3OffsetsFunc },
109995     { "optimize", fts3OptimizeFunc },
109996     { "matchinfo", fts3MatchinfoFunc },
109997   };
109998   int i;                          /* Iterator variable */
109999
110000   UNUSED_PARAMETER(pVtab);
110001   UNUSED_PARAMETER(nArg);
110002   UNUSED_PARAMETER(ppArg);
110003
110004   for(i=0; i<SizeofArray(aOverload); i++){
110005     if( strcmp(zName, aOverload[i].zName)==0 ){
110006       *pxFunc = aOverload[i].xFunc;
110007       return 1;
110008     }
110009   }
110010
110011   /* No function of the specified name was found. Return 0. */
110012   return 0;
110013 }
110014
110015 /*
110016 ** Implementation of FTS3 xRename method. Rename an fts3 table.
110017 */
110018 static int fts3RenameMethod(
110019   sqlite3_vtab *pVtab,            /* Virtual table handle */
110020   const char *zName               /* New name of table */
110021 ){
110022   Fts3Table *p = (Fts3Table *)pVtab;
110023   sqlite3 *db = p->db;            /* Database connection */
110024   int rc;                         /* Return Code */
110025
110026   rc = sqlite3Fts3PendingTermsFlush(p);
110027   if( rc!=SQLITE_OK ){
110028     return rc;
110029   }
110030
110031   fts3DbExec(&rc, db,
110032     "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';",
110033     p->zDb, p->zName, zName
110034   );
110035   if( rc==SQLITE_ERROR ) rc = SQLITE_OK;
110036   if( p->bHasDocsize ){
110037     fts3DbExec(&rc, db,
110038       "ALTER TABLE %Q.'%q_docsize'  RENAME TO '%q_docsize';",
110039       p->zDb, p->zName, zName
110040     );
110041     fts3DbExec(&rc, db,
110042       "ALTER TABLE %Q.'%q_stat'  RENAME TO '%q_stat';",
110043       p->zDb, p->zName, zName
110044     );
110045   }
110046   fts3DbExec(&rc, db,
110047     "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
110048     p->zDb, p->zName, zName
110049   );
110050   fts3DbExec(&rc, db,
110051     "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';",
110052     p->zDb, p->zName, zName
110053   );
110054   return rc;
110055 }
110056
110057 static const sqlite3_module fts3Module = {
110058   /* iVersion      */ 0,
110059   /* xCreate       */ fts3CreateMethod,
110060   /* xConnect      */ fts3ConnectMethod,
110061   /* xBestIndex    */ fts3BestIndexMethod,
110062   /* xDisconnect   */ fts3DisconnectMethod,
110063   /* xDestroy      */ fts3DestroyMethod,
110064   /* xOpen         */ fts3OpenMethod,
110065   /* xClose        */ fulltextClose,
110066   /* xFilter       */ fts3FilterMethod,
110067   /* xNext         */ fts3NextMethod,
110068   /* xEof          */ fts3EofMethod,
110069   /* xColumn       */ fts3ColumnMethod,
110070   /* xRowid        */ fts3RowidMethod,
110071   /* xUpdate       */ fts3UpdateMethod,
110072   /* xBegin        */ fts3BeginMethod,
110073   /* xSync         */ fts3SyncMethod,
110074   /* xCommit       */ fts3CommitMethod,
110075   /* xRollback     */ fts3RollbackMethod,
110076   /* xFindFunction */ fts3FindFunctionMethod,
110077   /* xRename */       fts3RenameMethod,
110078 };
110079
110080 /*
110081 ** This function is registered as the module destructor (called when an
110082 ** FTS3 enabled database connection is closed). It frees the memory
110083 ** allocated for the tokenizer hash table.
110084 */
110085 static void hashDestroy(void *p){
110086   Fts3Hash *pHash = (Fts3Hash *)p;
110087   sqlite3Fts3HashClear(pHash);
110088   sqlite3_free(pHash);
110089 }
110090
110091 /*
110092 ** The fts3 built-in tokenizers - "simple" and "porter" - are implemented
110093 ** in files fts3_tokenizer1.c and fts3_porter.c respectively. The following
110094 ** two forward declarations are for functions declared in these files
110095 ** used to retrieve the respective implementations.
110096 **
110097 ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
110098 ** to by the argument to point to the "simple" tokenizer implementation.
110099 ** Function ...PorterTokenizerModule() sets *pModule to point to the
110100 ** porter tokenizer/stemmer implementation.
110101 */
110102 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
110103 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
110104 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
110105
110106 /*
110107 ** Initialise the fts3 extension. If this extension is built as part
110108 ** of the sqlite library, then this function is called directly by
110109 ** SQLite. If fts3 is built as a dynamically loadable extension, this
110110 ** function is called by the sqlite3_extension_init() entry point.
110111 */
110112 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
110113   int rc = SQLITE_OK;
110114   Fts3Hash *pHash = 0;
110115   const sqlite3_tokenizer_module *pSimple = 0;
110116   const sqlite3_tokenizer_module *pPorter = 0;
110117
110118 #ifdef SQLITE_ENABLE_ICU
110119   const sqlite3_tokenizer_module *pIcu = 0;
110120   sqlite3Fts3IcuTokenizerModule(&pIcu);
110121 #endif
110122
110123   sqlite3Fts3SimpleTokenizerModule(&pSimple);
110124   sqlite3Fts3PorterTokenizerModule(&pPorter);
110125
110126   /* Allocate and initialise the hash-table used to store tokenizers. */
110127   pHash = sqlite3_malloc(sizeof(Fts3Hash));
110128   if( !pHash ){
110129     rc = SQLITE_NOMEM;
110130   }else{
110131     sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
110132   }
110133
110134   /* Load the built-in tokenizers into the hash table */
110135   if( rc==SQLITE_OK ){
110136     if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
110137      || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter) 
110138 #ifdef SQLITE_ENABLE_ICU
110139      || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
110140 #endif
110141     ){
110142       rc = SQLITE_NOMEM;
110143     }
110144   }
110145
110146 #ifdef SQLITE_TEST
110147   if( rc==SQLITE_OK ){
110148     rc = sqlite3Fts3ExprInitTestInterface(db);
110149   }
110150 #endif
110151
110152   /* Create the virtual table wrapper around the hash-table and overload 
110153   ** the two scalar functions. If this is successful, register the
110154   ** module with sqlite.
110155   */
110156   if( SQLITE_OK==rc 
110157    && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
110158    && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
110159    && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
110160    && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", -1))
110161    && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
110162   ){
110163     rc = sqlite3_create_module_v2(
110164         db, "fts3", &fts3Module, (void *)pHash, hashDestroy
110165     );
110166     if( rc==SQLITE_OK ){
110167       rc = sqlite3_create_module_v2(
110168           db, "fts4", &fts3Module, (void *)pHash, 0
110169       );
110170     }
110171     return rc;
110172   }
110173
110174   /* An error has occurred. Delete the hash table and return the error code. */
110175   assert( rc!=SQLITE_OK );
110176   if( pHash ){
110177     sqlite3Fts3HashClear(pHash);
110178     sqlite3_free(pHash);
110179   }
110180   return rc;
110181 }
110182
110183 #if !SQLITE_CORE
110184 SQLITE_API int sqlite3_extension_init(
110185   sqlite3 *db, 
110186   char **pzErrMsg,
110187   const sqlite3_api_routines *pApi
110188 ){
110189   SQLITE_EXTENSION_INIT2(pApi)
110190   return sqlite3Fts3Init(db);
110191 }
110192 #endif
110193
110194 #endif
110195
110196 /************** End of fts3.c ************************************************/
110197 /************** Begin file fts3_expr.c ***************************************/
110198 /*
110199 ** 2008 Nov 28
110200 **
110201 ** The author disclaims copyright to this source code.  In place of
110202 ** a legal notice, here is a blessing:
110203 **
110204 **    May you do good and not evil.
110205 **    May you find forgiveness for yourself and forgive others.
110206 **    May you share freely, never taking more than you give.
110207 **
110208 ******************************************************************************
110209 **
110210 ** This module contains code that implements a parser for fts3 query strings
110211 ** (the right-hand argument to the MATCH operator). Because the supported 
110212 ** syntax is relatively simple, the whole tokenizer/parser system is
110213 ** hand-coded. 
110214 */
110215 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
110216
110217 /*
110218 ** By default, this module parses the legacy syntax that has been 
110219 ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
110220 ** is defined, then it uses the new syntax. The differences between
110221 ** the new and the old syntaxes are:
110222 **
110223 **  a) The new syntax supports parenthesis. The old does not.
110224 **
110225 **  b) The new syntax supports the AND and NOT operators. The old does not.
110226 **
110227 **  c) The old syntax supports the "-" token qualifier. This is not 
110228 **     supported by the new syntax (it is replaced by the NOT operator).
110229 **
110230 **  d) When using the old syntax, the OR operator has a greater precedence
110231 **     than an implicit AND. When using the new, both implicity and explicit
110232 **     AND operators have a higher precedence than OR.
110233 **
110234 ** If compiled with SQLITE_TEST defined, then this module exports the
110235 ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
110236 ** to zero causes the module to use the old syntax. If it is set to 
110237 ** non-zero the new syntax is activated. This is so both syntaxes can
110238 ** be tested using a single build of testfixture.
110239 **
110240 ** The following describes the syntax supported by the fts3 MATCH
110241 ** operator in a similar format to that used by the lemon parser
110242 ** generator. This module does not use actually lemon, it uses a
110243 ** custom parser.
110244 **
110245 **   query ::= andexpr (OR andexpr)*.
110246 **
110247 **   andexpr ::= notexpr (AND? notexpr)*.
110248 **
110249 **   notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
110250 **   notexpr ::= LP query RP.
110251 **
110252 **   nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
110253 **
110254 **   distance_opt ::= .
110255 **   distance_opt ::= / INTEGER.
110256 **
110257 **   phrase ::= TOKEN.
110258 **   phrase ::= COLUMN:TOKEN.
110259 **   phrase ::= "TOKEN TOKEN TOKEN...".
110260 */
110261
110262 #ifdef SQLITE_TEST
110263 SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
110264 #else
110265 # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS 
110266 #  define sqlite3_fts3_enable_parentheses 1
110267 # else
110268 #  define sqlite3_fts3_enable_parentheses 0
110269 # endif
110270 #endif
110271
110272 /*
110273 ** Default span for NEAR operators.
110274 */
110275 #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
110276
110277
110278 typedef struct ParseContext ParseContext;
110279 struct ParseContext {
110280   sqlite3_tokenizer *pTokenizer;      /* Tokenizer module */
110281   const char **azCol;                 /* Array of column names for fts3 table */
110282   int nCol;                           /* Number of entries in azCol[] */
110283   int iDefaultCol;                    /* Default column to query */
110284   sqlite3_context *pCtx;              /* Write error message here */
110285   int nNest;                          /* Number of nested brackets */
110286 };
110287
110288 /*
110289 ** This function is equivalent to the standard isspace() function. 
110290 **
110291 ** The standard isspace() can be awkward to use safely, because although it
110292 ** is defined to accept an argument of type int, its behaviour when passed
110293 ** an integer that falls outside of the range of the unsigned char type
110294 ** is undefined (and sometimes, "undefined" means segfault). This wrapper
110295 ** is defined to accept an argument of type char, and always returns 0 for
110296 ** any values that fall outside of the range of the unsigned char type (i.e.
110297 ** negative values).
110298 */
110299 static int fts3isspace(char c){
110300   return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
110301 }
110302
110303 /*
110304 ** Extract the next token from buffer z (length n) using the tokenizer
110305 ** and other information (column names etc.) in pParse. Create an Fts3Expr
110306 ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
110307 ** single token and set *ppExpr to point to it. If the end of the buffer is
110308 ** reached before a token is found, set *ppExpr to zero. It is the
110309 ** responsibility of the caller to eventually deallocate the allocated 
110310 ** Fts3Expr structure (if any) by passing it to sqlite3_free().
110311 **
110312 ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
110313 ** fails.
110314 */
110315 static int getNextToken(
110316   ParseContext *pParse,                   /* fts3 query parse context */
110317   int iCol,                               /* Value for Fts3Phrase.iColumn */
110318   const char *z, int n,                   /* Input string */
110319   Fts3Expr **ppExpr,                      /* OUT: expression */
110320   int *pnConsumed                         /* OUT: Number of bytes consumed */
110321 ){
110322   sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
110323   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
110324   int rc;
110325   sqlite3_tokenizer_cursor *pCursor;
110326   Fts3Expr *pRet = 0;
110327   int nConsumed = 0;
110328
110329   rc = pModule->xOpen(pTokenizer, z, n, &pCursor);
110330   if( rc==SQLITE_OK ){
110331     const char *zToken;
110332     int nToken, iStart, iEnd, iPosition;
110333     int nByte;                               /* total space to allocate */
110334
110335     pCursor->pTokenizer = pTokenizer;
110336     rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
110337
110338     if( rc==SQLITE_OK ){
110339       nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
110340       pRet = (Fts3Expr *)sqlite3_malloc(nByte);
110341       if( !pRet ){
110342         rc = SQLITE_NOMEM;
110343       }else{
110344         memset(pRet, 0, nByte);
110345         pRet->eType = FTSQUERY_PHRASE;
110346         pRet->pPhrase = (Fts3Phrase *)&pRet[1];
110347         pRet->pPhrase->nToken = 1;
110348         pRet->pPhrase->iColumn = iCol;
110349         pRet->pPhrase->aToken[0].n = nToken;
110350         pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
110351         memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
110352
110353         if( iEnd<n && z[iEnd]=='*' ){
110354           pRet->pPhrase->aToken[0].isPrefix = 1;
110355           iEnd++;
110356         }
110357         if( !sqlite3_fts3_enable_parentheses && iStart>0 && z[iStart-1]=='-' ){
110358           pRet->pPhrase->isNot = 1;
110359         }
110360       }
110361       nConsumed = iEnd;
110362     }
110363
110364     pModule->xClose(pCursor);
110365   }
110366   
110367   *pnConsumed = nConsumed;
110368   *ppExpr = pRet;
110369   return rc;
110370 }
110371
110372
110373 /*
110374 ** Enlarge a memory allocation.  If an out-of-memory allocation occurs,
110375 ** then free the old allocation.
110376 */
110377 static void *fts3ReallocOrFree(void *pOrig, int nNew){
110378   void *pRet = sqlite3_realloc(pOrig, nNew);
110379   if( !pRet ){
110380     sqlite3_free(pOrig);
110381   }
110382   return pRet;
110383 }
110384
110385 /*
110386 ** Buffer zInput, length nInput, contains the contents of a quoted string
110387 ** that appeared as part of an fts3 query expression. Neither quote character
110388 ** is included in the buffer. This function attempts to tokenize the entire
110389 ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE 
110390 ** containing the results.
110391 **
110392 ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
110393 ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
110394 ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
110395 ** to 0.
110396 */
110397 static int getNextString(
110398   ParseContext *pParse,                   /* fts3 query parse context */
110399   const char *zInput, int nInput,         /* Input string */
110400   Fts3Expr **ppExpr                       /* OUT: expression */
110401 ){
110402   sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
110403   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
110404   int rc;
110405   Fts3Expr *p = 0;
110406   sqlite3_tokenizer_cursor *pCursor = 0;
110407   char *zTemp = 0;
110408   int nTemp = 0;
110409
110410   rc = pModule->xOpen(pTokenizer, zInput, nInput, &pCursor);
110411   if( rc==SQLITE_OK ){
110412     int ii;
110413     pCursor->pTokenizer = pTokenizer;
110414     for(ii=0; rc==SQLITE_OK; ii++){
110415       const char *zToken;
110416       int nToken, iBegin, iEnd, iPos;
110417       rc = pModule->xNext(pCursor, &zToken, &nToken, &iBegin, &iEnd, &iPos);
110418       if( rc==SQLITE_OK ){
110419         int nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
110420         p = fts3ReallocOrFree(p, nByte+ii*sizeof(struct PhraseToken));
110421         zTemp = fts3ReallocOrFree(zTemp, nTemp + nToken);
110422         if( !p || !zTemp ){
110423           goto no_mem;
110424         }
110425         if( ii==0 ){
110426           memset(p, 0, nByte);
110427           p->pPhrase = (Fts3Phrase *)&p[1];
110428         }
110429         p->pPhrase = (Fts3Phrase *)&p[1];
110430         p->pPhrase->nToken = ii+1;
110431         p->pPhrase->aToken[ii].n = nToken;
110432         memcpy(&zTemp[nTemp], zToken, nToken);
110433         nTemp += nToken;
110434         if( iEnd<nInput && zInput[iEnd]=='*' ){
110435           p->pPhrase->aToken[ii].isPrefix = 1;
110436         }else{
110437           p->pPhrase->aToken[ii].isPrefix = 0;
110438         }
110439       }
110440     }
110441
110442     pModule->xClose(pCursor);
110443     pCursor = 0;
110444   }
110445
110446   if( rc==SQLITE_DONE ){
110447     int jj;
110448     char *zNew = NULL;
110449     int nNew = 0;
110450     int nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
110451     nByte += (p?(p->pPhrase->nToken-1):0) * sizeof(struct PhraseToken);
110452     p = fts3ReallocOrFree(p, nByte + nTemp);
110453     if( !p ){
110454       goto no_mem;
110455     }
110456     if( zTemp ){
110457       zNew = &(((char *)p)[nByte]);
110458       memcpy(zNew, zTemp, nTemp);
110459     }else{
110460       memset(p, 0, nByte+nTemp);
110461     }
110462     p->pPhrase = (Fts3Phrase *)&p[1];
110463     for(jj=0; jj<p->pPhrase->nToken; jj++){
110464       p->pPhrase->aToken[jj].z = &zNew[nNew];
110465       nNew += p->pPhrase->aToken[jj].n;
110466     }
110467     sqlite3_free(zTemp);
110468     p->eType = FTSQUERY_PHRASE;
110469     p->pPhrase->iColumn = pParse->iDefaultCol;
110470     rc = SQLITE_OK;
110471   }
110472
110473   *ppExpr = p;
110474   return rc;
110475 no_mem:
110476
110477   if( pCursor ){
110478     pModule->xClose(pCursor);
110479   }
110480   sqlite3_free(zTemp);
110481   sqlite3_free(p);
110482   *ppExpr = 0;
110483   return SQLITE_NOMEM;
110484 }
110485
110486 /*
110487 ** Function getNextNode(), which is called by fts3ExprParse(), may itself
110488 ** call fts3ExprParse(). So this forward declaration is required.
110489 */
110490 static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
110491
110492 /*
110493 ** The output variable *ppExpr is populated with an allocated Fts3Expr 
110494 ** structure, or set to 0 if the end of the input buffer is reached.
110495 **
110496 ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
110497 ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
110498 ** If SQLITE_ERROR is returned, pContext is populated with an error message.
110499 */
110500 static int getNextNode(
110501   ParseContext *pParse,                   /* fts3 query parse context */
110502   const char *z, int n,                   /* Input string */
110503   Fts3Expr **ppExpr,                      /* OUT: expression */
110504   int *pnConsumed                         /* OUT: Number of bytes consumed */
110505 ){
110506   static const struct Fts3Keyword {
110507     char *z;                              /* Keyword text */
110508     unsigned char n;                      /* Length of the keyword */
110509     unsigned char parenOnly;              /* Only valid in paren mode */
110510     unsigned char eType;                  /* Keyword code */
110511   } aKeyword[] = {
110512     { "OR" ,  2, 0, FTSQUERY_OR   },
110513     { "AND",  3, 1, FTSQUERY_AND  },
110514     { "NOT",  3, 1, FTSQUERY_NOT  },
110515     { "NEAR", 4, 0, FTSQUERY_NEAR }
110516   };
110517   int ii;
110518   int iCol;
110519   int iColLen;
110520   int rc;
110521   Fts3Expr *pRet = 0;
110522
110523   const char *zInput = z;
110524   int nInput = n;
110525
110526   /* Skip over any whitespace before checking for a keyword, an open or
110527   ** close bracket, or a quoted string. 
110528   */
110529   while( nInput>0 && fts3isspace(*zInput) ){
110530     nInput--;
110531     zInput++;
110532   }
110533   if( nInput==0 ){
110534     return SQLITE_DONE;
110535   }
110536
110537   /* See if we are dealing with a keyword. */
110538   for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
110539     const struct Fts3Keyword *pKey = &aKeyword[ii];
110540
110541     if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
110542       continue;
110543     }
110544
110545     if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
110546       int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
110547       int nKey = pKey->n;
110548       char cNext;
110549
110550       /* If this is a "NEAR" keyword, check for an explicit nearness. */
110551       if( pKey->eType==FTSQUERY_NEAR ){
110552         assert( nKey==4 );
110553         if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
110554           nNear = 0;
110555           for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
110556             nNear = nNear * 10 + (zInput[nKey] - '0');
110557           }
110558         }
110559       }
110560
110561       /* At this point this is probably a keyword. But for that to be true,
110562       ** the next byte must contain either whitespace, an open or close
110563       ** parenthesis, a quote character, or EOF. 
110564       */
110565       cNext = zInput[nKey];
110566       if( fts3isspace(cNext) 
110567        || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
110568       ){
110569         pRet = (Fts3Expr *)sqlite3_malloc(sizeof(Fts3Expr));
110570         if( !pRet ){
110571           return SQLITE_NOMEM;
110572         }
110573         memset(pRet, 0, sizeof(Fts3Expr));
110574         pRet->eType = pKey->eType;
110575         pRet->nNear = nNear;
110576         *ppExpr = pRet;
110577         *pnConsumed = (int)((zInput - z) + nKey);
110578         return SQLITE_OK;
110579       }
110580
110581       /* Turns out that wasn't a keyword after all. This happens if the
110582       ** user has supplied a token such as "ORacle". Continue.
110583       */
110584     }
110585   }
110586
110587   /* Check for an open bracket. */
110588   if( sqlite3_fts3_enable_parentheses ){
110589     if( *zInput=='(' ){
110590       int nConsumed;
110591       int rc;
110592       pParse->nNest++;
110593       rc = fts3ExprParse(pParse, &zInput[1], nInput-1, ppExpr, &nConsumed);
110594       if( rc==SQLITE_OK && !*ppExpr ){
110595         rc = SQLITE_DONE;
110596       }
110597       *pnConsumed = (int)((zInput - z) + 1 + nConsumed);
110598       return rc;
110599     }
110600   
110601     /* Check for a close bracket. */
110602     if( *zInput==')' ){
110603       pParse->nNest--;
110604       *pnConsumed = (int)((zInput - z) + 1);
110605       return SQLITE_DONE;
110606     }
110607   }
110608
110609   /* See if we are dealing with a quoted phrase. If this is the case, then
110610   ** search for the closing quote and pass the whole string to getNextString()
110611   ** for processing. This is easy to do, as fts3 has no syntax for escaping
110612   ** a quote character embedded in a string.
110613   */
110614   if( *zInput=='"' ){
110615     for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
110616     *pnConsumed = (int)((zInput - z) + ii + 1);
110617     if( ii==nInput ){
110618       return SQLITE_ERROR;
110619     }
110620     return getNextString(pParse, &zInput[1], ii-1, ppExpr);
110621   }
110622
110623
110624   /* If control flows to this point, this must be a regular token, or 
110625   ** the end of the input. Read a regular token using the sqlite3_tokenizer
110626   ** interface. Before doing so, figure out if there is an explicit
110627   ** column specifier for the token. 
110628   **
110629   ** TODO: Strangely, it is not possible to associate a column specifier
110630   ** with a quoted phrase, only with a single token. Not sure if this was
110631   ** an implementation artifact or an intentional decision when fts3 was
110632   ** first implemented. Whichever it was, this module duplicates the 
110633   ** limitation.
110634   */
110635   iCol = pParse->iDefaultCol;
110636   iColLen = 0;
110637   for(ii=0; ii<pParse->nCol; ii++){
110638     const char *zStr = pParse->azCol[ii];
110639     int nStr = (int)strlen(zStr);
110640     if( nInput>nStr && zInput[nStr]==':' 
110641      && sqlite3_strnicmp(zStr, zInput, nStr)==0 
110642     ){
110643       iCol = ii;
110644       iColLen = (int)((zInput - z) + nStr + 1);
110645       break;
110646     }
110647   }
110648   rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
110649   *pnConsumed += iColLen;
110650   return rc;
110651 }
110652
110653 /*
110654 ** The argument is an Fts3Expr structure for a binary operator (any type
110655 ** except an FTSQUERY_PHRASE). Return an integer value representing the
110656 ** precedence of the operator. Lower values have a higher precedence (i.e.
110657 ** group more tightly). For example, in the C language, the == operator
110658 ** groups more tightly than ||, and would therefore have a higher precedence.
110659 **
110660 ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
110661 ** is defined), the order of the operators in precedence from highest to
110662 ** lowest is:
110663 **
110664 **   NEAR
110665 **   NOT
110666 **   AND (including implicit ANDs)
110667 **   OR
110668 **
110669 ** Note that when using the old query syntax, the OR operator has a higher
110670 ** precedence than the AND operator.
110671 */
110672 static int opPrecedence(Fts3Expr *p){
110673   assert( p->eType!=FTSQUERY_PHRASE );
110674   if( sqlite3_fts3_enable_parentheses ){
110675     return p->eType;
110676   }else if( p->eType==FTSQUERY_NEAR ){
110677     return 1;
110678   }else if( p->eType==FTSQUERY_OR ){
110679     return 2;
110680   }
110681   assert( p->eType==FTSQUERY_AND );
110682   return 3;
110683 }
110684
110685 /*
110686 ** Argument ppHead contains a pointer to the current head of a query 
110687 ** expression tree being parsed. pPrev is the expression node most recently
110688 ** inserted into the tree. This function adds pNew, which is always a binary
110689 ** operator node, into the expression tree based on the relative precedence
110690 ** of pNew and the existing nodes of the tree. This may result in the head
110691 ** of the tree changing, in which case *ppHead is set to the new root node.
110692 */
110693 static void insertBinaryOperator(
110694   Fts3Expr **ppHead,       /* Pointer to the root node of a tree */
110695   Fts3Expr *pPrev,         /* Node most recently inserted into the tree */
110696   Fts3Expr *pNew           /* New binary node to insert into expression tree */
110697 ){
110698   Fts3Expr *pSplit = pPrev;
110699   while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
110700     pSplit = pSplit->pParent;
110701   }
110702
110703   if( pSplit->pParent ){
110704     assert( pSplit->pParent->pRight==pSplit );
110705     pSplit->pParent->pRight = pNew;
110706     pNew->pParent = pSplit->pParent;
110707   }else{
110708     *ppHead = pNew;
110709   }
110710   pNew->pLeft = pSplit;
110711   pSplit->pParent = pNew;
110712 }
110713
110714 /*
110715 ** Parse the fts3 query expression found in buffer z, length n. This function
110716 ** returns either when the end of the buffer is reached or an unmatched 
110717 ** closing bracket - ')' - is encountered.
110718 **
110719 ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
110720 ** parsed form of the expression and *pnConsumed is set to the number of
110721 ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
110722 ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
110723 */
110724 static int fts3ExprParse(
110725   ParseContext *pParse,                   /* fts3 query parse context */
110726   const char *z, int n,                   /* Text of MATCH query */
110727   Fts3Expr **ppExpr,                      /* OUT: Parsed query structure */
110728   int *pnConsumed                         /* OUT: Number of bytes consumed */
110729 ){
110730   Fts3Expr *pRet = 0;
110731   Fts3Expr *pPrev = 0;
110732   Fts3Expr *pNotBranch = 0;               /* Only used in legacy parse mode */
110733   int nIn = n;
110734   const char *zIn = z;
110735   int rc = SQLITE_OK;
110736   int isRequirePhrase = 1;
110737
110738   while( rc==SQLITE_OK ){
110739     Fts3Expr *p = 0;
110740     int nByte = 0;
110741     rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
110742     if( rc==SQLITE_OK ){
110743       int isPhrase;
110744
110745       if( !sqlite3_fts3_enable_parentheses 
110746        && p->eType==FTSQUERY_PHRASE && p->pPhrase->isNot 
110747       ){
110748         /* Create an implicit NOT operator. */
110749         Fts3Expr *pNot = sqlite3_malloc(sizeof(Fts3Expr));
110750         if( !pNot ){
110751           sqlite3Fts3ExprFree(p);
110752           rc = SQLITE_NOMEM;
110753           goto exprparse_out;
110754         }
110755         memset(pNot, 0, sizeof(Fts3Expr));
110756         pNot->eType = FTSQUERY_NOT;
110757         pNot->pRight = p;
110758         if( pNotBranch ){
110759           pNot->pLeft = pNotBranch;
110760         }
110761         pNotBranch = pNot;
110762         p = pPrev;
110763       }else{
110764         int eType = p->eType;
110765         assert( eType!=FTSQUERY_PHRASE || !p->pPhrase->isNot );
110766         isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
110767
110768         /* The isRequirePhrase variable is set to true if a phrase or
110769         ** an expression contained in parenthesis is required. If a
110770         ** binary operator (AND, OR, NOT or NEAR) is encounted when
110771         ** isRequirePhrase is set, this is a syntax error.
110772         */
110773         if( !isPhrase && isRequirePhrase ){
110774           sqlite3Fts3ExprFree(p);
110775           rc = SQLITE_ERROR;
110776           goto exprparse_out;
110777         }
110778   
110779         if( isPhrase && !isRequirePhrase ){
110780           /* Insert an implicit AND operator. */
110781           Fts3Expr *pAnd;
110782           assert( pRet && pPrev );
110783           pAnd = sqlite3_malloc(sizeof(Fts3Expr));
110784           if( !pAnd ){
110785             sqlite3Fts3ExprFree(p);
110786             rc = SQLITE_NOMEM;
110787             goto exprparse_out;
110788           }
110789           memset(pAnd, 0, sizeof(Fts3Expr));
110790           pAnd->eType = FTSQUERY_AND;
110791           insertBinaryOperator(&pRet, pPrev, pAnd);
110792           pPrev = pAnd;
110793         }
110794
110795         /* This test catches attempts to make either operand of a NEAR
110796         ** operator something other than a phrase. For example, either of
110797         ** the following:
110798         **
110799         **    (bracketed expression) NEAR phrase
110800         **    phrase NEAR (bracketed expression)
110801         **
110802         ** Return an error in either case.
110803         */
110804         if( pPrev && (
110805             (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
110806          || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
110807         )){
110808           sqlite3Fts3ExprFree(p);
110809           rc = SQLITE_ERROR;
110810           goto exprparse_out;
110811         }
110812   
110813         if( isPhrase ){
110814           if( pRet ){
110815             assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
110816             pPrev->pRight = p;
110817             p->pParent = pPrev;
110818           }else{
110819             pRet = p;
110820           }
110821         }else{
110822           insertBinaryOperator(&pRet, pPrev, p);
110823         }
110824         isRequirePhrase = !isPhrase;
110825       }
110826       assert( nByte>0 );
110827     }
110828     assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
110829     nIn -= nByte;
110830     zIn += nByte;
110831     pPrev = p;
110832   }
110833
110834   if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
110835     rc = SQLITE_ERROR;
110836   }
110837
110838   if( rc==SQLITE_DONE ){
110839     rc = SQLITE_OK;
110840     if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
110841       if( !pRet ){
110842         rc = SQLITE_ERROR;
110843       }else{
110844         Fts3Expr *pIter = pNotBranch;
110845         while( pIter->pLeft ){
110846           pIter = pIter->pLeft;
110847         }
110848         pIter->pLeft = pRet;
110849         pRet = pNotBranch;
110850       }
110851     }
110852   }
110853   *pnConsumed = n - nIn;
110854
110855 exprparse_out:
110856   if( rc!=SQLITE_OK ){
110857     sqlite3Fts3ExprFree(pRet);
110858     sqlite3Fts3ExprFree(pNotBranch);
110859     pRet = 0;
110860   }
110861   *ppExpr = pRet;
110862   return rc;
110863 }
110864
110865 /*
110866 ** Parameters z and n contain a pointer to and length of a buffer containing
110867 ** an fts3 query expression, respectively. This function attempts to parse the
110868 ** query expression and create a tree of Fts3Expr structures representing the
110869 ** parsed expression. If successful, *ppExpr is set to point to the head
110870 ** of the parsed expression tree and SQLITE_OK is returned. If an error
110871 ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
110872 ** error) is returned and *ppExpr is set to 0.
110873 **
110874 ** If parameter n is a negative number, then z is assumed to point to a
110875 ** nul-terminated string and the length is determined using strlen().
110876 **
110877 ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
110878 ** use to normalize query tokens while parsing the expression. The azCol[]
110879 ** array, which is assumed to contain nCol entries, should contain the names
110880 ** of each column in the target fts3 table, in order from left to right. 
110881 ** Column names must be nul-terminated strings.
110882 **
110883 ** The iDefaultCol parameter should be passed the index of the table column
110884 ** that appears on the left-hand-side of the MATCH operator (the default
110885 ** column to match against for tokens for which a column name is not explicitly
110886 ** specified as part of the query string), or -1 if tokens may by default
110887 ** match any table column.
110888 */
110889 SQLITE_PRIVATE int sqlite3Fts3ExprParse(
110890   sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
110891   char **azCol,                       /* Array of column names for fts3 table */
110892   int nCol,                           /* Number of entries in azCol[] */
110893   int iDefaultCol,                    /* Default column to query */
110894   const char *z, int n,               /* Text of MATCH query */
110895   Fts3Expr **ppExpr                   /* OUT: Parsed query structure */
110896 ){
110897   int nParsed;
110898   int rc;
110899   ParseContext sParse;
110900   sParse.pTokenizer = pTokenizer;
110901   sParse.azCol = (const char **)azCol;
110902   sParse.nCol = nCol;
110903   sParse.iDefaultCol = iDefaultCol;
110904   sParse.nNest = 0;
110905   if( z==0 ){
110906     *ppExpr = 0;
110907     return SQLITE_OK;
110908   }
110909   if( n<0 ){
110910     n = (int)strlen(z);
110911   }
110912   rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
110913
110914   /* Check for mismatched parenthesis */
110915   if( rc==SQLITE_OK && sParse.nNest ){
110916     rc = SQLITE_ERROR;
110917     sqlite3Fts3ExprFree(*ppExpr);
110918     *ppExpr = 0;
110919   }
110920
110921   return rc;
110922 }
110923
110924 /*
110925 ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
110926 */
110927 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *p){
110928   if( p ){
110929     sqlite3Fts3ExprFree(p->pLeft);
110930     sqlite3Fts3ExprFree(p->pRight);
110931     sqlite3_free(p->aDoclist);
110932     sqlite3_free(p);
110933   }
110934 }
110935
110936 /****************************************************************************
110937 *****************************************************************************
110938 ** Everything after this point is just test code.
110939 */
110940
110941 #ifdef SQLITE_TEST
110942
110943
110944 /*
110945 ** Function to query the hash-table of tokenizers (see README.tokenizers).
110946 */
110947 static int queryTestTokenizer(
110948   sqlite3 *db, 
110949   const char *zName,  
110950   const sqlite3_tokenizer_module **pp
110951 ){
110952   int rc;
110953   sqlite3_stmt *pStmt;
110954   const char zSql[] = "SELECT fts3_tokenizer(?)";
110955
110956   *pp = 0;
110957   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
110958   if( rc!=SQLITE_OK ){
110959     return rc;
110960   }
110961
110962   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
110963   if( SQLITE_ROW==sqlite3_step(pStmt) ){
110964     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
110965       memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
110966     }
110967   }
110968
110969   return sqlite3_finalize(pStmt);
110970 }
110971
110972 /*
110973 ** This function is part of the test interface for the query parser. It
110974 ** writes a text representation of the query expression pExpr into the
110975 ** buffer pointed to by argument zBuf. It is assumed that zBuf is large 
110976 ** enough to store the required text representation.
110977 */
110978 static void exprToString(Fts3Expr *pExpr, char *zBuf){
110979   switch( pExpr->eType ){
110980     case FTSQUERY_PHRASE: {
110981       Fts3Phrase *pPhrase = pExpr->pPhrase;
110982       int i;
110983       zBuf += sprintf(zBuf, "PHRASE %d %d", pPhrase->iColumn, pPhrase->isNot);
110984       for(i=0; i<pPhrase->nToken; i++){
110985         zBuf += sprintf(zBuf," %.*s",pPhrase->aToken[i].n,pPhrase->aToken[i].z);
110986         zBuf += sprintf(zBuf,"%s", (pPhrase->aToken[i].isPrefix?"+":""));
110987       }
110988       return;
110989     }
110990
110991     case FTSQUERY_NEAR:
110992       zBuf += sprintf(zBuf, "NEAR/%d ", pExpr->nNear);
110993       break;
110994     case FTSQUERY_NOT:
110995       zBuf += sprintf(zBuf, "NOT ");
110996       break;
110997     case FTSQUERY_AND:
110998       zBuf += sprintf(zBuf, "AND ");
110999       break;
111000     case FTSQUERY_OR:
111001       zBuf += sprintf(zBuf, "OR ");
111002       break;
111003   }
111004
111005   zBuf += sprintf(zBuf, "{");
111006   exprToString(pExpr->pLeft, zBuf);
111007   zBuf += strlen(zBuf);
111008   zBuf += sprintf(zBuf, "} ");
111009
111010   zBuf += sprintf(zBuf, "{");
111011   exprToString(pExpr->pRight, zBuf);
111012   zBuf += strlen(zBuf);
111013   zBuf += sprintf(zBuf, "}");
111014 }
111015
111016 /*
111017 ** This is the implementation of a scalar SQL function used to test the 
111018 ** expression parser. It should be called as follows:
111019 **
111020 **   fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
111021 **
111022 ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
111023 ** to parse the query expression (see README.tokenizers). The second argument
111024 ** is the query expression to parse. Each subsequent argument is the name
111025 ** of a column of the fts3 table that the query expression may refer to.
111026 ** For example:
111027 **
111028 **   SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
111029 */
111030 static void fts3ExprTest(
111031   sqlite3_context *context,
111032   int argc,
111033   sqlite3_value **argv
111034 ){
111035   sqlite3_tokenizer_module const *pModule = 0;
111036   sqlite3_tokenizer *pTokenizer = 0;
111037   int rc;
111038   char **azCol = 0;
111039   const char *zExpr;
111040   int nExpr;
111041   int nCol;
111042   int ii;
111043   Fts3Expr *pExpr;
111044   sqlite3 *db = sqlite3_context_db_handle(context);
111045
111046   if( argc<3 ){
111047     sqlite3_result_error(context, 
111048         "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
111049     );
111050     return;
111051   }
111052
111053   rc = queryTestTokenizer(db,
111054                           (const char *)sqlite3_value_text(argv[0]), &pModule);
111055   if( rc==SQLITE_NOMEM ){
111056     sqlite3_result_error_nomem(context);
111057     goto exprtest_out;
111058   }else if( !pModule ){
111059     sqlite3_result_error(context, "No such tokenizer module", -1);
111060     goto exprtest_out;
111061   }
111062
111063   rc = pModule->xCreate(0, 0, &pTokenizer);
111064   assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
111065   if( rc==SQLITE_NOMEM ){
111066     sqlite3_result_error_nomem(context);
111067     goto exprtest_out;
111068   }
111069   pTokenizer->pModule = pModule;
111070
111071   zExpr = (const char *)sqlite3_value_text(argv[1]);
111072   nExpr = sqlite3_value_bytes(argv[1]);
111073   nCol = argc-2;
111074   azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
111075   if( !azCol ){
111076     sqlite3_result_error_nomem(context);
111077     goto exprtest_out;
111078   }
111079   for(ii=0; ii<nCol; ii++){
111080     azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
111081   }
111082
111083   rc = sqlite3Fts3ExprParse(
111084       pTokenizer, azCol, nCol, nCol, zExpr, nExpr, &pExpr
111085   );
111086   if( rc==SQLITE_NOMEM ){
111087     sqlite3_result_error_nomem(context);
111088     goto exprtest_out;
111089   }else if( rc==SQLITE_OK ){
111090     char zBuf[4096];
111091     exprToString(pExpr, zBuf);
111092     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
111093     sqlite3Fts3ExprFree(pExpr);
111094   }else{
111095     sqlite3_result_error(context, "Error parsing expression", -1);
111096   }
111097
111098 exprtest_out:
111099   if( pModule && pTokenizer ){
111100     rc = pModule->xDestroy(pTokenizer);
111101   }
111102   sqlite3_free(azCol);
111103 }
111104
111105 /*
111106 ** Register the query expression parser test function fts3_exprtest() 
111107 ** with database connection db. 
111108 */
111109 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
111110   return sqlite3_create_function(
111111       db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
111112   );
111113 }
111114
111115 #endif
111116 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
111117
111118 /************** End of fts3_expr.c *******************************************/
111119 /************** Begin file fts3_hash.c ***************************************/
111120 /*
111121 ** 2001 September 22
111122 **
111123 ** The author disclaims copyright to this source code.  In place of
111124 ** a legal notice, here is a blessing:
111125 **
111126 **    May you do good and not evil.
111127 **    May you find forgiveness for yourself and forgive others.
111128 **    May you share freely, never taking more than you give.
111129 **
111130 *************************************************************************
111131 ** This is the implementation of generic hash-tables used in SQLite.
111132 ** We've modified it slightly to serve as a standalone hash table
111133 ** implementation for the full-text indexing module.
111134 */
111135
111136 /*
111137 ** The code in this file is only compiled if:
111138 **
111139 **     * The FTS3 module is being built as an extension
111140 **       (in which case SQLITE_CORE is not defined), or
111141 **
111142 **     * The FTS3 module is being built into the core of
111143 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
111144 */
111145 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
111146
111147
111148
111149 /*
111150 ** Malloc and Free functions
111151 */
111152 static void *fts3HashMalloc(int n){
111153   void *p = sqlite3_malloc(n);
111154   if( p ){
111155     memset(p, 0, n);
111156   }
111157   return p;
111158 }
111159 static void fts3HashFree(void *p){
111160   sqlite3_free(p);
111161 }
111162
111163 /* Turn bulk memory into a hash table object by initializing the
111164 ** fields of the Hash structure.
111165 **
111166 ** "pNew" is a pointer to the hash table that is to be initialized.
111167 ** keyClass is one of the constants 
111168 ** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass 
111169 ** determines what kind of key the hash table will use.  "copyKey" is
111170 ** true if the hash table should make its own private copy of keys and
111171 ** false if it should just use the supplied pointer.
111172 */
111173 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
111174   assert( pNew!=0 );
111175   assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
111176   pNew->keyClass = keyClass;
111177   pNew->copyKey = copyKey;
111178   pNew->first = 0;
111179   pNew->count = 0;
111180   pNew->htsize = 0;
111181   pNew->ht = 0;
111182 }
111183
111184 /* Remove all entries from a hash table.  Reclaim all memory.
111185 ** Call this routine to delete a hash table or to reset a hash table
111186 ** to the empty state.
111187 */
111188 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
111189   Fts3HashElem *elem;         /* For looping over all elements of the table */
111190
111191   assert( pH!=0 );
111192   elem = pH->first;
111193   pH->first = 0;
111194   fts3HashFree(pH->ht);
111195   pH->ht = 0;
111196   pH->htsize = 0;
111197   while( elem ){
111198     Fts3HashElem *next_elem = elem->next;
111199     if( pH->copyKey && elem->pKey ){
111200       fts3HashFree(elem->pKey);
111201     }
111202     fts3HashFree(elem);
111203     elem = next_elem;
111204   }
111205   pH->count = 0;
111206 }
111207
111208 /*
111209 ** Hash and comparison functions when the mode is FTS3_HASH_STRING
111210 */
111211 static int fts3StrHash(const void *pKey, int nKey){
111212   const char *z = (const char *)pKey;
111213   int h = 0;
111214   if( nKey<=0 ) nKey = (int) strlen(z);
111215   while( nKey > 0  ){
111216     h = (h<<3) ^ h ^ *z++;
111217     nKey--;
111218   }
111219   return h & 0x7fffffff;
111220 }
111221 static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
111222   if( n1!=n2 ) return 1;
111223   return strncmp((const char*)pKey1,(const char*)pKey2,n1);
111224 }
111225
111226 /*
111227 ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
111228 */
111229 static int fts3BinHash(const void *pKey, int nKey){
111230   int h = 0;
111231   const char *z = (const char *)pKey;
111232   while( nKey-- > 0 ){
111233     h = (h<<3) ^ h ^ *(z++);
111234   }
111235   return h & 0x7fffffff;
111236 }
111237 static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
111238   if( n1!=n2 ) return 1;
111239   return memcmp(pKey1,pKey2,n1);
111240 }
111241
111242 /*
111243 ** Return a pointer to the appropriate hash function given the key class.
111244 **
111245 ** The C syntax in this function definition may be unfamilar to some 
111246 ** programmers, so we provide the following additional explanation:
111247 **
111248 ** The name of the function is "ftsHashFunction".  The function takes a
111249 ** single parameter "keyClass".  The return value of ftsHashFunction()
111250 ** is a pointer to another function.  Specifically, the return value
111251 ** of ftsHashFunction() is a pointer to a function that takes two parameters
111252 ** with types "const void*" and "int" and returns an "int".
111253 */
111254 static int (*ftsHashFunction(int keyClass))(const void*,int){
111255   if( keyClass==FTS3_HASH_STRING ){
111256     return &fts3StrHash;
111257   }else{
111258     assert( keyClass==FTS3_HASH_BINARY );
111259     return &fts3BinHash;
111260   }
111261 }
111262
111263 /*
111264 ** Return a pointer to the appropriate hash function given the key class.
111265 **
111266 ** For help in interpreted the obscure C code in the function definition,
111267 ** see the header comment on the previous function.
111268 */
111269 static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
111270   if( keyClass==FTS3_HASH_STRING ){
111271     return &fts3StrCompare;
111272   }else{
111273     assert( keyClass==FTS3_HASH_BINARY );
111274     return &fts3BinCompare;
111275   }
111276 }
111277
111278 /* Link an element into the hash table
111279 */
111280 static void fts3HashInsertElement(
111281   Fts3Hash *pH,            /* The complete hash table */
111282   struct _fts3ht *pEntry,  /* The entry into which pNew is inserted */
111283   Fts3HashElem *pNew       /* The element to be inserted */
111284 ){
111285   Fts3HashElem *pHead;     /* First element already in pEntry */
111286   pHead = pEntry->chain;
111287   if( pHead ){
111288     pNew->next = pHead;
111289     pNew->prev = pHead->prev;
111290     if( pHead->prev ){ pHead->prev->next = pNew; }
111291     else             { pH->first = pNew; }
111292     pHead->prev = pNew;
111293   }else{
111294     pNew->next = pH->first;
111295     if( pH->first ){ pH->first->prev = pNew; }
111296     pNew->prev = 0;
111297     pH->first = pNew;
111298   }
111299   pEntry->count++;
111300   pEntry->chain = pNew;
111301 }
111302
111303
111304 /* Resize the hash table so that it cantains "new_size" buckets.
111305 ** "new_size" must be a power of 2.  The hash table might fail 
111306 ** to resize if sqliteMalloc() fails.
111307 **
111308 ** Return non-zero if a memory allocation error occurs.
111309 */
111310 static int fts3Rehash(Fts3Hash *pH, int new_size){
111311   struct _fts3ht *new_ht;          /* The new hash table */
111312   Fts3HashElem *elem, *next_elem;  /* For looping over existing elements */
111313   int (*xHash)(const void*,int);   /* The hash function */
111314
111315   assert( (new_size & (new_size-1))==0 );
111316   new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
111317   if( new_ht==0 ) return 1;
111318   fts3HashFree(pH->ht);
111319   pH->ht = new_ht;
111320   pH->htsize = new_size;
111321   xHash = ftsHashFunction(pH->keyClass);
111322   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
111323     int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
111324     next_elem = elem->next;
111325     fts3HashInsertElement(pH, &new_ht[h], elem);
111326   }
111327   return 0;
111328 }
111329
111330 /* This function (for internal use only) locates an element in an
111331 ** hash table that matches the given key.  The hash for this key has
111332 ** already been computed and is passed as the 4th parameter.
111333 */
111334 static Fts3HashElem *fts3FindElementByHash(
111335   const Fts3Hash *pH, /* The pH to be searched */
111336   const void *pKey,   /* The key we are searching for */
111337   int nKey,
111338   int h               /* The hash for this key. */
111339 ){
111340   Fts3HashElem *elem;            /* Used to loop thru the element list */
111341   int count;                     /* Number of elements left to test */
111342   int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
111343
111344   if( pH->ht ){
111345     struct _fts3ht *pEntry = &pH->ht[h];
111346     elem = pEntry->chain;
111347     count = pEntry->count;
111348     xCompare = ftsCompareFunction(pH->keyClass);
111349     while( count-- && elem ){
111350       if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){ 
111351         return elem;
111352       }
111353       elem = elem->next;
111354     }
111355   }
111356   return 0;
111357 }
111358
111359 /* Remove a single entry from the hash table given a pointer to that
111360 ** element and a hash on the element's key.
111361 */
111362 static void fts3RemoveElementByHash(
111363   Fts3Hash *pH,         /* The pH containing "elem" */
111364   Fts3HashElem* elem,   /* The element to be removed from the pH */
111365   int h                 /* Hash value for the element */
111366 ){
111367   struct _fts3ht *pEntry;
111368   if( elem->prev ){
111369     elem->prev->next = elem->next; 
111370   }else{
111371     pH->first = elem->next;
111372   }
111373   if( elem->next ){
111374     elem->next->prev = elem->prev;
111375   }
111376   pEntry = &pH->ht[h];
111377   if( pEntry->chain==elem ){
111378     pEntry->chain = elem->next;
111379   }
111380   pEntry->count--;
111381   if( pEntry->count<=0 ){
111382     pEntry->chain = 0;
111383   }
111384   if( pH->copyKey && elem->pKey ){
111385     fts3HashFree(elem->pKey);
111386   }
111387   fts3HashFree( elem );
111388   pH->count--;
111389   if( pH->count<=0 ){
111390     assert( pH->first==0 );
111391     assert( pH->count==0 );
111392     fts3HashClear(pH);
111393   }
111394 }
111395
111396 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
111397   const Fts3Hash *pH, 
111398   const void *pKey, 
111399   int nKey
111400 ){
111401   int h;                          /* A hash on key */
111402   int (*xHash)(const void*,int);  /* The hash function */
111403
111404   if( pH==0 || pH->ht==0 ) return 0;
111405   xHash = ftsHashFunction(pH->keyClass);
111406   assert( xHash!=0 );
111407   h = (*xHash)(pKey,nKey);
111408   assert( (pH->htsize & (pH->htsize-1))==0 );
111409   return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
111410 }
111411
111412 /* 
111413 ** Attempt to locate an element of the hash table pH with a key
111414 ** that matches pKey,nKey.  Return the data for this element if it is
111415 ** found, or NULL if there is no match.
111416 */
111417 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
111418   Fts3HashElem *pElem;            /* The element that matches key (if any) */
111419
111420   pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
111421   return pElem ? pElem->data : 0;
111422 }
111423
111424 /* Insert an element into the hash table pH.  The key is pKey,nKey
111425 ** and the data is "data".
111426 **
111427 ** If no element exists with a matching key, then a new
111428 ** element is created.  A copy of the key is made if the copyKey
111429 ** flag is set.  NULL is returned.
111430 **
111431 ** If another element already exists with the same key, then the
111432 ** new data replaces the old data and the old data is returned.
111433 ** The key is not copied in this instance.  If a malloc fails, then
111434 ** the new data is returned and the hash table is unchanged.
111435 **
111436 ** If the "data" parameter to this function is NULL, then the
111437 ** element corresponding to "key" is removed from the hash table.
111438 */
111439 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
111440   Fts3Hash *pH,        /* The hash table to insert into */
111441   const void *pKey,    /* The key */
111442   int nKey,            /* Number of bytes in the key */
111443   void *data           /* The data */
111444 ){
111445   int hraw;                 /* Raw hash value of the key */
111446   int h;                    /* the hash of the key modulo hash table size */
111447   Fts3HashElem *elem;       /* Used to loop thru the element list */
111448   Fts3HashElem *new_elem;   /* New element added to the pH */
111449   int (*xHash)(const void*,int);  /* The hash function */
111450
111451   assert( pH!=0 );
111452   xHash = ftsHashFunction(pH->keyClass);
111453   assert( xHash!=0 );
111454   hraw = (*xHash)(pKey, nKey);
111455   assert( (pH->htsize & (pH->htsize-1))==0 );
111456   h = hraw & (pH->htsize-1);
111457   elem = fts3FindElementByHash(pH,pKey,nKey,h);
111458   if( elem ){
111459     void *old_data = elem->data;
111460     if( data==0 ){
111461       fts3RemoveElementByHash(pH,elem,h);
111462     }else{
111463       elem->data = data;
111464     }
111465     return old_data;
111466   }
111467   if( data==0 ) return 0;
111468   if( (pH->htsize==0 && fts3Rehash(pH,8))
111469    || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
111470   ){
111471     pH->count = 0;
111472     return data;
111473   }
111474   assert( pH->htsize>0 );
111475   new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
111476   if( new_elem==0 ) return data;
111477   if( pH->copyKey && pKey!=0 ){
111478     new_elem->pKey = fts3HashMalloc( nKey );
111479     if( new_elem->pKey==0 ){
111480       fts3HashFree(new_elem);
111481       return data;
111482     }
111483     memcpy((void*)new_elem->pKey, pKey, nKey);
111484   }else{
111485     new_elem->pKey = (void*)pKey;
111486   }
111487   new_elem->nKey = nKey;
111488   pH->count++;
111489   assert( pH->htsize>0 );
111490   assert( (pH->htsize & (pH->htsize-1))==0 );
111491   h = hraw & (pH->htsize-1);
111492   fts3HashInsertElement(pH, &pH->ht[h], new_elem);
111493   new_elem->data = data;
111494   return 0;
111495 }
111496
111497 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
111498
111499 /************** End of fts3_hash.c *******************************************/
111500 /************** Begin file fts3_porter.c *************************************/
111501 /*
111502 ** 2006 September 30
111503 **
111504 ** The author disclaims copyright to this source code.  In place of
111505 ** a legal notice, here is a blessing:
111506 **
111507 **    May you do good and not evil.
111508 **    May you find forgiveness for yourself and forgive others.
111509 **    May you share freely, never taking more than you give.
111510 **
111511 *************************************************************************
111512 ** Implementation of the full-text-search tokenizer that implements
111513 ** a Porter stemmer.
111514 */
111515
111516 /*
111517 ** The code in this file is only compiled if:
111518 **
111519 **     * The FTS3 module is being built as an extension
111520 **       (in which case SQLITE_CORE is not defined), or
111521 **
111522 **     * The FTS3 module is being built into the core of
111523 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
111524 */
111525 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
111526
111527
111528
111529
111530 /*
111531 ** Class derived from sqlite3_tokenizer
111532 */
111533 typedef struct porter_tokenizer {
111534   sqlite3_tokenizer base;      /* Base class */
111535 } porter_tokenizer;
111536
111537 /*
111538 ** Class derived from sqlit3_tokenizer_cursor
111539 */
111540 typedef struct porter_tokenizer_cursor {
111541   sqlite3_tokenizer_cursor base;
111542   const char *zInput;          /* input we are tokenizing */
111543   int nInput;                  /* size of the input */
111544   int iOffset;                 /* current position in zInput */
111545   int iToken;                  /* index of next token to be returned */
111546   char *zToken;                /* storage for current token */
111547   int nAllocated;              /* space allocated to zToken buffer */
111548 } porter_tokenizer_cursor;
111549
111550
111551 /*
111552 ** Create a new tokenizer instance.
111553 */
111554 static int porterCreate(
111555   int argc, const char * const *argv,
111556   sqlite3_tokenizer **ppTokenizer
111557 ){
111558   porter_tokenizer *t;
111559
111560   UNUSED_PARAMETER(argc);
111561   UNUSED_PARAMETER(argv);
111562
111563   t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
111564   if( t==NULL ) return SQLITE_NOMEM;
111565   memset(t, 0, sizeof(*t));
111566   *ppTokenizer = &t->base;
111567   return SQLITE_OK;
111568 }
111569
111570 /*
111571 ** Destroy a tokenizer
111572 */
111573 static int porterDestroy(sqlite3_tokenizer *pTokenizer){
111574   sqlite3_free(pTokenizer);
111575   return SQLITE_OK;
111576 }
111577
111578 /*
111579 ** Prepare to begin tokenizing a particular string.  The input
111580 ** string to be tokenized is zInput[0..nInput-1].  A cursor
111581 ** used to incrementally tokenize this string is returned in 
111582 ** *ppCursor.
111583 */
111584 static int porterOpen(
111585   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
111586   const char *zInput, int nInput,        /* String to be tokenized */
111587   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
111588 ){
111589   porter_tokenizer_cursor *c;
111590
111591   UNUSED_PARAMETER(pTokenizer);
111592
111593   c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
111594   if( c==NULL ) return SQLITE_NOMEM;
111595
111596   c->zInput = zInput;
111597   if( zInput==0 ){
111598     c->nInput = 0;
111599   }else if( nInput<0 ){
111600     c->nInput = (int)strlen(zInput);
111601   }else{
111602     c->nInput = nInput;
111603   }
111604   c->iOffset = 0;                 /* start tokenizing at the beginning */
111605   c->iToken = 0;
111606   c->zToken = NULL;               /* no space allocated, yet. */
111607   c->nAllocated = 0;
111608
111609   *ppCursor = &c->base;
111610   return SQLITE_OK;
111611 }
111612
111613 /*
111614 ** Close a tokenization cursor previously opened by a call to
111615 ** porterOpen() above.
111616 */
111617 static int porterClose(sqlite3_tokenizer_cursor *pCursor){
111618   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
111619   sqlite3_free(c->zToken);
111620   sqlite3_free(c);
111621   return SQLITE_OK;
111622 }
111623 /*
111624 ** Vowel or consonant
111625 */
111626 static const char cType[] = {
111627    0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
111628    1, 1, 1, 2, 1
111629 };
111630
111631 /*
111632 ** isConsonant() and isVowel() determine if their first character in
111633 ** the string they point to is a consonant or a vowel, according
111634 ** to Porter ruls.  
111635 **
111636 ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
111637 ** 'Y' is a consonant unless it follows another consonant,
111638 ** in which case it is a vowel.
111639 **
111640 ** In these routine, the letters are in reverse order.  So the 'y' rule
111641 ** is that 'y' is a consonant unless it is followed by another
111642 ** consonent.
111643 */
111644 static int isVowel(const char*);
111645 static int isConsonant(const char *z){
111646   int j;
111647   char x = *z;
111648   if( x==0 ) return 0;
111649   assert( x>='a' && x<='z' );
111650   j = cType[x-'a'];
111651   if( j<2 ) return j;
111652   return z[1]==0 || isVowel(z + 1);
111653 }
111654 static int isVowel(const char *z){
111655   int j;
111656   char x = *z;
111657   if( x==0 ) return 0;
111658   assert( x>='a' && x<='z' );
111659   j = cType[x-'a'];
111660   if( j<2 ) return 1-j;
111661   return isConsonant(z + 1);
111662 }
111663
111664 /*
111665 ** Let any sequence of one or more vowels be represented by V and let
111666 ** C be sequence of one or more consonants.  Then every word can be
111667 ** represented as:
111668 **
111669 **           [C] (VC){m} [V]
111670 **
111671 ** In prose:  A word is an optional consonant followed by zero or
111672 ** vowel-consonant pairs followed by an optional vowel.  "m" is the
111673 ** number of vowel consonant pairs.  This routine computes the value
111674 ** of m for the first i bytes of a word.
111675 **
111676 ** Return true if the m-value for z is 1 or more.  In other words,
111677 ** return true if z contains at least one vowel that is followed
111678 ** by a consonant.
111679 **
111680 ** In this routine z[] is in reverse order.  So we are really looking
111681 ** for an instance of of a consonant followed by a vowel.
111682 */
111683 static int m_gt_0(const char *z){
111684   while( isVowel(z) ){ z++; }
111685   if( *z==0 ) return 0;
111686   while( isConsonant(z) ){ z++; }
111687   return *z!=0;
111688 }
111689
111690 /* Like mgt0 above except we are looking for a value of m which is
111691 ** exactly 1
111692 */
111693 static int m_eq_1(const char *z){
111694   while( isVowel(z) ){ z++; }
111695   if( *z==0 ) return 0;
111696   while( isConsonant(z) ){ z++; }
111697   if( *z==0 ) return 0;
111698   while( isVowel(z) ){ z++; }
111699   if( *z==0 ) return 1;
111700   while( isConsonant(z) ){ z++; }
111701   return *z==0;
111702 }
111703
111704 /* Like mgt0 above except we are looking for a value of m>1 instead
111705 ** or m>0
111706 */
111707 static int m_gt_1(const char *z){
111708   while( isVowel(z) ){ z++; }
111709   if( *z==0 ) return 0;
111710   while( isConsonant(z) ){ z++; }
111711   if( *z==0 ) return 0;
111712   while( isVowel(z) ){ z++; }
111713   if( *z==0 ) return 0;
111714   while( isConsonant(z) ){ z++; }
111715   return *z!=0;
111716 }
111717
111718 /*
111719 ** Return TRUE if there is a vowel anywhere within z[0..n-1]
111720 */
111721 static int hasVowel(const char *z){
111722   while( isConsonant(z) ){ z++; }
111723   return *z!=0;
111724 }
111725
111726 /*
111727 ** Return TRUE if the word ends in a double consonant.
111728 **
111729 ** The text is reversed here. So we are really looking at
111730 ** the first two characters of z[].
111731 */
111732 static int doubleConsonant(const char *z){
111733   return isConsonant(z) && z[0]==z[1];
111734 }
111735
111736 /*
111737 ** Return TRUE if the word ends with three letters which
111738 ** are consonant-vowel-consonent and where the final consonant
111739 ** is not 'w', 'x', or 'y'.
111740 **
111741 ** The word is reversed here.  So we are really checking the
111742 ** first three letters and the first one cannot be in [wxy].
111743 */
111744 static int star_oh(const char *z){
111745   return
111746     isConsonant(z) &&
111747     z[0]!='w' && z[0]!='x' && z[0]!='y' &&
111748     isVowel(z+1) &&
111749     isConsonant(z+2);
111750 }
111751
111752 /*
111753 ** If the word ends with zFrom and xCond() is true for the stem
111754 ** of the word that preceeds the zFrom ending, then change the 
111755 ** ending to zTo.
111756 **
111757 ** The input word *pz and zFrom are both in reverse order.  zTo
111758 ** is in normal order. 
111759 **
111760 ** Return TRUE if zFrom matches.  Return FALSE if zFrom does not
111761 ** match.  Not that TRUE is returned even if xCond() fails and
111762 ** no substitution occurs.
111763 */
111764 static int stem(
111765   char **pz,             /* The word being stemmed (Reversed) */
111766   const char *zFrom,     /* If the ending matches this... (Reversed) */
111767   const char *zTo,       /* ... change the ending to this (not reversed) */
111768   int (*xCond)(const char*)   /* Condition that must be true */
111769 ){
111770   char *z = *pz;
111771   while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
111772   if( *zFrom!=0 ) return 0;
111773   if( xCond && !xCond(z) ) return 1;
111774   while( *zTo ){
111775     *(--z) = *(zTo++);
111776   }
111777   *pz = z;
111778   return 1;
111779 }
111780
111781 /*
111782 ** This is the fallback stemmer used when the porter stemmer is
111783 ** inappropriate.  The input word is copied into the output with
111784 ** US-ASCII case folding.  If the input word is too long (more
111785 ** than 20 bytes if it contains no digits or more than 6 bytes if
111786 ** it contains digits) then word is truncated to 20 or 6 bytes
111787 ** by taking 10 or 3 bytes from the beginning and end.
111788 */
111789 static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
111790   int i, mx, j;
111791   int hasDigit = 0;
111792   for(i=0; i<nIn; i++){
111793     char c = zIn[i];
111794     if( c>='A' && c<='Z' ){
111795       zOut[i] = c - 'A' + 'a';
111796     }else{
111797       if( c>='0' && c<='9' ) hasDigit = 1;
111798       zOut[i] = c;
111799     }
111800   }
111801   mx = hasDigit ? 3 : 10;
111802   if( nIn>mx*2 ){
111803     for(j=mx, i=nIn-mx; i<nIn; i++, j++){
111804       zOut[j] = zOut[i];
111805     }
111806     i = j;
111807   }
111808   zOut[i] = 0;
111809   *pnOut = i;
111810 }
111811
111812
111813 /*
111814 ** Stem the input word zIn[0..nIn-1].  Store the output in zOut.
111815 ** zOut is at least big enough to hold nIn bytes.  Write the actual
111816 ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
111817 **
111818 ** Any upper-case characters in the US-ASCII character set ([A-Z])
111819 ** are converted to lower case.  Upper-case UTF characters are
111820 ** unchanged.
111821 **
111822 ** Words that are longer than about 20 bytes are stemmed by retaining
111823 ** a few bytes from the beginning and the end of the word.  If the
111824 ** word contains digits, 3 bytes are taken from the beginning and
111825 ** 3 bytes from the end.  For long words without digits, 10 bytes
111826 ** are taken from each end.  US-ASCII case folding still applies.
111827 ** 
111828 ** If the input word contains not digits but does characters not 
111829 ** in [a-zA-Z] then no stemming is attempted and this routine just 
111830 ** copies the input into the input into the output with US-ASCII
111831 ** case folding.
111832 **
111833 ** Stemming never increases the length of the word.  So there is
111834 ** no chance of overflowing the zOut buffer.
111835 */
111836 static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
111837   int i, j;
111838   char zReverse[28];
111839   char *z, *z2;
111840   if( nIn<3 || nIn>=sizeof(zReverse)-7 ){
111841     /* The word is too big or too small for the porter stemmer.
111842     ** Fallback to the copy stemmer */
111843     copy_stemmer(zIn, nIn, zOut, pnOut);
111844     return;
111845   }
111846   for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
111847     char c = zIn[i];
111848     if( c>='A' && c<='Z' ){
111849       zReverse[j] = c + 'a' - 'A';
111850     }else if( c>='a' && c<='z' ){
111851       zReverse[j] = c;
111852     }else{
111853       /* The use of a character not in [a-zA-Z] means that we fallback
111854       ** to the copy stemmer */
111855       copy_stemmer(zIn, nIn, zOut, pnOut);
111856       return;
111857     }
111858   }
111859   memset(&zReverse[sizeof(zReverse)-5], 0, 5);
111860   z = &zReverse[j+1];
111861
111862
111863   /* Step 1a */
111864   if( z[0]=='s' ){
111865     if(
111866      !stem(&z, "sess", "ss", 0) &&
111867      !stem(&z, "sei", "i", 0)  &&
111868      !stem(&z, "ss", "ss", 0)
111869     ){
111870       z++;
111871     }
111872   }
111873
111874   /* Step 1b */  
111875   z2 = z;
111876   if( stem(&z, "dee", "ee", m_gt_0) ){
111877     /* Do nothing.  The work was all in the test */
111878   }else if( 
111879      (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
111880       && z!=z2
111881   ){
111882      if( stem(&z, "ta", "ate", 0) ||
111883          stem(&z, "lb", "ble", 0) ||
111884          stem(&z, "zi", "ize", 0) ){
111885        /* Do nothing.  The work was all in the test */
111886      }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
111887        z++;
111888      }else if( m_eq_1(z) && star_oh(z) ){
111889        *(--z) = 'e';
111890      }
111891   }
111892
111893   /* Step 1c */
111894   if( z[0]=='y' && hasVowel(z+1) ){
111895     z[0] = 'i';
111896   }
111897
111898   /* Step 2 */
111899   switch( z[1] ){
111900    case 'a':
111901      stem(&z, "lanoita", "ate", m_gt_0) ||
111902      stem(&z, "lanoit", "tion", m_gt_0);
111903      break;
111904    case 'c':
111905      stem(&z, "icne", "ence", m_gt_0) ||
111906      stem(&z, "icna", "ance", m_gt_0);
111907      break;
111908    case 'e':
111909      stem(&z, "rezi", "ize", m_gt_0);
111910      break;
111911    case 'g':
111912      stem(&z, "igol", "log", m_gt_0);
111913      break;
111914    case 'l':
111915      stem(&z, "ilb", "ble", m_gt_0) ||
111916      stem(&z, "illa", "al", m_gt_0) ||
111917      stem(&z, "iltne", "ent", m_gt_0) ||
111918      stem(&z, "ile", "e", m_gt_0) ||
111919      stem(&z, "ilsuo", "ous", m_gt_0);
111920      break;
111921    case 'o':
111922      stem(&z, "noitazi", "ize", m_gt_0) ||
111923      stem(&z, "noita", "ate", m_gt_0) ||
111924      stem(&z, "rota", "ate", m_gt_0);
111925      break;
111926    case 's':
111927      stem(&z, "msila", "al", m_gt_0) ||
111928      stem(&z, "ssenevi", "ive", m_gt_0) ||
111929      stem(&z, "ssenluf", "ful", m_gt_0) ||
111930      stem(&z, "ssensuo", "ous", m_gt_0);
111931      break;
111932    case 't':
111933      stem(&z, "itila", "al", m_gt_0) ||
111934      stem(&z, "itivi", "ive", m_gt_0) ||
111935      stem(&z, "itilib", "ble", m_gt_0);
111936      break;
111937   }
111938
111939   /* Step 3 */
111940   switch( z[0] ){
111941    case 'e':
111942      stem(&z, "etaci", "ic", m_gt_0) ||
111943      stem(&z, "evita", "", m_gt_0)   ||
111944      stem(&z, "ezila", "al", m_gt_0);
111945      break;
111946    case 'i':
111947      stem(&z, "itici", "ic", m_gt_0);
111948      break;
111949    case 'l':
111950      stem(&z, "laci", "ic", m_gt_0) ||
111951      stem(&z, "luf", "", m_gt_0);
111952      break;
111953    case 's':
111954      stem(&z, "ssen", "", m_gt_0);
111955      break;
111956   }
111957
111958   /* Step 4 */
111959   switch( z[1] ){
111960    case 'a':
111961      if( z[0]=='l' && m_gt_1(z+2) ){
111962        z += 2;
111963      }
111964      break;
111965    case 'c':
111966      if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){
111967        z += 4;
111968      }
111969      break;
111970    case 'e':
111971      if( z[0]=='r' && m_gt_1(z+2) ){
111972        z += 2;
111973      }
111974      break;
111975    case 'i':
111976      if( z[0]=='c' && m_gt_1(z+2) ){
111977        z += 2;
111978      }
111979      break;
111980    case 'l':
111981      if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
111982        z += 4;
111983      }
111984      break;
111985    case 'n':
111986      if( z[0]=='t' ){
111987        if( z[2]=='a' ){
111988          if( m_gt_1(z+3) ){
111989            z += 3;
111990          }
111991        }else if( z[2]=='e' ){
111992          stem(&z, "tneme", "", m_gt_1) ||
111993          stem(&z, "tnem", "", m_gt_1) ||
111994          stem(&z, "tne", "", m_gt_1);
111995        }
111996      }
111997      break;
111998    case 'o':
111999      if( z[0]=='u' ){
112000        if( m_gt_1(z+2) ){
112001          z += 2;
112002        }
112003      }else if( z[3]=='s' || z[3]=='t' ){
112004        stem(&z, "noi", "", m_gt_1);
112005      }
112006      break;
112007    case 's':
112008      if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
112009        z += 3;
112010      }
112011      break;
112012    case 't':
112013      stem(&z, "eta", "", m_gt_1) ||
112014      stem(&z, "iti", "", m_gt_1);
112015      break;
112016    case 'u':
112017      if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
112018        z += 3;
112019      }
112020      break;
112021    case 'v':
112022    case 'z':
112023      if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
112024        z += 3;
112025      }
112026      break;
112027   }
112028
112029   /* Step 5a */
112030   if( z[0]=='e' ){
112031     if( m_gt_1(z+1) ){
112032       z++;
112033     }else if( m_eq_1(z+1) && !star_oh(z+1) ){
112034       z++;
112035     }
112036   }
112037
112038   /* Step 5b */
112039   if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
112040     z++;
112041   }
112042
112043   /* z[] is now the stemmed word in reverse order.  Flip it back
112044   ** around into forward order and return.
112045   */
112046   *pnOut = i = (int)strlen(z);
112047   zOut[i] = 0;
112048   while( *z ){
112049     zOut[--i] = *(z++);
112050   }
112051 }
112052
112053 /*
112054 ** Characters that can be part of a token.  We assume any character
112055 ** whose value is greater than 0x80 (any UTF character) can be
112056 ** part of a token.  In other words, delimiters all must have
112057 ** values of 0x7f or lower.
112058 */
112059 static const char porterIdChar[] = {
112060 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
112061     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
112062     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
112063     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
112064     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
112065     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
112066 };
112067 #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
112068
112069 /*
112070 ** Extract the next token from a tokenization cursor.  The cursor must
112071 ** have been opened by a prior call to porterOpen().
112072 */
112073 static int porterNext(
112074   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */
112075   const char **pzToken,               /* OUT: *pzToken is the token text */
112076   int *pnBytes,                       /* OUT: Number of bytes in token */
112077   int *piStartOffset,                 /* OUT: Starting offset of token */
112078   int *piEndOffset,                   /* OUT: Ending offset of token */
112079   int *piPosition                     /* OUT: Position integer of token */
112080 ){
112081   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
112082   const char *z = c->zInput;
112083
112084   while( c->iOffset<c->nInput ){
112085     int iStartOffset, ch;
112086
112087     /* Scan past delimiter characters */
112088     while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
112089       c->iOffset++;
112090     }
112091
112092     /* Count non-delimiter characters. */
112093     iStartOffset = c->iOffset;
112094     while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
112095       c->iOffset++;
112096     }
112097
112098     if( c->iOffset>iStartOffset ){
112099       int n = c->iOffset-iStartOffset;
112100       if( n>c->nAllocated ){
112101         char *pNew;
112102         c->nAllocated = n+20;
112103         pNew = sqlite3_realloc(c->zToken, c->nAllocated);
112104         if( !pNew ) return SQLITE_NOMEM;
112105         c->zToken = pNew;
112106       }
112107       porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
112108       *pzToken = c->zToken;
112109       *piStartOffset = iStartOffset;
112110       *piEndOffset = c->iOffset;
112111       *piPosition = c->iToken++;
112112       return SQLITE_OK;
112113     }
112114   }
112115   return SQLITE_DONE;
112116 }
112117
112118 /*
112119 ** The set of routines that implement the porter-stemmer tokenizer
112120 */
112121 static const sqlite3_tokenizer_module porterTokenizerModule = {
112122   0,
112123   porterCreate,
112124   porterDestroy,
112125   porterOpen,
112126   porterClose,
112127   porterNext,
112128 };
112129
112130 /*
112131 ** Allocate a new porter tokenizer.  Return a pointer to the new
112132 ** tokenizer in *ppModule
112133 */
112134 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
112135   sqlite3_tokenizer_module const**ppModule
112136 ){
112137   *ppModule = &porterTokenizerModule;
112138 }
112139
112140 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
112141
112142 /************** End of fts3_porter.c *****************************************/
112143 /************** Begin file fts3_tokenizer.c **********************************/
112144 /*
112145 ** 2007 June 22
112146 **
112147 ** The author disclaims copyright to this source code.  In place of
112148 ** a legal notice, here is a blessing:
112149 **
112150 **    May you do good and not evil.
112151 **    May you find forgiveness for yourself and forgive others.
112152 **    May you share freely, never taking more than you give.
112153 **
112154 ******************************************************************************
112155 **
112156 ** This is part of an SQLite module implementing full-text search.
112157 ** This particular file implements the generic tokenizer interface.
112158 */
112159
112160 /*
112161 ** The code in this file is only compiled if:
112162 **
112163 **     * The FTS3 module is being built as an extension
112164 **       (in which case SQLITE_CORE is not defined), or
112165 **
112166 **     * The FTS3 module is being built into the core of
112167 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
112168 */
112169 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
112170
112171 #ifndef SQLITE_CORE
112172   SQLITE_EXTENSION_INIT1
112173 #endif
112174
112175
112176 /*
112177 ** Implementation of the SQL scalar function for accessing the underlying 
112178 ** hash table. This function may be called as follows:
112179 **
112180 **   SELECT <function-name>(<key-name>);
112181 **   SELECT <function-name>(<key-name>, <pointer>);
112182 **
112183 ** where <function-name> is the name passed as the second argument
112184 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
112185 **
112186 ** If the <pointer> argument is specified, it must be a blob value
112187 ** containing a pointer to be stored as the hash data corresponding
112188 ** to the string <key-name>. If <pointer> is not specified, then
112189 ** the string <key-name> must already exist in the has table. Otherwise,
112190 ** an error is returned.
112191 **
112192 ** Whether or not the <pointer> argument is specified, the value returned
112193 ** is a blob containing the pointer stored as the hash data corresponding
112194 ** to string <key-name> (after the hash-table is updated, if applicable).
112195 */
112196 static void scalarFunc(
112197   sqlite3_context *context,
112198   int argc,
112199   sqlite3_value **argv
112200 ){
112201   Fts3Hash *pHash;
112202   void *pPtr = 0;
112203   const unsigned char *zName;
112204   int nName;
112205
112206   assert( argc==1 || argc==2 );
112207
112208   pHash = (Fts3Hash *)sqlite3_user_data(context);
112209
112210   zName = sqlite3_value_text(argv[0]);
112211   nName = sqlite3_value_bytes(argv[0])+1;
112212
112213   if( argc==2 ){
112214     void *pOld;
112215     int n = sqlite3_value_bytes(argv[1]);
112216     if( n!=sizeof(pPtr) ){
112217       sqlite3_result_error(context, "argument type mismatch", -1);
112218       return;
112219     }
112220     pPtr = *(void **)sqlite3_value_blob(argv[1]);
112221     pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
112222     if( pOld==pPtr ){
112223       sqlite3_result_error(context, "out of memory", -1);
112224       return;
112225     }
112226   }else{
112227     pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
112228     if( !pPtr ){
112229       char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
112230       sqlite3_result_error(context, zErr, -1);
112231       sqlite3_free(zErr);
112232       return;
112233     }
112234   }
112235
112236   sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
112237 }
112238
112239 static int fts3IsIdChar(char c){
112240   static const char isFtsIdChar[] = {
112241       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 0x */
112242       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 1x */
112243       0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
112244       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
112245       0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
112246       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
112247       0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
112248       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
112249   };
112250   return (c&0x80 || isFtsIdChar[(int)(c)]);
112251 }
112252
112253 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
112254   const char *z1;
112255   const char *z2 = 0;
112256
112257   /* Find the start of the next token. */
112258   z1 = zStr;
112259   while( z2==0 ){
112260     char c = *z1;
112261     switch( c ){
112262       case '\0': return 0;        /* No more tokens here */
112263       case '\'':
112264       case '"':
112265       case '`': {
112266         z2 = z1;
112267         while( *++z2 && (*z2!=c || *++z2==c) );
112268         break;
112269       }
112270       case '[':
112271         z2 = &z1[1];
112272         while( *z2 && z2[0]!=']' ) z2++;
112273         if( *z2 ) z2++;
112274         break;
112275
112276       default:
112277         if( fts3IsIdChar(*z1) ){
112278           z2 = &z1[1];
112279           while( fts3IsIdChar(*z2) ) z2++;
112280         }else{
112281           z1++;
112282         }
112283     }
112284   }
112285
112286   *pn = (int)(z2-z1);
112287   return z1;
112288 }
112289
112290 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
112291   Fts3Hash *pHash,                /* Tokenizer hash table */
112292   const char *zArg,               /* Possible tokenizer specification */
112293   sqlite3_tokenizer **ppTok,      /* OUT: Tokenizer (if applicable) */
112294   const char **pzTokenizer,       /* OUT: Set to zArg if is tokenizer */
112295   char **pzErr                    /* OUT: Set to malloced error message */
112296 ){
112297   int rc;
112298   char *z = (char *)zArg;
112299   int n;
112300   char *zCopy;
112301   char *zEnd;                     /* Pointer to nul-term of zCopy */
112302   sqlite3_tokenizer_module *m;
112303
112304   if( !z ){
112305     zCopy = sqlite3_mprintf("simple");
112306   }else{
112307     if( sqlite3_strnicmp(z, "tokenize", 8) || fts3IsIdChar(z[8])){
112308       return SQLITE_OK;
112309     }
112310     zCopy = sqlite3_mprintf("%s", &z[8]);
112311     *pzTokenizer = zArg;
112312   }
112313   if( !zCopy ){
112314     return SQLITE_NOMEM;
112315   }
112316
112317   zEnd = &zCopy[strlen(zCopy)];
112318
112319   z = (char *)sqlite3Fts3NextToken(zCopy, &n);
112320   z[n] = '\0';
112321   sqlite3Fts3Dequote(z);
112322
112323   m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, z, (int)strlen(z)+1);
112324   if( !m ){
112325     *pzErr = sqlite3_mprintf("unknown tokenizer: %s", z);
112326     rc = SQLITE_ERROR;
112327   }else{
112328     char const **aArg = 0;
112329     int iArg = 0;
112330     z = &z[n+1];
112331     while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
112332       int nNew = sizeof(char *)*(iArg+1);
112333       char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
112334       if( !aNew ){
112335         sqlite3_free(zCopy);
112336         sqlite3_free((void *)aArg);
112337         return SQLITE_NOMEM;
112338       }
112339       aArg = aNew;
112340       aArg[iArg++] = z;
112341       z[n] = '\0';
112342       sqlite3Fts3Dequote(z);
112343       z = &z[n+1];
112344     }
112345     rc = m->xCreate(iArg, aArg, ppTok);
112346     assert( rc!=SQLITE_OK || *ppTok );
112347     if( rc!=SQLITE_OK ){
112348       *pzErr = sqlite3_mprintf("unknown tokenizer");
112349     }else{
112350       (*ppTok)->pModule = m; 
112351     }
112352     sqlite3_free((void *)aArg);
112353   }
112354
112355   sqlite3_free(zCopy);
112356   return rc;
112357 }
112358
112359
112360 #ifdef SQLITE_TEST
112361
112362
112363 /*
112364 ** Implementation of a special SQL scalar function for testing tokenizers 
112365 ** designed to be used in concert with the Tcl testing framework. This
112366 ** function must be called with two arguments:
112367 **
112368 **   SELECT <function-name>(<key-name>, <input-string>);
112369 **   SELECT <function-name>(<key-name>, <pointer>);
112370 **
112371 ** where <function-name> is the name passed as the second argument
112372 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
112373 ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
112374 **
112375 ** The return value is a string that may be interpreted as a Tcl
112376 ** list. For each token in the <input-string>, three elements are
112377 ** added to the returned list. The first is the token position, the 
112378 ** second is the token text (folded, stemmed, etc.) and the third is the
112379 ** substring of <input-string> associated with the token. For example, 
112380 ** using the built-in "simple" tokenizer:
112381 **
112382 **   SELECT fts_tokenizer_test('simple', 'I don't see how');
112383 **
112384 ** will return the string:
112385 **
112386 **   "{0 i I 1 dont don't 2 see see 3 how how}"
112387 **   
112388 */
112389 static void testFunc(
112390   sqlite3_context *context,
112391   int argc,
112392   sqlite3_value **argv
112393 ){
112394   Fts3Hash *pHash;
112395   sqlite3_tokenizer_module *p;
112396   sqlite3_tokenizer *pTokenizer = 0;
112397   sqlite3_tokenizer_cursor *pCsr = 0;
112398
112399   const char *zErr = 0;
112400
112401   const char *zName;
112402   int nName;
112403   const char *zInput;
112404   int nInput;
112405
112406   const char *zArg = 0;
112407
112408   const char *zToken;
112409   int nToken;
112410   int iStart;
112411   int iEnd;
112412   int iPos;
112413
112414   Tcl_Obj *pRet;
112415
112416   assert( argc==2 || argc==3 );
112417
112418   nName = sqlite3_value_bytes(argv[0]);
112419   zName = (const char *)sqlite3_value_text(argv[0]);
112420   nInput = sqlite3_value_bytes(argv[argc-1]);
112421   zInput = (const char *)sqlite3_value_text(argv[argc-1]);
112422
112423   if( argc==3 ){
112424     zArg = (const char *)sqlite3_value_text(argv[1]);
112425   }
112426
112427   pHash = (Fts3Hash *)sqlite3_user_data(context);
112428   p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
112429
112430   if( !p ){
112431     char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
112432     sqlite3_result_error(context, zErr, -1);
112433     sqlite3_free(zErr);
112434     return;
112435   }
112436
112437   pRet = Tcl_NewObj();
112438   Tcl_IncrRefCount(pRet);
112439
112440   if( SQLITE_OK!=p->xCreate(zArg ? 1 : 0, &zArg, &pTokenizer) ){
112441     zErr = "error in xCreate()";
112442     goto finish;
112443   }
112444   pTokenizer->pModule = p;
112445   if( SQLITE_OK!=p->xOpen(pTokenizer, zInput, nInput, &pCsr) ){
112446     zErr = "error in xOpen()";
112447     goto finish;
112448   }
112449   pCsr->pTokenizer = pTokenizer;
112450
112451   while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
112452     Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
112453     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
112454     zToken = &zInput[iStart];
112455     nToken = iEnd-iStart;
112456     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
112457   }
112458
112459   if( SQLITE_OK!=p->xClose(pCsr) ){
112460     zErr = "error in xClose()";
112461     goto finish;
112462   }
112463   if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
112464     zErr = "error in xDestroy()";
112465     goto finish;
112466   }
112467
112468 finish:
112469   if( zErr ){
112470     sqlite3_result_error(context, zErr, -1);
112471   }else{
112472     sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
112473   }
112474   Tcl_DecrRefCount(pRet);
112475 }
112476
112477 static
112478 int registerTokenizer(
112479   sqlite3 *db, 
112480   char *zName, 
112481   const sqlite3_tokenizer_module *p
112482 ){
112483   int rc;
112484   sqlite3_stmt *pStmt;
112485   const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
112486
112487   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
112488   if( rc!=SQLITE_OK ){
112489     return rc;
112490   }
112491
112492   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
112493   sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
112494   sqlite3_step(pStmt);
112495
112496   return sqlite3_finalize(pStmt);
112497 }
112498
112499 static
112500 int queryTokenizer(
112501   sqlite3 *db, 
112502   char *zName,  
112503   const sqlite3_tokenizer_module **pp
112504 ){
112505   int rc;
112506   sqlite3_stmt *pStmt;
112507   const char zSql[] = "SELECT fts3_tokenizer(?)";
112508
112509   *pp = 0;
112510   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
112511   if( rc!=SQLITE_OK ){
112512     return rc;
112513   }
112514
112515   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
112516   if( SQLITE_ROW==sqlite3_step(pStmt) ){
112517     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
112518       memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
112519     }
112520   }
112521
112522   return sqlite3_finalize(pStmt);
112523 }
112524
112525 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
112526
112527 /*
112528 ** Implementation of the scalar function fts3_tokenizer_internal_test().
112529 ** This function is used for testing only, it is not included in the
112530 ** build unless SQLITE_TEST is defined.
112531 **
112532 ** The purpose of this is to test that the fts3_tokenizer() function
112533 ** can be used as designed by the C-code in the queryTokenizer and
112534 ** registerTokenizer() functions above. These two functions are repeated
112535 ** in the README.tokenizer file as an example, so it is important to
112536 ** test them.
112537 **
112538 ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
112539 ** function with no arguments. An assert() will fail if a problem is
112540 ** detected. i.e.:
112541 **
112542 **     SELECT fts3_tokenizer_internal_test();
112543 **
112544 */
112545 static void intTestFunc(
112546   sqlite3_context *context,
112547   int argc,
112548   sqlite3_value **argv
112549 ){
112550   int rc;
112551   const sqlite3_tokenizer_module *p1;
112552   const sqlite3_tokenizer_module *p2;
112553   sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
112554
112555   UNUSED_PARAMETER(argc);
112556   UNUSED_PARAMETER(argv);
112557
112558   /* Test the query function */
112559   sqlite3Fts3SimpleTokenizerModule(&p1);
112560   rc = queryTokenizer(db, "simple", &p2);
112561   assert( rc==SQLITE_OK );
112562   assert( p1==p2 );
112563   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
112564   assert( rc==SQLITE_ERROR );
112565   assert( p2==0 );
112566   assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
112567
112568   /* Test the storage function */
112569   rc = registerTokenizer(db, "nosuchtokenizer", p1);
112570   assert( rc==SQLITE_OK );
112571   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
112572   assert( rc==SQLITE_OK );
112573   assert( p2==p1 );
112574
112575   sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
112576 }
112577
112578 #endif
112579
112580 /*
112581 ** Set up SQL objects in database db used to access the contents of
112582 ** the hash table pointed to by argument pHash. The hash table must
112583 ** been initialised to use string keys, and to take a private copy 
112584 ** of the key when a value is inserted. i.e. by a call similar to:
112585 **
112586 **    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
112587 **
112588 ** This function adds a scalar function (see header comment above
112589 ** scalarFunc() in this file for details) and, if ENABLE_TABLE is
112590 ** defined at compilation time, a temporary virtual table (see header 
112591 ** comment above struct HashTableVtab) to the database schema. Both 
112592 ** provide read/write access to the contents of *pHash.
112593 **
112594 ** The third argument to this function, zName, is used as the name
112595 ** of both the scalar and, if created, the virtual table.
112596 */
112597 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
112598   sqlite3 *db, 
112599   Fts3Hash *pHash, 
112600   const char *zName
112601 ){
112602   int rc = SQLITE_OK;
112603   void *p = (void *)pHash;
112604   const int any = SQLITE_ANY;
112605
112606 #ifdef SQLITE_TEST
112607   char *zTest = 0;
112608   char *zTest2 = 0;
112609   void *pdb = (void *)db;
112610   zTest = sqlite3_mprintf("%s_test", zName);
112611   zTest2 = sqlite3_mprintf("%s_internal_test", zName);
112612   if( !zTest || !zTest2 ){
112613     rc = SQLITE_NOMEM;
112614   }
112615 #endif
112616
112617   if( SQLITE_OK!=rc
112618    || SQLITE_OK!=(rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0))
112619    || SQLITE_OK!=(rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0))
112620 #ifdef SQLITE_TEST
112621    || SQLITE_OK!=(rc = sqlite3_create_function(db, zTest, 2, any, p, testFunc, 0, 0))
112622    || SQLITE_OK!=(rc = sqlite3_create_function(db, zTest, 3, any, p, testFunc, 0, 0))
112623    || SQLITE_OK!=(rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0))
112624 #endif
112625    );
112626
112627 #ifdef SQLITE_TEST
112628   sqlite3_free(zTest);
112629   sqlite3_free(zTest2);
112630 #endif
112631
112632   return rc;
112633 }
112634
112635 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
112636
112637 /************** End of fts3_tokenizer.c **************************************/
112638 /************** Begin file fts3_tokenizer1.c *********************************/
112639 /*
112640 ** 2006 Oct 10
112641 **
112642 ** The author disclaims copyright to this source code.  In place of
112643 ** a legal notice, here is a blessing:
112644 **
112645 **    May you do good and not evil.
112646 **    May you find forgiveness for yourself and forgive others.
112647 **    May you share freely, never taking more than you give.
112648 **
112649 ******************************************************************************
112650 **
112651 ** Implementation of the "simple" full-text-search tokenizer.
112652 */
112653
112654 /*
112655 ** The code in this file is only compiled if:
112656 **
112657 **     * The FTS3 module is being built as an extension
112658 **       (in which case SQLITE_CORE is not defined), or
112659 **
112660 **     * The FTS3 module is being built into the core of
112661 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
112662 */
112663 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
112664
112665
112666
112667
112668 typedef struct simple_tokenizer {
112669   sqlite3_tokenizer base;
112670   char delim[128];             /* flag ASCII delimiters */
112671 } simple_tokenizer;
112672
112673 typedef struct simple_tokenizer_cursor {
112674   sqlite3_tokenizer_cursor base;
112675   const char *pInput;          /* input we are tokenizing */
112676   int nBytes;                  /* size of the input */
112677   int iOffset;                 /* current position in pInput */
112678   int iToken;                  /* index of next token to be returned */
112679   char *pToken;                /* storage for current token */
112680   int nTokenAllocated;         /* space allocated to zToken buffer */
112681 } simple_tokenizer_cursor;
112682
112683
112684 static int simpleDelim(simple_tokenizer *t, unsigned char c){
112685   return c<0x80 && t->delim[c];
112686 }
112687 static int fts3_isalnum(int x){
112688   return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
112689 }
112690
112691 /*
112692 ** Create a new tokenizer instance.
112693 */
112694 static int simpleCreate(
112695   int argc, const char * const *argv,
112696   sqlite3_tokenizer **ppTokenizer
112697 ){
112698   simple_tokenizer *t;
112699
112700   t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
112701   if( t==NULL ) return SQLITE_NOMEM;
112702   memset(t, 0, sizeof(*t));
112703
112704   /* TODO(shess) Delimiters need to remain the same from run to run,
112705   ** else we need to reindex.  One solution would be a meta-table to
112706   ** track such information in the database, then we'd only want this
112707   ** information on the initial create.
112708   */
112709   if( argc>1 ){
112710     int i, n = (int)strlen(argv[1]);
112711     for(i=0; i<n; i++){
112712       unsigned char ch = argv[1][i];
112713       /* We explicitly don't support UTF-8 delimiters for now. */
112714       if( ch>=0x80 ){
112715         sqlite3_free(t);
112716         return SQLITE_ERROR;
112717       }
112718       t->delim[ch] = 1;
112719     }
112720   } else {
112721     /* Mark non-alphanumeric ASCII characters as delimiters */
112722     int i;
112723     for(i=1; i<0x80; i++){
112724       t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
112725     }
112726   }
112727
112728   *ppTokenizer = &t->base;
112729   return SQLITE_OK;
112730 }
112731
112732 /*
112733 ** Destroy a tokenizer
112734 */
112735 static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
112736   sqlite3_free(pTokenizer);
112737   return SQLITE_OK;
112738 }
112739
112740 /*
112741 ** Prepare to begin tokenizing a particular string.  The input
112742 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
112743 ** used to incrementally tokenize this string is returned in 
112744 ** *ppCursor.
112745 */
112746 static int simpleOpen(
112747   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
112748   const char *pInput, int nBytes,        /* String to be tokenized */
112749   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
112750 ){
112751   simple_tokenizer_cursor *c;
112752
112753   UNUSED_PARAMETER(pTokenizer);
112754
112755   c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
112756   if( c==NULL ) return SQLITE_NOMEM;
112757
112758   c->pInput = pInput;
112759   if( pInput==0 ){
112760     c->nBytes = 0;
112761   }else if( nBytes<0 ){
112762     c->nBytes = (int)strlen(pInput);
112763   }else{
112764     c->nBytes = nBytes;
112765   }
112766   c->iOffset = 0;                 /* start tokenizing at the beginning */
112767   c->iToken = 0;
112768   c->pToken = NULL;               /* no space allocated, yet. */
112769   c->nTokenAllocated = 0;
112770
112771   *ppCursor = &c->base;
112772   return SQLITE_OK;
112773 }
112774
112775 /*
112776 ** Close a tokenization cursor previously opened by a call to
112777 ** simpleOpen() above.
112778 */
112779 static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
112780   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
112781   sqlite3_free(c->pToken);
112782   sqlite3_free(c);
112783   return SQLITE_OK;
112784 }
112785
112786 /*
112787 ** Extract the next token from a tokenization cursor.  The cursor must
112788 ** have been opened by a prior call to simpleOpen().
112789 */
112790 static int simpleNext(
112791   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
112792   const char **ppToken,               /* OUT: *ppToken is the token text */
112793   int *pnBytes,                       /* OUT: Number of bytes in token */
112794   int *piStartOffset,                 /* OUT: Starting offset of token */
112795   int *piEndOffset,                   /* OUT: Ending offset of token */
112796   int *piPosition                     /* OUT: Position integer of token */
112797 ){
112798   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
112799   simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
112800   unsigned char *p = (unsigned char *)c->pInput;
112801
112802   while( c->iOffset<c->nBytes ){
112803     int iStartOffset;
112804
112805     /* Scan past delimiter characters */
112806     while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
112807       c->iOffset++;
112808     }
112809
112810     /* Count non-delimiter characters. */
112811     iStartOffset = c->iOffset;
112812     while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
112813       c->iOffset++;
112814     }
112815
112816     if( c->iOffset>iStartOffset ){
112817       int i, n = c->iOffset-iStartOffset;
112818       if( n>c->nTokenAllocated ){
112819         char *pNew;
112820         c->nTokenAllocated = n+20;
112821         pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
112822         if( !pNew ) return SQLITE_NOMEM;
112823         c->pToken = pNew;
112824       }
112825       for(i=0; i<n; i++){
112826         /* TODO(shess) This needs expansion to handle UTF-8
112827         ** case-insensitivity.
112828         */
112829         unsigned char ch = p[iStartOffset+i];
112830         c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
112831       }
112832       *ppToken = c->pToken;
112833       *pnBytes = n;
112834       *piStartOffset = iStartOffset;
112835       *piEndOffset = c->iOffset;
112836       *piPosition = c->iToken++;
112837
112838       return SQLITE_OK;
112839     }
112840   }
112841   return SQLITE_DONE;
112842 }
112843
112844 /*
112845 ** The set of routines that implement the simple tokenizer
112846 */
112847 static const sqlite3_tokenizer_module simpleTokenizerModule = {
112848   0,
112849   simpleCreate,
112850   simpleDestroy,
112851   simpleOpen,
112852   simpleClose,
112853   simpleNext,
112854 };
112855
112856 /*
112857 ** Allocate a new simple tokenizer.  Return a pointer to the new
112858 ** tokenizer in *ppModule
112859 */
112860 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
112861   sqlite3_tokenizer_module const**ppModule
112862 ){
112863   *ppModule = &simpleTokenizerModule;
112864 }
112865
112866 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
112867
112868 /************** End of fts3_tokenizer1.c *************************************/
112869 /************** Begin file fts3_write.c **************************************/
112870 /*
112871 ** 2009 Oct 23
112872 **
112873 ** The author disclaims copyright to this source code.  In place of
112874 ** a legal notice, here is a blessing:
112875 **
112876 **    May you do good and not evil.
112877 **    May you find forgiveness for yourself and forgive others.
112878 **    May you share freely, never taking more than you give.
112879 **
112880 ******************************************************************************
112881 **
112882 ** This file is part of the SQLite FTS3 extension module. Specifically,
112883 ** this file contains code to insert, update and delete rows from FTS3
112884 ** tables. It also contains code to merge FTS3 b-tree segments. Some
112885 ** of the sub-routines used to merge segments are also used by the query 
112886 ** code in fts3.c.
112887 */
112888
112889 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
112890
112891
112892 typedef struct PendingList PendingList;
112893 typedef struct SegmentNode SegmentNode;
112894 typedef struct SegmentWriter SegmentWriter;
112895
112896 /*
112897 ** Data structure used while accumulating terms in the pending-terms hash
112898 ** table. The hash table entry maps from term (a string) to a malloc'd
112899 ** instance of this structure.
112900 */
112901 struct PendingList {
112902   int nData;
112903   char *aData;
112904   int nSpace;
112905   sqlite3_int64 iLastDocid;
112906   sqlite3_int64 iLastCol;
112907   sqlite3_int64 iLastPos;
112908 };
112909
112910 /*
112911 ** An instance of this structure is used to iterate through the terms on
112912 ** a contiguous set of segment b-tree leaf nodes. Although the details of
112913 ** this structure are only manipulated by code in this file, opaque handles
112914 ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
112915 ** terms when querying the full-text index. See functions:
112916 **
112917 **   sqlite3Fts3SegReaderNew()
112918 **   sqlite3Fts3SegReaderFree()
112919 **   sqlite3Fts3SegReaderIterate()
112920 **
112921 ** Methods used to manipulate Fts3SegReader structures:
112922 **
112923 **   fts3SegReaderNext()
112924 **   fts3SegReaderFirstDocid()
112925 **   fts3SegReaderNextDocid()
112926 */
112927 struct Fts3SegReader {
112928   int iIdx;                       /* Index within level, or 0x7FFFFFFF for PT */
112929   sqlite3_int64 iStartBlock;
112930   sqlite3_int64 iEndBlock;
112931   sqlite3_stmt *pStmt;            /* SQL Statement to access leaf nodes */
112932   char *aNode;                    /* Pointer to node data (or NULL) */
112933   int nNode;                      /* Size of buffer at aNode (or 0) */
112934   int nTermAlloc;                 /* Allocated size of zTerm buffer */
112935   Fts3HashElem **ppNextElem;
112936
112937   /* Variables set by fts3SegReaderNext(). These may be read directly
112938   ** by the caller. They are valid from the time SegmentReaderNew() returns
112939   ** until SegmentReaderNext() returns something other than SQLITE_OK
112940   ** (i.e. SQLITE_DONE).
112941   */
112942   int nTerm;                      /* Number of bytes in current term */
112943   char *zTerm;                    /* Pointer to current term */
112944   char *aDoclist;                 /* Pointer to doclist of current entry */
112945   int nDoclist;                   /* Size of doclist in current entry */
112946
112947   /* The following variables are used to iterate through the current doclist */
112948   char *pOffsetList;
112949   sqlite3_int64 iDocid;
112950 };
112951
112952 #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
112953
112954 /*
112955 ** An instance of this structure is used to create a segment b-tree in the
112956 ** database. The internal details of this type are only accessed by the
112957 ** following functions:
112958 **
112959 **   fts3SegWriterAdd()
112960 **   fts3SegWriterFlush()
112961 **   fts3SegWriterFree()
112962 */
112963 struct SegmentWriter {
112964   SegmentNode *pTree;             /* Pointer to interior tree structure */
112965   sqlite3_int64 iFirst;           /* First slot in %_segments written */
112966   sqlite3_int64 iFree;            /* Next free slot in %_segments */
112967   char *zTerm;                    /* Pointer to previous term buffer */
112968   int nTerm;                      /* Number of bytes in zTerm */
112969   int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
112970   char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
112971   int nSize;                      /* Size of allocation at aData */
112972   int nData;                      /* Bytes of data in aData */
112973   char *aData;                    /* Pointer to block from malloc() */
112974 };
112975
112976 /*
112977 ** Type SegmentNode is used by the following three functions to create
112978 ** the interior part of the segment b+-tree structures (everything except
112979 ** the leaf nodes). These functions and type are only ever used by code
112980 ** within the fts3SegWriterXXX() family of functions described above.
112981 **
112982 **   fts3NodeAddTerm()
112983 **   fts3NodeWrite()
112984 **   fts3NodeFree()
112985 */
112986 struct SegmentNode {
112987   SegmentNode *pParent;           /* Parent node (or NULL for root node) */
112988   SegmentNode *pRight;            /* Pointer to right-sibling */
112989   SegmentNode *pLeftmost;         /* Pointer to left-most node of this depth */
112990   int nEntry;                     /* Number of terms written to node so far */
112991   char *zTerm;                    /* Pointer to previous term buffer */
112992   int nTerm;                      /* Number of bytes in zTerm */
112993   int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
112994   char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
112995   int nData;                      /* Bytes of valid data so far */
112996   char *aData;                    /* Node data */
112997 };
112998
112999 /*
113000 ** Valid values for the second argument to fts3SqlStmt().
113001 */
113002 #define SQL_DELETE_CONTENT             0
113003 #define SQL_IS_EMPTY                   1
113004 #define SQL_DELETE_ALL_CONTENT         2 
113005 #define SQL_DELETE_ALL_SEGMENTS        3
113006 #define SQL_DELETE_ALL_SEGDIR          4
113007 #define SQL_DELETE_ALL_DOCSIZE         5
113008 #define SQL_DELETE_ALL_STAT            6
113009 #define SQL_SELECT_CONTENT_BY_ROWID    7
113010 #define SQL_NEXT_SEGMENT_INDEX         8
113011 #define SQL_INSERT_SEGMENTS            9
113012 #define SQL_NEXT_SEGMENTS_ID          10
113013 #define SQL_INSERT_SEGDIR             11
113014 #define SQL_SELECT_LEVEL              12
113015 #define SQL_SELECT_ALL_LEVEL          13
113016 #define SQL_SELECT_LEVEL_COUNT        14
113017 #define SQL_SELECT_SEGDIR_COUNT_MAX   15
113018 #define SQL_DELETE_SEGDIR_BY_LEVEL    16
113019 #define SQL_DELETE_SEGMENTS_RANGE     17
113020 #define SQL_CONTENT_INSERT            18
113021 #define SQL_GET_BLOCK                 19
113022 #define SQL_DELETE_DOCSIZE            20
113023 #define SQL_REPLACE_DOCSIZE           21
113024 #define SQL_SELECT_DOCSIZE            22
113025 #define SQL_SELECT_DOCTOTAL           23
113026 #define SQL_REPLACE_DOCTOTAL          24
113027
113028 /*
113029 ** This function is used to obtain an SQLite prepared statement handle
113030 ** for the statement identified by the second argument. If successful,
113031 ** *pp is set to the requested statement handle and SQLITE_OK returned.
113032 ** Otherwise, an SQLite error code is returned and *pp is set to 0.
113033 **
113034 ** If argument apVal is not NULL, then it must point to an array with
113035 ** at least as many entries as the requested statement has bound 
113036 ** parameters. The values are bound to the statements parameters before
113037 ** returning.
113038 */
113039 static int fts3SqlStmt(
113040   Fts3Table *p,                   /* Virtual table handle */
113041   int eStmt,                      /* One of the SQL_XXX constants above */
113042   sqlite3_stmt **pp,              /* OUT: Statement handle */
113043   sqlite3_value **apVal           /* Values to bind to statement */
113044 ){
113045   const char *azSql[] = {
113046 /* 0  */  "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
113047 /* 1  */  "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
113048 /* 2  */  "DELETE FROM %Q.'%q_content'",
113049 /* 3  */  "DELETE FROM %Q.'%q_segments'",
113050 /* 4  */  "DELETE FROM %Q.'%q_segdir'",
113051 /* 5  */  "DELETE FROM %Q.'%q_docsize'",
113052 /* 6  */  "DELETE FROM %Q.'%q_stat'",
113053 /* 7  */  "SELECT * FROM %Q.'%q_content' WHERE rowid=?",
113054 /* 8  */  "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
113055 /* 9  */  "INSERT INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
113056 /* 10 */  "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
113057 /* 11 */  "INSERT INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
113058
113059           /* Return segments in order from oldest to newest.*/ 
113060 /* 12 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
113061             "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
113062 /* 13 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
113063             "FROM %Q.'%q_segdir' ORDER BY level DESC, idx ASC",
113064
113065 /* 14 */  "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
113066 /* 15 */  "SELECT count(*), max(level) FROM %Q.'%q_segdir'",
113067
113068 /* 16 */  "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
113069 /* 17 */  "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
113070 /* 18 */  "INSERT INTO %Q.'%q_content' VALUES(%z)",
113071 /* 19 */  "SELECT block FROM %Q.'%q_segments' WHERE blockid = ?",
113072 /* 20 */  "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
113073 /* 21 */  "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
113074 /* 22 */  "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
113075 /* 23 */  "SELECT value FROM %Q.'%q_stat' WHERE id=0",
113076 /* 24 */  "REPLACE INTO %Q.'%q_stat' VALUES(0,?)",
113077   };
113078   int rc = SQLITE_OK;
113079   sqlite3_stmt *pStmt;
113080
113081   assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
113082   assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
113083   
113084   pStmt = p->aStmt[eStmt];
113085   if( !pStmt ){
113086     char *zSql;
113087     if( eStmt==SQL_CONTENT_INSERT ){
113088       int i;                      /* Iterator variable */  
113089       char *zVarlist;             /* The "?, ?, ..." string */
113090       zVarlist = (char *)sqlite3_malloc(2*p->nColumn+2);
113091       if( !zVarlist ){
113092         *pp = 0;
113093         return SQLITE_NOMEM;
113094       }
113095       zVarlist[0] = '?';
113096       zVarlist[p->nColumn*2+1] = '\0';
113097       for(i=1; i<=p->nColumn; i++){
113098         zVarlist[i*2-1] = ',';
113099         zVarlist[i*2] = '?';
113100       }
113101       zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, zVarlist);
113102     }else{
113103       zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
113104     }
113105     if( !zSql ){
113106       rc = SQLITE_NOMEM;
113107     }else{
113108       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
113109       sqlite3_free(zSql);
113110       assert( rc==SQLITE_OK || pStmt==0 );
113111       p->aStmt[eStmt] = pStmt;
113112     }
113113   }
113114   if( apVal ){
113115     int i;
113116     int nParam = sqlite3_bind_parameter_count(pStmt);
113117     for(i=0; rc==SQLITE_OK && i<nParam; i++){
113118       rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
113119     }
113120   }
113121   *pp = pStmt;
113122   return rc;
113123 }
113124
113125 /*
113126 ** Similar to fts3SqlStmt(). Except, after binding the parameters in
113127 ** array apVal[] to the SQL statement identified by eStmt, the statement
113128 ** is executed.
113129 **
113130 ** Returns SQLITE_OK if the statement is successfully executed, or an
113131 ** SQLite error code otherwise.
113132 */
113133 static void fts3SqlExec(
113134   int *pRC,                /* Result code */
113135   Fts3Table *p,            /* The FTS3 table */
113136   int eStmt,               /* Index of statement to evaluate */
113137   sqlite3_value **apVal    /* Parameters to bind */
113138 ){
113139   sqlite3_stmt *pStmt;
113140   int rc;
113141   if( *pRC ) return;
113142   rc = fts3SqlStmt(p, eStmt, &pStmt, apVal); 
113143   if( rc==SQLITE_OK ){
113144     sqlite3_step(pStmt);
113145     rc = sqlite3_reset(pStmt);
113146   }
113147   *pRC = rc;
113148 }
113149
113150
113151 /*
113152 ** Read a single block from the %_segments table. If the specified block
113153 ** does not exist, return SQLITE_CORRUPT. If some other error (malloc, IO 
113154 ** etc.) occurs, return the appropriate SQLite error code.
113155 **
113156 ** Otherwise, if successful, set *pzBlock to point to a buffer containing
113157 ** the block read from the database, and *pnBlock to the size of the read
113158 ** block in bytes.
113159 **
113160 ** WARNING: The returned buffer is only valid until the next call to 
113161 ** sqlite3Fts3ReadBlock().
113162 */
113163 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
113164   Fts3Table *p,
113165   sqlite3_int64 iBlock,
113166   char const **pzBlock,
113167   int *pnBlock
113168 ){
113169   sqlite3_stmt *pStmt;
113170   int rc = fts3SqlStmt(p, SQL_GET_BLOCK, &pStmt, 0);
113171   if( rc!=SQLITE_OK ) return rc;
113172   sqlite3_reset(pStmt);
113173
113174   if( pzBlock ){
113175     sqlite3_bind_int64(pStmt, 1, iBlock);
113176     rc = sqlite3_step(pStmt); 
113177     if( rc!=SQLITE_ROW ){
113178       return (rc==SQLITE_DONE ? SQLITE_CORRUPT : rc);
113179     }
113180   
113181     *pnBlock = sqlite3_column_bytes(pStmt, 0);
113182     *pzBlock = (char *)sqlite3_column_blob(pStmt, 0);
113183     if( sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
113184       return SQLITE_CORRUPT;
113185     }
113186   }
113187   return SQLITE_OK;
113188 }
113189
113190 /*
113191 ** This function ensures that the caller has obtained a shared-cache
113192 ** table-lock on the %_content table. This is required before reading
113193 ** data from the fts3 table. If this lock is not acquired first, then
113194 ** the caller may end up holding read-locks on the %_segments and %_segdir
113195 ** tables, but no read-lock on the %_content table. If this happens 
113196 ** a second connection will be able to write to the fts3 table, but
113197 ** attempting to commit those writes might return SQLITE_LOCKED or
113198 ** SQLITE_LOCKED_SHAREDCACHE (because the commit attempts to obtain 
113199 ** write-locks on the %_segments and %_segdir ** tables). 
113200 **
113201 ** We try to avoid this because if FTS3 returns any error when committing
113202 ** a transaction, the whole transaction will be rolled back. And this is
113203 ** not what users expect when they get SQLITE_LOCKED_SHAREDCACHE. It can
113204 ** still happen if the user reads data directly from the %_segments or
113205 ** %_segdir tables instead of going through FTS3 though.
113206 */
113207 SQLITE_PRIVATE int sqlite3Fts3ReadLock(Fts3Table *p){
113208   int rc;                         /* Return code */
113209   sqlite3_stmt *pStmt;            /* Statement used to obtain lock */
113210
113211   rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pStmt, 0);
113212   if( rc==SQLITE_OK ){
113213     sqlite3_bind_null(pStmt, 1);
113214     sqlite3_step(pStmt);
113215     rc = sqlite3_reset(pStmt);
113216   }
113217   return rc;
113218 }
113219
113220 /*
113221 ** Set *ppStmt to a statement handle that may be used to iterate through
113222 ** all rows in the %_segdir table, from oldest to newest. If successful,
113223 ** return SQLITE_OK. If an error occurs while preparing the statement, 
113224 ** return an SQLite error code.
113225 **
113226 ** There is only ever one instance of this SQL statement compiled for
113227 ** each FTS3 table.
113228 **
113229 ** The statement returns the following columns from the %_segdir table:
113230 **
113231 **   0: idx
113232 **   1: start_block
113233 **   2: leaves_end_block
113234 **   3: end_block
113235 **   4: root
113236 */
113237 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table *p, sqlite3_stmt **ppStmt){
113238   return fts3SqlStmt(p, SQL_SELECT_ALL_LEVEL, ppStmt, 0);
113239 }
113240
113241
113242 /*
113243 ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
113244 ** if successful, or an SQLite error code otherwise.
113245 **
113246 ** This function also serves to allocate the PendingList structure itself.
113247 ** For example, to create a new PendingList structure containing two
113248 ** varints:
113249 **
113250 **   PendingList *p = 0;
113251 **   fts3PendingListAppendVarint(&p, 1);
113252 **   fts3PendingListAppendVarint(&p, 2);
113253 */
113254 static int fts3PendingListAppendVarint(
113255   PendingList **pp,               /* IN/OUT: Pointer to PendingList struct */
113256   sqlite3_int64 i                 /* Value to append to data */
113257 ){
113258   PendingList *p = *pp;
113259
113260   /* Allocate or grow the PendingList as required. */
113261   if( !p ){
113262     p = sqlite3_malloc(sizeof(*p) + 100);
113263     if( !p ){
113264       return SQLITE_NOMEM;
113265     }
113266     p->nSpace = 100;
113267     p->aData = (char *)&p[1];
113268     p->nData = 0;
113269   }
113270   else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
113271     int nNew = p->nSpace * 2;
113272     p = sqlite3_realloc(p, sizeof(*p) + nNew);
113273     if( !p ){
113274       sqlite3_free(*pp);
113275       *pp = 0;
113276       return SQLITE_NOMEM;
113277     }
113278     p->nSpace = nNew;
113279     p->aData = (char *)&p[1];
113280   }
113281
113282   /* Append the new serialized varint to the end of the list. */
113283   p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
113284   p->aData[p->nData] = '\0';
113285   *pp = p;
113286   return SQLITE_OK;
113287 }
113288
113289 /*
113290 ** Add a docid/column/position entry to a PendingList structure. Non-zero
113291 ** is returned if the structure is sqlite3_realloced as part of adding
113292 ** the entry. Otherwise, zero.
113293 **
113294 ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
113295 ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
113296 ** it is set to SQLITE_OK.
113297 */
113298 static int fts3PendingListAppend(
113299   PendingList **pp,               /* IN/OUT: PendingList structure */
113300   sqlite3_int64 iDocid,           /* Docid for entry to add */
113301   sqlite3_int64 iCol,             /* Column for entry to add */
113302   sqlite3_int64 iPos,             /* Position of term for entry to add */
113303   int *pRc                        /* OUT: Return code */
113304 ){
113305   PendingList *p = *pp;
113306   int rc = SQLITE_OK;
113307
113308   assert( !p || p->iLastDocid<=iDocid );
113309
113310   if( !p || p->iLastDocid!=iDocid ){
113311     sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
113312     if( p ){
113313       assert( p->nData<p->nSpace );
113314       assert( p->aData[p->nData]==0 );
113315       p->nData++;
113316     }
113317     if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
113318       goto pendinglistappend_out;
113319     }
113320     p->iLastCol = -1;
113321     p->iLastPos = 0;
113322     p->iLastDocid = iDocid;
113323   }
113324   if( iCol>0 && p->iLastCol!=iCol ){
113325     if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
113326      || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
113327     ){
113328       goto pendinglistappend_out;
113329     }
113330     p->iLastCol = iCol;
113331     p->iLastPos = 0;
113332   }
113333   if( iCol>=0 ){
113334     assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
113335     rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
113336     if( rc==SQLITE_OK ){
113337       p->iLastPos = iPos;
113338     }
113339   }
113340
113341  pendinglistappend_out:
113342   *pRc = rc;
113343   if( p!=*pp ){
113344     *pp = p;
113345     return 1;
113346   }
113347   return 0;
113348 }
113349
113350 /*
113351 ** Tokenize the nul-terminated string zText and add all tokens to the
113352 ** pending-terms hash-table. The docid used is that currently stored in
113353 ** p->iPrevDocid, and the column is specified by argument iCol.
113354 **
113355 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
113356 */
113357 static int fts3PendingTermsAdd(
113358   Fts3Table *p,          /* FTS table into which text will be inserted */
113359   const char *zText,     /* Text of document to be inseted */
113360   int iCol,              /* Column number into which text is inserted */
113361   u32 *pnWord            /* OUT: Number of tokens inserted */
113362 ){
113363   int rc;
113364   int iStart;
113365   int iEnd;
113366   int iPos;
113367   int nWord = 0;
113368
113369   char const *zToken;
113370   int nToken;
113371
113372   sqlite3_tokenizer *pTokenizer = p->pTokenizer;
113373   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
113374   sqlite3_tokenizer_cursor *pCsr;
113375   int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
113376       const char**,int*,int*,int*,int*);
113377
113378   assert( pTokenizer && pModule );
113379
113380   rc = pModule->xOpen(pTokenizer, zText, -1, &pCsr);
113381   if( rc!=SQLITE_OK ){
113382     return rc;
113383   }
113384   pCsr->pTokenizer = pTokenizer;
113385
113386   xNext = pModule->xNext;
113387   while( SQLITE_OK==rc
113388       && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
113389   ){
113390     PendingList *pList;
113391  
113392     if( iPos>=nWord ) nWord = iPos+1;
113393
113394     /* Positions cannot be negative; we use -1 as a terminator internally.
113395     ** Tokens must have a non-zero length.
113396     */
113397     if( iPos<0 || !zToken || nToken<=0 ){
113398       rc = SQLITE_ERROR;
113399       break;
113400     }
113401
113402     pList = (PendingList *)fts3HashFind(&p->pendingTerms, zToken, nToken);
113403     if( pList ){
113404       p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
113405     }
113406     if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
113407       if( pList==fts3HashInsert(&p->pendingTerms, zToken, nToken, pList) ){
113408         /* Malloc failed while inserting the new entry. This can only 
113409         ** happen if there was no previous entry for this token.
113410         */
113411         assert( 0==fts3HashFind(&p->pendingTerms, zToken, nToken) );
113412         sqlite3_free(pList);
113413         rc = SQLITE_NOMEM;
113414       }
113415     }
113416     if( rc==SQLITE_OK ){
113417       p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
113418     }
113419   }
113420
113421   pModule->xClose(pCsr);
113422   *pnWord = nWord;
113423   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
113424 }
113425
113426 /* 
113427 ** Calling this function indicates that subsequent calls to 
113428 ** fts3PendingTermsAdd() are to add term/position-list pairs for the
113429 ** contents of the document with docid iDocid.
113430 */
113431 static int fts3PendingTermsDocid(Fts3Table *p, sqlite_int64 iDocid){
113432   /* TODO(shess) Explore whether partially flushing the buffer on
113433   ** forced-flush would provide better performance.  I suspect that if
113434   ** we ordered the doclists by size and flushed the largest until the
113435   ** buffer was half empty, that would let the less frequent terms
113436   ** generate longer doclists.
113437   */
113438   if( iDocid<=p->iPrevDocid || p->nPendingData>p->nMaxPendingData ){
113439     int rc = sqlite3Fts3PendingTermsFlush(p);
113440     if( rc!=SQLITE_OK ) return rc;
113441   }
113442   p->iPrevDocid = iDocid;
113443   return SQLITE_OK;
113444 }
113445
113446 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
113447   Fts3HashElem *pElem;
113448   for(pElem=fts3HashFirst(&p->pendingTerms); pElem; pElem=fts3HashNext(pElem)){
113449     sqlite3_free(fts3HashData(pElem));
113450   }
113451   fts3HashClear(&p->pendingTerms);
113452   p->nPendingData = 0;
113453 }
113454
113455 /*
113456 ** This function is called by the xUpdate() method as part of an INSERT
113457 ** operation. It adds entries for each term in the new record to the
113458 ** pendingTerms hash table.
113459 **
113460 ** Argument apVal is the same as the similarly named argument passed to
113461 ** fts3InsertData(). Parameter iDocid is the docid of the new row.
113462 */
113463 static int fts3InsertTerms(Fts3Table *p, sqlite3_value **apVal, u32 *aSz){
113464   int i;                          /* Iterator variable */
113465   for(i=2; i<p->nColumn+2; i++){
113466     const char *zText = (const char *)sqlite3_value_text(apVal[i]);
113467     if( zText ){
113468       int rc = fts3PendingTermsAdd(p, zText, i-2, &aSz[i-2]);
113469       if( rc!=SQLITE_OK ){
113470         return rc;
113471       }
113472     }
113473   }
113474   return SQLITE_OK;
113475 }
113476
113477 /*
113478 ** This function is called by the xUpdate() method for an INSERT operation.
113479 ** The apVal parameter is passed a copy of the apVal argument passed by
113480 ** SQLite to the xUpdate() method. i.e:
113481 **
113482 **   apVal[0]                Not used for INSERT.
113483 **   apVal[1]                rowid
113484 **   apVal[2]                Left-most user-defined column
113485 **   ...
113486 **   apVal[p->nColumn+1]     Right-most user-defined column
113487 **   apVal[p->nColumn+2]     Hidden column with same name as table
113488 **   apVal[p->nColumn+3]     Hidden "docid" column (alias for rowid)
113489 */
113490 static int fts3InsertData(
113491   Fts3Table *p,                   /* Full-text table */
113492   sqlite3_value **apVal,          /* Array of values to insert */
113493   sqlite3_int64 *piDocid          /* OUT: Docid for row just inserted */
113494 ){
113495   int rc;                         /* Return code */
113496   sqlite3_stmt *pContentInsert;   /* INSERT INTO %_content VALUES(...) */
113497
113498   /* Locate the statement handle used to insert data into the %_content
113499   ** table. The SQL for this statement is:
113500   **
113501   **   INSERT INTO %_content VALUES(?, ?, ?, ...)
113502   **
113503   ** The statement features N '?' variables, where N is the number of user
113504   ** defined columns in the FTS3 table, plus one for the docid field.
113505   */
113506   rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
113507   if( rc!=SQLITE_OK ){
113508     return rc;
113509   }
113510
113511   /* There is a quirk here. The users INSERT statement may have specified
113512   ** a value for the "rowid" field, for the "docid" field, or for both.
113513   ** Which is a problem, since "rowid" and "docid" are aliases for the
113514   ** same value. For example:
113515   **
113516   **   INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
113517   **
113518   ** In FTS3, this is an error. It is an error to specify non-NULL values
113519   ** for both docid and some other rowid alias.
113520   */
113521   if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
113522     if( SQLITE_NULL==sqlite3_value_type(apVal[0])
113523      && SQLITE_NULL!=sqlite3_value_type(apVal[1])
113524     ){
113525       /* A rowid/docid conflict. */
113526       return SQLITE_ERROR;
113527     }
113528     rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
113529     if( rc!=SQLITE_OK ) return rc;
113530   }
113531
113532   /* Execute the statement to insert the record. Set *piDocid to the 
113533   ** new docid value. 
113534   */
113535   sqlite3_step(pContentInsert);
113536   rc = sqlite3_reset(pContentInsert);
113537
113538   *piDocid = sqlite3_last_insert_rowid(p->db);
113539   return rc;
113540 }
113541
113542
113543
113544 /*
113545 ** Remove all data from the FTS3 table. Clear the hash table containing
113546 ** pending terms.
113547 */
113548 static int fts3DeleteAll(Fts3Table *p){
113549   int rc = SQLITE_OK;             /* Return code */
113550
113551   /* Discard the contents of the pending-terms hash table. */
113552   sqlite3Fts3PendingTermsClear(p);
113553
113554   /* Delete everything from the %_content, %_segments and %_segdir tables. */
113555   fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
113556   fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
113557   fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
113558   if( p->bHasDocsize ){
113559     fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
113560     fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
113561   }
113562   return rc;
113563 }
113564
113565 /*
113566 ** The first element in the apVal[] array is assumed to contain the docid
113567 ** (an integer) of a row about to be deleted. Remove all terms from the
113568 ** full-text index.
113569 */
113570 static void fts3DeleteTerms(
113571   int *pRC,               /* Result code */
113572   Fts3Table *p,           /* The FTS table to delete from */
113573   sqlite3_value **apVal,  /* apVal[] contains the docid to be deleted */
113574   u32 *aSz                /* Sizes of deleted document written here */
113575 ){
113576   int rc;
113577   sqlite3_stmt *pSelect;
113578
113579   if( *pRC ) return;
113580   rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, apVal);
113581   if( rc==SQLITE_OK ){
113582     if( SQLITE_ROW==sqlite3_step(pSelect) ){
113583       int i;
113584       for(i=1; i<=p->nColumn; i++){
113585         const char *zText = (const char *)sqlite3_column_text(pSelect, i);
113586         rc = fts3PendingTermsAdd(p, zText, -1, &aSz[i-1]);
113587         if( rc!=SQLITE_OK ){
113588           sqlite3_reset(pSelect);
113589           *pRC = rc;
113590           return;
113591         }
113592       }
113593     }
113594     rc = sqlite3_reset(pSelect);
113595   }else{
113596     sqlite3_reset(pSelect);
113597   }
113598   *pRC = rc;
113599 }
113600
113601 /*
113602 ** Forward declaration to account for the circular dependency between
113603 ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
113604 */
113605 static int fts3SegmentMerge(Fts3Table *, int);
113606
113607 /* 
113608 ** This function allocates a new level iLevel index in the segdir table.
113609 ** Usually, indexes are allocated within a level sequentially starting
113610 ** with 0, so the allocated index is one greater than the value returned
113611 ** by:
113612 **
113613 **   SELECT max(idx) FROM %_segdir WHERE level = :iLevel
113614 **
113615 ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
113616 ** level, they are merged into a single level (iLevel+1) segment and the 
113617 ** allocated index is 0.
113618 **
113619 ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
113620 ** returned. Otherwise, an SQLite error code is returned.
113621 */
113622 static int fts3AllocateSegdirIdx(Fts3Table *p, int iLevel, int *piIdx){
113623   int rc;                         /* Return Code */
113624   sqlite3_stmt *pNextIdx;         /* Query for next idx at level iLevel */
113625   int iNext = 0;                  /* Result of query pNextIdx */
113626
113627   /* Set variable iNext to the next available segdir index at level iLevel. */
113628   rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
113629   if( rc==SQLITE_OK ){
113630     sqlite3_bind_int(pNextIdx, 1, iLevel);
113631     if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
113632       iNext = sqlite3_column_int(pNextIdx, 0);
113633     }
113634     rc = sqlite3_reset(pNextIdx);
113635   }
113636
113637   if( rc==SQLITE_OK ){
113638     /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
113639     ** full, merge all segments in level iLevel into a single iLevel+1
113640     ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
113641     ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
113642     */
113643     if( iNext>=FTS3_MERGE_COUNT ){
113644       rc = fts3SegmentMerge(p, iLevel);
113645       *piIdx = 0;
113646     }else{
113647       *piIdx = iNext;
113648     }
113649   }
113650
113651   return rc;
113652 }
113653
113654 /*
113655 ** Move the iterator passed as the first argument to the next term in the
113656 ** segment. If successful, SQLITE_OK is returned. If there is no next term,
113657 ** SQLITE_DONE. Otherwise, an SQLite error code.
113658 */
113659 static int fts3SegReaderNext(Fts3SegReader *pReader){
113660   char *pNext;                    /* Cursor variable */
113661   int nPrefix;                    /* Number of bytes in term prefix */
113662   int nSuffix;                    /* Number of bytes in term suffix */
113663
113664   if( !pReader->aDoclist ){
113665     pNext = pReader->aNode;
113666   }else{
113667     pNext = &pReader->aDoclist[pReader->nDoclist];
113668   }
113669
113670   if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
113671     int rc;
113672     if( fts3SegReaderIsPending(pReader) ){
113673       Fts3HashElem *pElem = *(pReader->ppNextElem);
113674       if( pElem==0 ){
113675         pReader->aNode = 0;
113676       }else{
113677         PendingList *pList = (PendingList *)fts3HashData(pElem);
113678         pReader->zTerm = (char *)fts3HashKey(pElem);
113679         pReader->nTerm = fts3HashKeysize(pElem);
113680         pReader->nNode = pReader->nDoclist = pList->nData + 1;
113681         pReader->aNode = pReader->aDoclist = pList->aData;
113682         pReader->ppNextElem++;
113683         assert( pReader->aNode );
113684       }
113685       return SQLITE_OK;
113686     }
113687     if( !pReader->pStmt ){
113688       pReader->aNode = 0;
113689       return SQLITE_OK;
113690     }
113691     rc = sqlite3_step(pReader->pStmt);
113692     if( rc!=SQLITE_ROW ){
113693       pReader->aNode = 0;
113694       return (rc==SQLITE_DONE ? SQLITE_OK : rc);
113695     }
113696     pReader->nNode = sqlite3_column_bytes(pReader->pStmt, 0);
113697     pReader->aNode = (char *)sqlite3_column_blob(pReader->pStmt, 0);
113698     pNext = pReader->aNode;
113699   }
113700   
113701   pNext += sqlite3Fts3GetVarint32(pNext, &nPrefix);
113702   pNext += sqlite3Fts3GetVarint32(pNext, &nSuffix);
113703
113704   if( nPrefix+nSuffix>pReader->nTermAlloc ){
113705     int nNew = (nPrefix+nSuffix)*2;
113706     char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
113707     if( !zNew ){
113708       return SQLITE_NOMEM;
113709     }
113710     pReader->zTerm = zNew;
113711     pReader->nTermAlloc = nNew;
113712   }
113713   memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
113714   pReader->nTerm = nPrefix+nSuffix;
113715   pNext += nSuffix;
113716   pNext += sqlite3Fts3GetVarint32(pNext, &pReader->nDoclist);
113717   assert( pNext<&pReader->aNode[pReader->nNode] );
113718   pReader->aDoclist = pNext;
113719   pReader->pOffsetList = 0;
113720   return SQLITE_OK;
113721 }
113722
113723 /*
113724 ** Set the SegReader to point to the first docid in the doclist associated
113725 ** with the current term.
113726 */
113727 static void fts3SegReaderFirstDocid(Fts3SegReader *pReader){
113728   int n;
113729   assert( pReader->aDoclist );
113730   assert( !pReader->pOffsetList );
113731   n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
113732   pReader->pOffsetList = &pReader->aDoclist[n];
113733 }
113734
113735 /*
113736 ** Advance the SegReader to point to the next docid in the doclist
113737 ** associated with the current term.
113738 ** 
113739 ** If arguments ppOffsetList and pnOffsetList are not NULL, then 
113740 ** *ppOffsetList is set to point to the first column-offset list
113741 ** in the doclist entry (i.e. immediately past the docid varint).
113742 ** *pnOffsetList is set to the length of the set of column-offset
113743 ** lists, not including the nul-terminator byte. For example:
113744 */
113745 static void fts3SegReaderNextDocid(
113746   Fts3SegReader *pReader,
113747   char **ppOffsetList,
113748   int *pnOffsetList
113749 ){
113750   char *p = pReader->pOffsetList;
113751   char c = 0;
113752
113753   /* Pointer p currently points at the first byte of an offset list. The
113754   ** following two lines advance it to point one byte past the end of
113755   ** the same offset list.
113756   */
113757   while( *p | c ) c = *p++ & 0x80;
113758   p++;
113759
113760   /* If required, populate the output variables with a pointer to and the
113761   ** size of the previous offset-list.
113762   */
113763   if( ppOffsetList ){
113764     *ppOffsetList = pReader->pOffsetList;
113765     *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
113766   }
113767
113768   /* If there are no more entries in the doclist, set pOffsetList to
113769   ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
113770   ** Fts3SegReader.pOffsetList to point to the next offset list before
113771   ** returning.
113772   */
113773   if( p>=&pReader->aDoclist[pReader->nDoclist] ){
113774     pReader->pOffsetList = 0;
113775   }else{
113776     sqlite3_int64 iDelta;
113777     pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
113778     pReader->iDocid += iDelta;
113779   }
113780 }
113781
113782 /*
113783 ** Free all allocations associated with the iterator passed as the 
113784 ** second argument.
113785 */
113786 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3Table *p, Fts3SegReader *pReader){
113787   if( pReader ){
113788     if( pReader->pStmt ){
113789       /* Move the leaf-range SELECT statement to the aLeavesStmt[] array,
113790       ** so that it can be reused when required by another query.
113791       */
113792       assert( p->nLeavesStmt<p->nLeavesTotal );
113793       sqlite3_reset(pReader->pStmt);
113794       p->aLeavesStmt[p->nLeavesStmt++] = pReader->pStmt;
113795     }
113796     if( !fts3SegReaderIsPending(pReader) ){
113797       sqlite3_free(pReader->zTerm);
113798     }
113799     sqlite3_free(pReader);
113800   }
113801 }
113802
113803 /*
113804 ** Allocate a new SegReader object.
113805 */
113806 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
113807   Fts3Table *p,                   /* Virtual table handle */
113808   int iAge,                       /* Segment "age". */
113809   sqlite3_int64 iStartLeaf,       /* First leaf to traverse */
113810   sqlite3_int64 iEndLeaf,         /* Final leaf to traverse */
113811   sqlite3_int64 iEndBlock,        /* Final block of segment */
113812   const char *zRoot,              /* Buffer containing root node */
113813   int nRoot,                      /* Size of buffer containing root node */
113814   Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
113815 ){
113816   int rc = SQLITE_OK;             /* Return code */
113817   Fts3SegReader *pReader;         /* Newly allocated SegReader object */
113818   int nExtra = 0;                 /* Bytes to allocate segment root node */
113819
113820   if( iStartLeaf==0 ){
113821     nExtra = nRoot;
113822   }
113823
113824   pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
113825   if( !pReader ){
113826     return SQLITE_NOMEM;
113827   }
113828   memset(pReader, 0, sizeof(Fts3SegReader));
113829   pReader->iStartBlock = iStartLeaf;
113830   pReader->iIdx = iAge;
113831   pReader->iEndBlock = iEndBlock;
113832
113833   if( nExtra ){
113834     /* The entire segment is stored in the root node. */
113835     pReader->aNode = (char *)&pReader[1];
113836     pReader->nNode = nRoot;
113837     memcpy(pReader->aNode, zRoot, nRoot);
113838   }else{
113839     /* If the text of the SQL statement to iterate through a contiguous
113840     ** set of entries in the %_segments table has not yet been composed,
113841     ** compose it now.
113842     */
113843     if( !p->zSelectLeaves ){
113844       p->zSelectLeaves = sqlite3_mprintf(
113845           "SELECT block FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ? "
113846           "ORDER BY blockid", p->zDb, p->zName
113847       );
113848       if( !p->zSelectLeaves ){
113849         rc = SQLITE_NOMEM;
113850         goto finished;
113851       }
113852     }
113853
113854     /* If there are no free statements in the aLeavesStmt[] array, prepare
113855     ** a new statement now. Otherwise, reuse a prepared statement from
113856     ** aLeavesStmt[].
113857     */
113858     if( p->nLeavesStmt==0 ){
113859       if( p->nLeavesTotal==p->nLeavesAlloc ){
113860         int nNew = p->nLeavesAlloc + 16;
113861         sqlite3_stmt **aNew = (sqlite3_stmt **)sqlite3_realloc(
113862             p->aLeavesStmt, nNew*sizeof(sqlite3_stmt *)
113863         );
113864         if( !aNew ){
113865           rc = SQLITE_NOMEM;
113866           goto finished;
113867         }
113868         p->nLeavesAlloc = nNew;
113869         p->aLeavesStmt = aNew;
113870       }
113871       rc = sqlite3_prepare_v2(p->db, p->zSelectLeaves, -1, &pReader->pStmt, 0);
113872       if( rc!=SQLITE_OK ){
113873         goto finished;
113874       }
113875       p->nLeavesTotal++;
113876     }else{
113877       pReader->pStmt = p->aLeavesStmt[--p->nLeavesStmt];
113878     }
113879
113880     /* Bind the start and end leaf blockids to the prepared SQL statement. */
113881     sqlite3_bind_int64(pReader->pStmt, 1, iStartLeaf);
113882     sqlite3_bind_int64(pReader->pStmt, 2, iEndLeaf);
113883   }
113884   rc = fts3SegReaderNext(pReader);
113885
113886  finished:
113887   if( rc==SQLITE_OK ){
113888     *ppReader = pReader;
113889   }else{
113890     sqlite3Fts3SegReaderFree(p, pReader);
113891   }
113892   return rc;
113893 }
113894
113895 /*
113896 ** This is a comparison function used as a qsort() callback when sorting
113897 ** an array of pending terms by term. This occurs as part of flushing
113898 ** the contents of the pending-terms hash table to the database.
113899 */
113900 static int fts3CompareElemByTerm(const void *lhs, const void *rhs){
113901   char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
113902   char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
113903   int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
113904   int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
113905
113906   int n = (n1<n2 ? n1 : n2);
113907   int c = memcmp(z1, z2, n);
113908   if( c==0 ){
113909     c = n1 - n2;
113910   }
113911   return c;
113912 }
113913
113914 /*
113915 ** This function is used to allocate an Fts3SegReader that iterates through
113916 ** a subset of the terms stored in the Fts3Table.pendingTerms array.
113917 */
113918 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
113919   Fts3Table *p,                   /* Virtual table handle */
113920   const char *zTerm,              /* Term to search for */
113921   int nTerm,                      /* Size of buffer zTerm */
113922   int isPrefix,                   /* True for a term-prefix query */
113923   Fts3SegReader **ppReader        /* OUT: SegReader for pending-terms */
113924 ){
113925   Fts3SegReader *pReader = 0;     /* Fts3SegReader object to return */
113926   Fts3HashElem **aElem = 0;       /* Array of term hash entries to scan */
113927   int nElem = 0;                  /* Size of array at aElem */
113928   int rc = SQLITE_OK;             /* Return Code */
113929
113930   if( isPrefix ){
113931     int nAlloc = 0;               /* Size of allocated array at aElem */
113932     Fts3HashElem *pE = 0;         /* Iterator variable */
113933
113934     for(pE=fts3HashFirst(&p->pendingTerms); pE; pE=fts3HashNext(pE)){
113935       char *zKey = (char *)fts3HashKey(pE);
113936       int nKey = fts3HashKeysize(pE);
113937       if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
113938         if( nElem==nAlloc ){
113939           Fts3HashElem **aElem2;
113940           nAlloc += 16;
113941           aElem2 = (Fts3HashElem **)sqlite3_realloc(
113942               aElem, nAlloc*sizeof(Fts3HashElem *)
113943           );
113944           if( !aElem2 ){
113945             rc = SQLITE_NOMEM;
113946             nElem = 0;
113947             break;
113948           }
113949           aElem = aElem2;
113950         }
113951         aElem[nElem++] = pE;
113952       }
113953     }
113954
113955     /* If more than one term matches the prefix, sort the Fts3HashElem
113956     ** objects in term order using qsort(). This uses the same comparison
113957     ** callback as is used when flushing terms to disk.
113958     */
113959     if( nElem>1 ){
113960       qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
113961     }
113962
113963   }else{
113964     Fts3HashElem *pE = fts3HashFindElem(&p->pendingTerms, zTerm, nTerm);
113965     if( pE ){
113966       aElem = &pE;
113967       nElem = 1;
113968     }
113969   }
113970
113971   if( nElem>0 ){
113972     int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
113973     pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
113974     if( !pReader ){
113975       rc = SQLITE_NOMEM;
113976     }else{
113977       memset(pReader, 0, nByte);
113978       pReader->iIdx = 0x7FFFFFFF;
113979       pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
113980       memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
113981       fts3SegReaderNext(pReader);
113982     }
113983   }
113984
113985   if( isPrefix ){
113986     sqlite3_free(aElem);
113987   }
113988   *ppReader = pReader;
113989   return rc;
113990 }
113991
113992
113993 /*
113994 ** The second argument to this function is expected to be a statement of
113995 ** the form:
113996 **
113997 **   SELECT 
113998 **     idx,                  -- col 0
113999 **     start_block,          -- col 1
114000 **     leaves_end_block,     -- col 2
114001 **     end_block,            -- col 3
114002 **     root                  -- col 4
114003 **   FROM %_segdir ...
114004 **
114005 ** This function allocates and initializes a Fts3SegReader structure to
114006 ** iterate through the terms stored in the segment identified by the
114007 ** current row that pStmt is pointing to. 
114008 **
114009 ** If successful, the Fts3SegReader is left pointing to the first term
114010 ** in the segment and SQLITE_OK is returned. Otherwise, an SQLite error
114011 ** code is returned.
114012 */
114013 static int fts3SegReaderNew(
114014   Fts3Table *p,                   /* Virtual table handle */
114015   sqlite3_stmt *pStmt,            /* See above */
114016   int iAge,                       /* Segment "age". */
114017   Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
114018 ){
114019   return sqlite3Fts3SegReaderNew(p, iAge, 
114020       sqlite3_column_int64(pStmt, 1),
114021       sqlite3_column_int64(pStmt, 2),
114022       sqlite3_column_int64(pStmt, 3),
114023       sqlite3_column_blob(pStmt, 4),
114024       sqlite3_column_bytes(pStmt, 4),
114025       ppReader
114026   );
114027 }
114028
114029 /*
114030 ** Compare the entries pointed to by two Fts3SegReader structures. 
114031 ** Comparison is as follows:
114032 **
114033 **   1) EOF is greater than not EOF.
114034 **
114035 **   2) The current terms (if any) are compared using memcmp(). If one
114036 **      term is a prefix of another, the longer term is considered the
114037 **      larger.
114038 **
114039 **   3) By segment age. An older segment is considered larger.
114040 */
114041 static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
114042   int rc;
114043   if( pLhs->aNode && pRhs->aNode ){
114044     int rc2 = pLhs->nTerm - pRhs->nTerm;
114045     if( rc2<0 ){
114046       rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
114047     }else{
114048       rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
114049     }
114050     if( rc==0 ){
114051       rc = rc2;
114052     }
114053   }else{
114054     rc = (pLhs->aNode==0) - (pRhs->aNode==0);
114055   }
114056   if( rc==0 ){
114057     rc = pRhs->iIdx - pLhs->iIdx;
114058   }
114059   assert( rc!=0 );
114060   return rc;
114061 }
114062
114063 /*
114064 ** A different comparison function for SegReader structures. In this
114065 ** version, it is assumed that each SegReader points to an entry in
114066 ** a doclist for identical terms. Comparison is made as follows:
114067 **
114068 **   1) EOF (end of doclist in this case) is greater than not EOF.
114069 **
114070 **   2) By current docid.
114071 **
114072 **   3) By segment age. An older segment is considered larger.
114073 */
114074 static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
114075   int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
114076   if( rc==0 ){
114077     if( pLhs->iDocid==pRhs->iDocid ){
114078       rc = pRhs->iIdx - pLhs->iIdx;
114079     }else{
114080       rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
114081     }
114082   }
114083   assert( pLhs->aNode && pRhs->aNode );
114084   return rc;
114085 }
114086
114087 /*
114088 ** Compare the term that the Fts3SegReader object passed as the first argument
114089 ** points to with the term specified by arguments zTerm and nTerm. 
114090 **
114091 ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
114092 ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
114093 ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
114094 */
114095 static int fts3SegReaderTermCmp(
114096   Fts3SegReader *pSeg,            /* Segment reader object */
114097   const char *zTerm,              /* Term to compare to */
114098   int nTerm                       /* Size of term zTerm in bytes */
114099 ){
114100   int res = 0;
114101   if( pSeg->aNode ){
114102     if( pSeg->nTerm>nTerm ){
114103       res = memcmp(pSeg->zTerm, zTerm, nTerm);
114104     }else{
114105       res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
114106     }
114107     if( res==0 ){
114108       res = pSeg->nTerm-nTerm;
114109     }
114110   }
114111   return res;
114112 }
114113
114114 /*
114115 ** Argument apSegment is an array of nSegment elements. It is known that
114116 ** the final (nSegment-nSuspect) members are already in sorted order
114117 ** (according to the comparison function provided). This function shuffles
114118 ** the array around until all entries are in sorted order.
114119 */
114120 static void fts3SegReaderSort(
114121   Fts3SegReader **apSegment,                     /* Array to sort entries of */
114122   int nSegment,                                  /* Size of apSegment array */
114123   int nSuspect,                                  /* Unsorted entry count */
114124   int (*xCmp)(Fts3SegReader *, Fts3SegReader *)  /* Comparison function */
114125 ){
114126   int i;                          /* Iterator variable */
114127
114128   assert( nSuspect<=nSegment );
114129
114130   if( nSuspect==nSegment ) nSuspect--;
114131   for(i=nSuspect-1; i>=0; i--){
114132     int j;
114133     for(j=i; j<(nSegment-1); j++){
114134       Fts3SegReader *pTmp;
114135       if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
114136       pTmp = apSegment[j+1];
114137       apSegment[j+1] = apSegment[j];
114138       apSegment[j] = pTmp;
114139     }
114140   }
114141
114142 #ifndef NDEBUG
114143   /* Check that the list really is sorted now. */
114144   for(i=0; i<(nSuspect-1); i++){
114145     assert( xCmp(apSegment[i], apSegment[i+1])<0 );
114146   }
114147 #endif
114148 }
114149
114150 /* 
114151 ** Insert a record into the %_segments table.
114152 */
114153 static int fts3WriteSegment(
114154   Fts3Table *p,                   /* Virtual table handle */
114155   sqlite3_int64 iBlock,           /* Block id for new block */
114156   char *z,                        /* Pointer to buffer containing block data */
114157   int n                           /* Size of buffer z in bytes */
114158 ){
114159   sqlite3_stmt *pStmt;
114160   int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
114161   if( rc==SQLITE_OK ){
114162     sqlite3_bind_int64(pStmt, 1, iBlock);
114163     sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
114164     sqlite3_step(pStmt);
114165     rc = sqlite3_reset(pStmt);
114166   }
114167   return rc;
114168 }
114169
114170 /* 
114171 ** Insert a record into the %_segdir table.
114172 */
114173 static int fts3WriteSegdir(
114174   Fts3Table *p,                   /* Virtual table handle */
114175   int iLevel,                     /* Value for "level" field */
114176   int iIdx,                       /* Value for "idx" field */
114177   sqlite3_int64 iStartBlock,      /* Value for "start_block" field */
114178   sqlite3_int64 iLeafEndBlock,    /* Value for "leaves_end_block" field */
114179   sqlite3_int64 iEndBlock,        /* Value for "end_block" field */
114180   char *zRoot,                    /* Blob value for "root" field */
114181   int nRoot                       /* Number of bytes in buffer zRoot */
114182 ){
114183   sqlite3_stmt *pStmt;
114184   int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
114185   if( rc==SQLITE_OK ){
114186     sqlite3_bind_int(pStmt, 1, iLevel);
114187     sqlite3_bind_int(pStmt, 2, iIdx);
114188     sqlite3_bind_int64(pStmt, 3, iStartBlock);
114189     sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
114190     sqlite3_bind_int64(pStmt, 5, iEndBlock);
114191     sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
114192     sqlite3_step(pStmt);
114193     rc = sqlite3_reset(pStmt);
114194   }
114195   return rc;
114196 }
114197
114198 /*
114199 ** Return the size of the common prefix (if any) shared by zPrev and
114200 ** zNext, in bytes. For example, 
114201 **
114202 **   fts3PrefixCompress("abc", 3, "abcdef", 6)   // returns 3
114203 **   fts3PrefixCompress("abX", 3, "abcdef", 6)   // returns 2
114204 **   fts3PrefixCompress("abX", 3, "Xbcdef", 6)   // returns 0
114205 */
114206 static int fts3PrefixCompress(
114207   const char *zPrev,              /* Buffer containing previous term */
114208   int nPrev,                      /* Size of buffer zPrev in bytes */
114209   const char *zNext,              /* Buffer containing next term */
114210   int nNext                       /* Size of buffer zNext in bytes */
114211 ){
114212   int n;
114213   UNUSED_PARAMETER(nNext);
114214   for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
114215   return n;
114216 }
114217
114218 /*
114219 ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
114220 ** (according to memcmp) than the previous term.
114221 */
114222 static int fts3NodeAddTerm(
114223   Fts3Table *p,               /* Virtual table handle */
114224   SegmentNode **ppTree,           /* IN/OUT: SegmentNode handle */ 
114225   int isCopyTerm,                 /* True if zTerm/nTerm is transient */
114226   const char *zTerm,              /* Pointer to buffer containing term */
114227   int nTerm                       /* Size of term in bytes */
114228 ){
114229   SegmentNode *pTree = *ppTree;
114230   int rc;
114231   SegmentNode *pNew;
114232
114233   /* First try to append the term to the current node. Return early if 
114234   ** this is possible.
114235   */
114236   if( pTree ){
114237     int nData = pTree->nData;     /* Current size of node in bytes */
114238     int nReq = nData;             /* Required space after adding zTerm */
114239     int nPrefix;                  /* Number of bytes of prefix compression */
114240     int nSuffix;                  /* Suffix length */
114241
114242     nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
114243     nSuffix = nTerm-nPrefix;
114244
114245     nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
114246     if( nReq<=p->nNodeSize || !pTree->zTerm ){
114247
114248       if( nReq>p->nNodeSize ){
114249         /* An unusual case: this is the first term to be added to the node
114250         ** and the static node buffer (p->nNodeSize bytes) is not large
114251         ** enough. Use a separately malloced buffer instead This wastes
114252         ** p->nNodeSize bytes, but since this scenario only comes about when
114253         ** the database contain two terms that share a prefix of almost 2KB, 
114254         ** this is not expected to be a serious problem. 
114255         */
114256         assert( pTree->aData==(char *)&pTree[1] );
114257         pTree->aData = (char *)sqlite3_malloc(nReq);
114258         if( !pTree->aData ){
114259           return SQLITE_NOMEM;
114260         }
114261       }
114262
114263       if( pTree->zTerm ){
114264         /* There is no prefix-length field for first term in a node */
114265         nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
114266       }
114267
114268       nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
114269       memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
114270       pTree->nData = nData + nSuffix;
114271       pTree->nEntry++;
114272
114273       if( isCopyTerm ){
114274         if( pTree->nMalloc<nTerm ){
114275           char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
114276           if( !zNew ){
114277             return SQLITE_NOMEM;
114278           }
114279           pTree->nMalloc = nTerm*2;
114280           pTree->zMalloc = zNew;
114281         }
114282         pTree->zTerm = pTree->zMalloc;
114283         memcpy(pTree->zTerm, zTerm, nTerm);
114284         pTree->nTerm = nTerm;
114285       }else{
114286         pTree->zTerm = (char *)zTerm;
114287         pTree->nTerm = nTerm;
114288       }
114289       return SQLITE_OK;
114290     }
114291   }
114292
114293   /* If control flows to here, it was not possible to append zTerm to the
114294   ** current node. Create a new node (a right-sibling of the current node).
114295   ** If this is the first node in the tree, the term is added to it.
114296   **
114297   ** Otherwise, the term is not added to the new node, it is left empty for
114298   ** now. Instead, the term is inserted into the parent of pTree. If pTree 
114299   ** has no parent, one is created here.
114300   */
114301   pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
114302   if( !pNew ){
114303     return SQLITE_NOMEM;
114304   }
114305   memset(pNew, 0, sizeof(SegmentNode));
114306   pNew->nData = 1 + FTS3_VARINT_MAX;
114307   pNew->aData = (char *)&pNew[1];
114308
114309   if( pTree ){
114310     SegmentNode *pParent = pTree->pParent;
114311     rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
114312     if( pTree->pParent==0 ){
114313       pTree->pParent = pParent;
114314     }
114315     pTree->pRight = pNew;
114316     pNew->pLeftmost = pTree->pLeftmost;
114317     pNew->pParent = pParent;
114318     pNew->zMalloc = pTree->zMalloc;
114319     pNew->nMalloc = pTree->nMalloc;
114320     pTree->zMalloc = 0;
114321   }else{
114322     pNew->pLeftmost = pNew;
114323     rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm); 
114324   }
114325
114326   *ppTree = pNew;
114327   return rc;
114328 }
114329
114330 /*
114331 ** Helper function for fts3NodeWrite().
114332 */
114333 static int fts3TreeFinishNode(
114334   SegmentNode *pTree, 
114335   int iHeight, 
114336   sqlite3_int64 iLeftChild
114337 ){
114338   int nStart;
114339   assert( iHeight>=1 && iHeight<128 );
114340   nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
114341   pTree->aData[nStart] = (char)iHeight;
114342   sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
114343   return nStart;
114344 }
114345
114346 /*
114347 ** Write the buffer for the segment node pTree and all of its peers to the
114348 ** database. Then call this function recursively to write the parent of 
114349 ** pTree and its peers to the database. 
114350 **
114351 ** Except, if pTree is a root node, do not write it to the database. Instead,
114352 ** set output variables *paRoot and *pnRoot to contain the root node.
114353 **
114354 ** If successful, SQLITE_OK is returned and output variable *piLast is
114355 ** set to the largest blockid written to the database (or zero if no
114356 ** blocks were written to the db). Otherwise, an SQLite error code is 
114357 ** returned.
114358 */
114359 static int fts3NodeWrite(
114360   Fts3Table *p,                   /* Virtual table handle */
114361   SegmentNode *pTree,             /* SegmentNode handle */
114362   int iHeight,                    /* Height of this node in tree */
114363   sqlite3_int64 iLeaf,            /* Block id of first leaf node */
114364   sqlite3_int64 iFree,            /* Block id of next free slot in %_segments */
114365   sqlite3_int64 *piLast,          /* OUT: Block id of last entry written */
114366   char **paRoot,                  /* OUT: Data for root node */
114367   int *pnRoot                     /* OUT: Size of root node in bytes */
114368 ){
114369   int rc = SQLITE_OK;
114370
114371   if( !pTree->pParent ){
114372     /* Root node of the tree. */
114373     int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
114374     *piLast = iFree-1;
114375     *pnRoot = pTree->nData - nStart;
114376     *paRoot = &pTree->aData[nStart];
114377   }else{
114378     SegmentNode *pIter;
114379     sqlite3_int64 iNextFree = iFree;
114380     sqlite3_int64 iNextLeaf = iLeaf;
114381     for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
114382       int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
114383       int nWrite = pIter->nData - nStart;
114384   
114385       rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
114386       iNextFree++;
114387       iNextLeaf += (pIter->nEntry+1);
114388     }
114389     if( rc==SQLITE_OK ){
114390       assert( iNextLeaf==iFree );
114391       rc = fts3NodeWrite(
114392           p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
114393       );
114394     }
114395   }
114396
114397   return rc;
114398 }
114399
114400 /*
114401 ** Free all memory allocations associated with the tree pTree.
114402 */
114403 static void fts3NodeFree(SegmentNode *pTree){
114404   if( pTree ){
114405     SegmentNode *p = pTree->pLeftmost;
114406     fts3NodeFree(p->pParent);
114407     while( p ){
114408       SegmentNode *pRight = p->pRight;
114409       if( p->aData!=(char *)&p[1] ){
114410         sqlite3_free(p->aData);
114411       }
114412       assert( pRight==0 || p->zMalloc==0 );
114413       sqlite3_free(p->zMalloc);
114414       sqlite3_free(p);
114415       p = pRight;
114416     }
114417   }
114418 }
114419
114420 /*
114421 ** Add a term to the segment being constructed by the SegmentWriter object
114422 ** *ppWriter. When adding the first term to a segment, *ppWriter should
114423 ** be passed NULL. This function will allocate a new SegmentWriter object
114424 ** and return it via the input/output variable *ppWriter in this case.
114425 **
114426 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
114427 */
114428 static int fts3SegWriterAdd(
114429   Fts3Table *p,                   /* Virtual table handle */
114430   SegmentWriter **ppWriter,       /* IN/OUT: SegmentWriter handle */ 
114431   int isCopyTerm,                 /* True if buffer zTerm must be copied */
114432   const char *zTerm,              /* Pointer to buffer containing term */
114433   int nTerm,                      /* Size of term in bytes */
114434   const char *aDoclist,           /* Pointer to buffer containing doclist */
114435   int nDoclist                    /* Size of doclist in bytes */
114436 ){
114437   int nPrefix;                    /* Size of term prefix in bytes */
114438   int nSuffix;                    /* Size of term suffix in bytes */
114439   int nReq;                       /* Number of bytes required on leaf page */
114440   int nData;
114441   SegmentWriter *pWriter = *ppWriter;
114442
114443   if( !pWriter ){
114444     int rc;
114445     sqlite3_stmt *pStmt;
114446
114447     /* Allocate the SegmentWriter structure */
114448     pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
114449     if( !pWriter ) return SQLITE_NOMEM;
114450     memset(pWriter, 0, sizeof(SegmentWriter));
114451     *ppWriter = pWriter;
114452
114453     /* Allocate a buffer in which to accumulate data */
114454     pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
114455     if( !pWriter->aData ) return SQLITE_NOMEM;
114456     pWriter->nSize = p->nNodeSize;
114457
114458     /* Find the next free blockid in the %_segments table */
114459     rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
114460     if( rc!=SQLITE_OK ) return rc;
114461     if( SQLITE_ROW==sqlite3_step(pStmt) ){
114462       pWriter->iFree = sqlite3_column_int64(pStmt, 0);
114463       pWriter->iFirst = pWriter->iFree;
114464     }
114465     rc = sqlite3_reset(pStmt);
114466     if( rc!=SQLITE_OK ) return rc;
114467   }
114468   nData = pWriter->nData;
114469
114470   nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
114471   nSuffix = nTerm-nPrefix;
114472
114473   /* Figure out how many bytes are required by this new entry */
114474   nReq = sqlite3Fts3VarintLen(nPrefix) +    /* varint containing prefix size */
114475     sqlite3Fts3VarintLen(nSuffix) +         /* varint containing suffix size */
114476     nSuffix +                               /* Term suffix */
114477     sqlite3Fts3VarintLen(nDoclist) +        /* Size of doclist */
114478     nDoclist;                               /* Doclist data */
114479
114480   if( nData>0 && nData+nReq>p->nNodeSize ){
114481     int rc;
114482
114483     /* The current leaf node is full. Write it out to the database. */
114484     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
114485     if( rc!=SQLITE_OK ) return rc;
114486
114487     /* Add the current term to the interior node tree. The term added to
114488     ** the interior tree must:
114489     **
114490     **   a) be greater than the largest term on the leaf node just written
114491     **      to the database (still available in pWriter->zTerm), and
114492     **
114493     **   b) be less than or equal to the term about to be added to the new
114494     **      leaf node (zTerm/nTerm).
114495     **
114496     ** In other words, it must be the prefix of zTerm 1 byte longer than
114497     ** the common prefix (if any) of zTerm and pWriter->zTerm.
114498     */
114499     assert( nPrefix<nTerm );
114500     rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
114501     if( rc!=SQLITE_OK ) return rc;
114502
114503     nData = 0;
114504     pWriter->nTerm = 0;
114505
114506     nPrefix = 0;
114507     nSuffix = nTerm;
114508     nReq = 1 +                              /* varint containing prefix size */
114509       sqlite3Fts3VarintLen(nTerm) +         /* varint containing suffix size */
114510       nTerm +                               /* Term suffix */
114511       sqlite3Fts3VarintLen(nDoclist) +      /* Size of doclist */
114512       nDoclist;                             /* Doclist data */
114513   }
114514
114515   /* If the buffer currently allocated is too small for this entry, realloc
114516   ** the buffer to make it large enough.
114517   */
114518   if( nReq>pWriter->nSize ){
114519     char *aNew = sqlite3_realloc(pWriter->aData, nReq);
114520     if( !aNew ) return SQLITE_NOMEM;
114521     pWriter->aData = aNew;
114522     pWriter->nSize = nReq;
114523   }
114524   assert( nData+nReq<=pWriter->nSize );
114525
114526   /* Append the prefix-compressed term and doclist to the buffer. */
114527   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
114528   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
114529   memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
114530   nData += nSuffix;
114531   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
114532   memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
114533   pWriter->nData = nData + nDoclist;
114534
114535   /* Save the current term so that it can be used to prefix-compress the next.
114536   ** If the isCopyTerm parameter is true, then the buffer pointed to by
114537   ** zTerm is transient, so take a copy of the term data. Otherwise, just
114538   ** store a copy of the pointer.
114539   */
114540   if( isCopyTerm ){
114541     if( nTerm>pWriter->nMalloc ){
114542       char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
114543       if( !zNew ){
114544         return SQLITE_NOMEM;
114545       }
114546       pWriter->nMalloc = nTerm*2;
114547       pWriter->zMalloc = zNew;
114548       pWriter->zTerm = zNew;
114549     }
114550     assert( pWriter->zTerm==pWriter->zMalloc );
114551     memcpy(pWriter->zTerm, zTerm, nTerm);
114552   }else{
114553     pWriter->zTerm = (char *)zTerm;
114554   }
114555   pWriter->nTerm = nTerm;
114556
114557   return SQLITE_OK;
114558 }
114559
114560 /*
114561 ** Flush all data associated with the SegmentWriter object pWriter to the
114562 ** database. This function must be called after all terms have been added
114563 ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
114564 ** returned. Otherwise, an SQLite error code.
114565 */
114566 static int fts3SegWriterFlush(
114567   Fts3Table *p,                   /* Virtual table handle */
114568   SegmentWriter *pWriter,         /* SegmentWriter to flush to the db */
114569   int iLevel,                     /* Value for 'level' column of %_segdir */
114570   int iIdx                        /* Value for 'idx' column of %_segdir */
114571 ){
114572   int rc;                         /* Return code */
114573   if( pWriter->pTree ){
114574     sqlite3_int64 iLast = 0;      /* Largest block id written to database */
114575     sqlite3_int64 iLastLeaf;      /* Largest leaf block id written to db */
114576     char *zRoot = NULL;           /* Pointer to buffer containing root node */
114577     int nRoot = 0;                /* Size of buffer zRoot */
114578
114579     iLastLeaf = pWriter->iFree;
114580     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
114581     if( rc==SQLITE_OK ){
114582       rc = fts3NodeWrite(p, pWriter->pTree, 1,
114583           pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
114584     }
114585     if( rc==SQLITE_OK ){
114586       rc = fts3WriteSegdir(
114587           p, iLevel, iIdx, pWriter->iFirst, iLastLeaf, iLast, zRoot, nRoot);
114588     }
114589   }else{
114590     /* The entire tree fits on the root node. Write it to the segdir table. */
114591     rc = fts3WriteSegdir(
114592         p, iLevel, iIdx, 0, 0, 0, pWriter->aData, pWriter->nData);
114593   }
114594   return rc;
114595 }
114596
114597 /*
114598 ** Release all memory held by the SegmentWriter object passed as the 
114599 ** first argument.
114600 */
114601 static void fts3SegWriterFree(SegmentWriter *pWriter){
114602   if( pWriter ){
114603     sqlite3_free(pWriter->aData);
114604     sqlite3_free(pWriter->zMalloc);
114605     fts3NodeFree(pWriter->pTree);
114606     sqlite3_free(pWriter);
114607   }
114608 }
114609
114610 /*
114611 ** The first value in the apVal[] array is assumed to contain an integer.
114612 ** This function tests if there exist any documents with docid values that
114613 ** are different from that integer. i.e. if deleting the document with docid
114614 ** apVal[0] would mean the FTS3 table were empty.
114615 **
114616 ** If successful, *pisEmpty is set to true if the table is empty except for
114617 ** document apVal[0], or false otherwise, and SQLITE_OK is returned. If an
114618 ** error occurs, an SQLite error code is returned.
114619 */
114620 static int fts3IsEmpty(Fts3Table *p, sqlite3_value **apVal, int *pisEmpty){
114621   sqlite3_stmt *pStmt;
114622   int rc;
114623   rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, apVal);
114624   if( rc==SQLITE_OK ){
114625     if( SQLITE_ROW==sqlite3_step(pStmt) ){
114626       *pisEmpty = sqlite3_column_int(pStmt, 0);
114627     }
114628     rc = sqlite3_reset(pStmt);
114629   }
114630   return rc;
114631 }
114632
114633 /*
114634 ** Set *pnSegment to the number of segments of level iLevel in the database.
114635 **
114636 ** Return SQLITE_OK if successful, or an SQLite error code if not.
114637 */
114638 static int fts3SegmentCount(Fts3Table *p, int iLevel, int *pnSegment){
114639   sqlite3_stmt *pStmt;
114640   int rc;
114641
114642   assert( iLevel>=0 );
114643   rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_COUNT, &pStmt, 0);
114644   if( rc!=SQLITE_OK ) return rc;
114645   sqlite3_bind_int(pStmt, 1, iLevel);
114646   if( SQLITE_ROW==sqlite3_step(pStmt) ){
114647     *pnSegment = sqlite3_column_int(pStmt, 0);
114648   }
114649   return sqlite3_reset(pStmt);
114650 }
114651
114652 /*
114653 ** Set *pnSegment to the total number of segments in the database. Set
114654 ** *pnMax to the largest segment level in the database (segment levels
114655 ** are stored in the 'level' column of the %_segdir table).
114656 **
114657 ** Return SQLITE_OK if successful, or an SQLite error code if not.
114658 */
114659 static int fts3SegmentCountMax(Fts3Table *p, int *pnSegment, int *pnMax){
114660   sqlite3_stmt *pStmt;
114661   int rc;
114662
114663   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_COUNT_MAX, &pStmt, 0);
114664   if( rc!=SQLITE_OK ) return rc;
114665   if( SQLITE_ROW==sqlite3_step(pStmt) ){
114666     *pnSegment = sqlite3_column_int(pStmt, 0);
114667     *pnMax = sqlite3_column_int(pStmt, 1);
114668   }
114669   return sqlite3_reset(pStmt);
114670 }
114671
114672 /*
114673 ** This function is used after merging multiple segments into a single large
114674 ** segment to delete the old, now redundant, segment b-trees. Specifically,
114675 ** it:
114676 ** 
114677 **   1) Deletes all %_segments entries for the segments associated with 
114678 **      each of the SegReader objects in the array passed as the third 
114679 **      argument, and
114680 **
114681 **   2) deletes all %_segdir entries with level iLevel, or all %_segdir
114682 **      entries regardless of level if (iLevel<0).
114683 **
114684 ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
114685 */
114686 static int fts3DeleteSegdir(
114687   Fts3Table *p,                   /* Virtual table handle */
114688   int iLevel,                     /* Level of %_segdir entries to delete */
114689   Fts3SegReader **apSegment,      /* Array of SegReader objects */
114690   int nReader                     /* Size of array apSegment */
114691 ){
114692   int rc;                         /* Return Code */
114693   int i;                          /* Iterator variable */
114694   sqlite3_stmt *pDelete;          /* SQL statement to delete rows */
114695
114696   rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
114697   for(i=0; rc==SQLITE_OK && i<nReader; i++){
114698     Fts3SegReader *pSegment = apSegment[i];
114699     if( pSegment->iStartBlock ){
114700       sqlite3_bind_int64(pDelete, 1, pSegment->iStartBlock);
114701       sqlite3_bind_int64(pDelete, 2, pSegment->iEndBlock);
114702       sqlite3_step(pDelete);
114703       rc = sqlite3_reset(pDelete);
114704     }
114705   }
114706   if( rc!=SQLITE_OK ){
114707     return rc;
114708   }
114709
114710   if( iLevel>=0 ){
114711     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_BY_LEVEL, &pDelete, 0);
114712     if( rc==SQLITE_OK ){
114713       sqlite3_bind_int(pDelete, 1, iLevel);
114714       sqlite3_step(pDelete);
114715       rc = sqlite3_reset(pDelete);
114716     }
114717   }else{
114718     fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
114719   }
114720
114721   return rc;
114722 }
114723
114724 /*
114725 ** When this function is called, buffer *ppList (size *pnList bytes) contains 
114726 ** a position list that may (or may not) feature multiple columns. This
114727 ** function adjusts the pointer *ppList and the length *pnList so that they
114728 ** identify the subset of the position list that corresponds to column iCol.
114729 **
114730 ** If there are no entries in the input position list for column iCol, then
114731 ** *pnList is set to zero before returning.
114732 */
114733 static void fts3ColumnFilter(
114734   int iCol,                       /* Column to filter on */
114735   char **ppList,                  /* IN/OUT: Pointer to position list */
114736   int *pnList                     /* IN/OUT: Size of buffer *ppList in bytes */
114737 ){
114738   char *pList = *ppList;
114739   int nList = *pnList;
114740   char *pEnd = &pList[nList];
114741   int iCurrent = 0;
114742   char *p = pList;
114743
114744   assert( iCol>=0 );
114745   while( 1 ){
114746     char c = 0;
114747     while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
114748   
114749     if( iCol==iCurrent ){
114750       nList = (int)(p - pList);
114751       break;
114752     }
114753
114754     nList -= (int)(p - pList);
114755     pList = p;
114756     if( nList==0 ){
114757       break;
114758     }
114759     p = &pList[1];
114760     p += sqlite3Fts3GetVarint32(p, &iCurrent);
114761   }
114762
114763   *ppList = pList;
114764   *pnList = nList;
114765 }
114766
114767 /*
114768 ** sqlite3Fts3SegReaderIterate() callback used when merging multiple 
114769 ** segments to create a single, larger segment.
114770 */
114771 static int fts3MergeCallback(
114772   Fts3Table *p,                   /* FTS3 Virtual table handle */
114773   void *pContext,                 /* Pointer to SegmentWriter* to write with */
114774   char *zTerm,                    /* Term to write to the db */
114775   int nTerm,                      /* Number of bytes in zTerm */
114776   char *aDoclist,                 /* Doclist associated with zTerm */
114777   int nDoclist                    /* Number of bytes in doclist */
114778 ){
114779   SegmentWriter **ppW = (SegmentWriter **)pContext;
114780   return fts3SegWriterAdd(p, ppW, 1, zTerm, nTerm, aDoclist, nDoclist);
114781 }
114782
114783 /*
114784 ** sqlite3Fts3SegReaderIterate() callback used when flushing the contents
114785 ** of the pending-terms hash table to the database.
114786 */
114787 static int fts3FlushCallback(
114788   Fts3Table *p,                   /* FTS3 Virtual table handle */
114789   void *pContext,                 /* Pointer to SegmentWriter* to write with */
114790   char *zTerm,                    /* Term to write to the db */
114791   int nTerm,                      /* Number of bytes in zTerm */
114792   char *aDoclist,                 /* Doclist associated with zTerm */
114793   int nDoclist                    /* Number of bytes in doclist */
114794 ){
114795   SegmentWriter **ppW = (SegmentWriter **)pContext;
114796   return fts3SegWriterAdd(p, ppW, 0, zTerm, nTerm, aDoclist, nDoclist);
114797 }
114798
114799 /*
114800 ** This function is used to iterate through a contiguous set of terms 
114801 ** stored in the full-text index. It merges data contained in one or 
114802 ** more segments to support this.
114803 **
114804 ** The second argument is passed an array of pointers to SegReader objects
114805 ** allocated with sqlite3Fts3SegReaderNew(). This function merges the range 
114806 ** of terms selected by each SegReader. If a single term is present in
114807 ** more than one segment, the associated doclists are merged. For each
114808 ** term and (possibly merged) doclist in the merged range, the callback
114809 ** function xFunc is invoked with its arguments set as follows.
114810 **
114811 **   arg 0: Copy of 'p' parameter passed to this function
114812 **   arg 1: Copy of 'pContext' parameter passed to this function
114813 **   arg 2: Pointer to buffer containing term
114814 **   arg 3: Size of arg 2 buffer in bytes
114815 **   arg 4: Pointer to buffer containing doclist
114816 **   arg 5: Size of arg 2 buffer in bytes
114817 **
114818 ** The 4th argument to this function is a pointer to a structure of type
114819 ** Fts3SegFilter, defined in fts3Int.h. The contents of this structure
114820 ** further restrict the range of terms that callbacks are made for and
114821 ** modify the behaviour of this function. See comments above structure
114822 ** definition for details.
114823 */
114824 SQLITE_PRIVATE int sqlite3Fts3SegReaderIterate(
114825   Fts3Table *p,                   /* Virtual table handle */
114826   Fts3SegReader **apSegment,      /* Array of Fts3SegReader objects */
114827   int nSegment,                   /* Size of apSegment array */
114828   Fts3SegFilter *pFilter,         /* Restrictions on range of iteration */
114829   int (*xFunc)(Fts3Table *, void *, char *, int, char *, int),  /* Callback */
114830   void *pContext                  /* Callback context (2nd argument) */
114831 ){
114832   int i;                          /* Iterator variable */
114833   char *aBuffer = 0;              /* Buffer to merge doclists in */
114834   int nAlloc = 0;                 /* Allocated size of aBuffer buffer */
114835   int rc = SQLITE_OK;             /* Return code */
114836
114837   int isIgnoreEmpty =  (pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
114838   int isRequirePos =   (pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
114839   int isColFilter =    (pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
114840   int isPrefix =       (pFilter->flags & FTS3_SEGMENT_PREFIX);
114841
114842   /* If there are zero segments, this function is a no-op. This scenario
114843   ** comes about only when reading from an empty database.
114844   */
114845   if( nSegment==0 ) goto finished;
114846
114847   /* If the Fts3SegFilter defines a specific term (or term prefix) to search 
114848   ** for, then advance each segment iterator until it points to a term of
114849   ** equal or greater value than the specified term. This prevents many
114850   ** unnecessary merge/sort operations for the case where single segment
114851   ** b-tree leaf nodes contain more than one term.
114852   */
114853   if( pFilter->zTerm ){
114854     int nTerm = pFilter->nTerm;
114855     const char *zTerm = pFilter->zTerm;
114856     for(i=0; i<nSegment; i++){
114857       Fts3SegReader *pSeg = apSegment[i];
114858       while( fts3SegReaderTermCmp(pSeg, zTerm, nTerm)<0 ){
114859         rc = fts3SegReaderNext(pSeg);
114860         if( rc!=SQLITE_OK ) goto finished; }
114861     }
114862   }
114863
114864   fts3SegReaderSort(apSegment, nSegment, nSegment, fts3SegReaderCmp);
114865   while( apSegment[0]->aNode ){
114866     int nTerm = apSegment[0]->nTerm;
114867     char *zTerm = apSegment[0]->zTerm;
114868     int nMerge = 1;
114869
114870     /* If this is a prefix-search, and if the term that apSegment[0] points
114871     ** to does not share a suffix with pFilter->zTerm/nTerm, then all 
114872     ** required callbacks have been made. In this case exit early.
114873     **
114874     ** Similarly, if this is a search for an exact match, and the first term
114875     ** of segment apSegment[0] is not a match, exit early.
114876     */
114877     if( pFilter->zTerm ){
114878       if( nTerm<pFilter->nTerm 
114879        || (!isPrefix && nTerm>pFilter->nTerm)
114880        || memcmp(zTerm, pFilter->zTerm, pFilter->nTerm) 
114881     ){
114882         goto finished;
114883       }
114884     }
114885
114886     while( nMerge<nSegment 
114887         && apSegment[nMerge]->aNode
114888         && apSegment[nMerge]->nTerm==nTerm 
114889         && 0==memcmp(zTerm, apSegment[nMerge]->zTerm, nTerm)
114890     ){
114891       nMerge++;
114892     }
114893
114894     assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
114895     if( nMerge==1 && !isIgnoreEmpty ){
114896       Fts3SegReader *p0 = apSegment[0];
114897       rc = xFunc(p, pContext, zTerm, nTerm, p0->aDoclist, p0->nDoclist);
114898       if( rc!=SQLITE_OK ) goto finished;
114899     }else{
114900       int nDoclist = 0;           /* Size of doclist */
114901       sqlite3_int64 iPrev = 0;    /* Previous docid stored in doclist */
114902
114903       /* The current term of the first nMerge entries in the array
114904       ** of Fts3SegReader objects is the same. The doclists must be merged
114905       ** and a single term added to the new segment.
114906       */
114907       for(i=0; i<nMerge; i++){
114908         fts3SegReaderFirstDocid(apSegment[i]);
114909       }
114910       fts3SegReaderSort(apSegment, nMerge, nMerge, fts3SegReaderDoclistCmp);
114911       while( apSegment[0]->pOffsetList ){
114912         int j;                    /* Number of segments that share a docid */
114913         char *pList;
114914         int nList;
114915         int nByte;
114916         sqlite3_int64 iDocid = apSegment[0]->iDocid;
114917         fts3SegReaderNextDocid(apSegment[0], &pList, &nList);
114918         j = 1;
114919         while( j<nMerge
114920             && apSegment[j]->pOffsetList
114921             && apSegment[j]->iDocid==iDocid
114922         ){
114923           fts3SegReaderNextDocid(apSegment[j], 0, 0);
114924           j++;
114925         }
114926
114927         if( isColFilter ){
114928           fts3ColumnFilter(pFilter->iCol, &pList, &nList);
114929         }
114930
114931         if( !isIgnoreEmpty || nList>0 ){
114932           nByte = sqlite3Fts3VarintLen(iDocid-iPrev) + (isRequirePos?nList+1:0);
114933           if( nDoclist+nByte>nAlloc ){
114934             char *aNew;
114935             nAlloc = nDoclist+nByte*2;
114936             aNew = sqlite3_realloc(aBuffer, nAlloc);
114937             if( !aNew ){
114938               rc = SQLITE_NOMEM;
114939               goto finished;
114940             }
114941             aBuffer = aNew;
114942           }
114943           nDoclist += sqlite3Fts3PutVarint(&aBuffer[nDoclist], iDocid-iPrev);
114944           iPrev = iDocid;
114945           if( isRequirePos ){
114946             memcpy(&aBuffer[nDoclist], pList, nList);
114947             nDoclist += nList;
114948             aBuffer[nDoclist++] = '\0';
114949           }
114950         }
114951
114952         fts3SegReaderSort(apSegment, nMerge, j, fts3SegReaderDoclistCmp);
114953       }
114954
114955       if( nDoclist>0 ){
114956         rc = xFunc(p, pContext, zTerm, nTerm, aBuffer, nDoclist);
114957         if( rc!=SQLITE_OK ) goto finished;
114958       }
114959     }
114960
114961     /* If there is a term specified to filter on, and this is not a prefix
114962     ** search, return now. The callback that corresponds to the required
114963     ** term (if such a term exists in the index) has already been made.
114964     */
114965     if( pFilter->zTerm && !isPrefix ){
114966       goto finished;
114967     }
114968
114969     for(i=0; i<nMerge; i++){
114970       rc = fts3SegReaderNext(apSegment[i]);
114971       if( rc!=SQLITE_OK ) goto finished;
114972     }
114973     fts3SegReaderSort(apSegment, nSegment, nMerge, fts3SegReaderCmp);
114974   }
114975
114976  finished:
114977   sqlite3_free(aBuffer);
114978   return rc;
114979 }
114980
114981 /*
114982 ** Merge all level iLevel segments in the database into a single 
114983 ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
114984 ** single segment with a level equal to the numerically largest level 
114985 ** currently present in the database.
114986 **
114987 ** If this function is called with iLevel<0, but there is only one
114988 ** segment in the database, SQLITE_DONE is returned immediately. 
114989 ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs, 
114990 ** an SQLite error code is returned.
114991 */
114992 static int fts3SegmentMerge(Fts3Table *p, int iLevel){
114993   int i;                          /* Iterator variable */
114994   int rc;                         /* Return code */
114995   int iIdx;                       /* Index of new segment */
114996   int iNewLevel;                  /* Level to create new segment at */
114997   sqlite3_stmt *pStmt = 0;
114998   SegmentWriter *pWriter = 0;
114999   int nSegment = 0;               /* Number of segments being merged */
115000   Fts3SegReader **apSegment = 0;  /* Array of Segment iterators */
115001   Fts3SegReader *pPending = 0;    /* Iterator for pending-terms */
115002   Fts3SegFilter filter;           /* Segment term filter condition */
115003
115004   if( iLevel<0 ){
115005     /* This call is to merge all segments in the database to a single
115006     ** segment. The level of the new segment is equal to the the numerically 
115007     ** greatest segment level currently present in the database. The index
115008     ** of the new segment is always 0.
115009     */
115010     iIdx = 0;
115011     rc = sqlite3Fts3SegReaderPending(p, 0, 0, 1, &pPending);
115012     if( rc!=SQLITE_OK ) goto finished;
115013     rc = fts3SegmentCountMax(p, &nSegment, &iNewLevel);
115014     if( rc!=SQLITE_OK ) goto finished;
115015     nSegment += (pPending!=0);
115016     if( nSegment<=1 ){
115017       return SQLITE_DONE;
115018     }
115019   }else{
115020     /* This call is to merge all segments at level iLevel. Find the next
115021     ** available segment index at level iLevel+1. The call to
115022     ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to 
115023     ** a single iLevel+2 segment if necessary.
115024     */
115025     iNewLevel = iLevel+1;
115026     rc = fts3AllocateSegdirIdx(p, iNewLevel, &iIdx);
115027     if( rc!=SQLITE_OK ) goto finished;
115028     rc = fts3SegmentCount(p, iLevel, &nSegment);
115029     if( rc!=SQLITE_OK ) goto finished;
115030   }
115031   assert( nSegment>0 );
115032   assert( iNewLevel>=0 );
115033
115034   /* Allocate space for an array of pointers to segment iterators. */
115035   apSegment = (Fts3SegReader**)sqlite3_malloc(sizeof(Fts3SegReader *)*nSegment);
115036   if( !apSegment ){
115037     rc = SQLITE_NOMEM;
115038     goto finished;
115039   }
115040   memset(apSegment, 0, sizeof(Fts3SegReader *)*nSegment);
115041
115042   /* Allocate a Fts3SegReader structure for each segment being merged. A 
115043   ** Fts3SegReader stores the state data required to iterate through all 
115044   ** entries on all leaves of a single segment. 
115045   */
115046   assert( SQL_SELECT_LEVEL+1==SQL_SELECT_ALL_LEVEL);
115047   rc = fts3SqlStmt(p, SQL_SELECT_LEVEL+(iLevel<0), &pStmt, 0);
115048   if( rc!=SQLITE_OK ) goto finished;
115049   sqlite3_bind_int(pStmt, 1, iLevel);
115050   for(i=0; SQLITE_ROW==(sqlite3_step(pStmt)); i++){
115051     rc = fts3SegReaderNew(p, pStmt, i, &apSegment[i]);
115052     if( rc!=SQLITE_OK ){
115053       goto finished;
115054     }
115055   }
115056   rc = sqlite3_reset(pStmt);
115057   if( pPending ){
115058     apSegment[i] = pPending;
115059     pPending = 0;
115060   }
115061   pStmt = 0;
115062   if( rc!=SQLITE_OK ) goto finished;
115063
115064   memset(&filter, 0, sizeof(Fts3SegFilter));
115065   filter.flags = FTS3_SEGMENT_REQUIRE_POS;
115066   filter.flags |= (iLevel<0 ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
115067   rc = sqlite3Fts3SegReaderIterate(p, apSegment, nSegment,
115068       &filter, fts3MergeCallback, (void *)&pWriter
115069   );
115070   if( rc!=SQLITE_OK ) goto finished;
115071
115072   rc = fts3DeleteSegdir(p, iLevel, apSegment, nSegment);
115073   if( rc==SQLITE_OK ){
115074     rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
115075   }
115076
115077  finished:
115078   fts3SegWriterFree(pWriter);
115079   if( apSegment ){
115080     for(i=0; i<nSegment; i++){
115081       sqlite3Fts3SegReaderFree(p, apSegment[i]);
115082     }
115083     sqlite3_free(apSegment);
115084   }
115085   sqlite3Fts3SegReaderFree(p, pPending);
115086   sqlite3_reset(pStmt);
115087   return rc;
115088 }
115089
115090
115091 /* 
115092 ** Flush the contents of pendingTerms to a level 0 segment.
115093 */
115094 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
115095   int rc;                         /* Return Code */
115096   int idx;                        /* Index of new segment created */
115097   SegmentWriter *pWriter = 0;     /* Used to write the segment */
115098   Fts3SegReader *pReader = 0;     /* Used to iterate through the hash table */
115099
115100   /* Allocate a SegReader object to iterate through the contents of the
115101   ** pending-terms table. If an error occurs, or if there are no terms
115102   ** in the pending-terms table, return immediately.
115103   */
115104   rc = sqlite3Fts3SegReaderPending(p, 0, 0, 1, &pReader);
115105   if( rc!=SQLITE_OK || pReader==0 ){
115106     return rc;
115107   }
115108
115109   /* Determine the next index at level 0. If level 0 is already full, this
115110   ** call may merge all existing level 0 segments into a single level 1
115111   ** segment.
115112   */
115113   rc = fts3AllocateSegdirIdx(p, 0, &idx);
115114
115115   /* If no errors have occured, iterate through the contents of the 
115116   ** pending-terms hash table using the Fts3SegReader iterator. The callback
115117   ** writes each term (along with its doclist) to the database via the
115118   ** SegmentWriter handle pWriter.
115119   */
115120   if( rc==SQLITE_OK ){
115121     void *c = (void *)&pWriter;   /* SegReaderIterate() callback context */
115122     Fts3SegFilter f;              /* SegReaderIterate() parameters */
115123
115124     memset(&f, 0, sizeof(Fts3SegFilter));
115125     f.flags = FTS3_SEGMENT_REQUIRE_POS;
115126     rc = sqlite3Fts3SegReaderIterate(p, &pReader, 1, &f, fts3FlushCallback, c);
115127   }
115128   assert( pWriter || rc!=SQLITE_OK );
115129
115130   /* If no errors have occured, flush the SegmentWriter object to the
115131   ** database. Then delete the SegmentWriter and Fts3SegReader objects
115132   ** allocated by this function.
115133   */
115134   if( rc==SQLITE_OK ){
115135     rc = fts3SegWriterFlush(p, pWriter, 0, idx);
115136   }
115137   fts3SegWriterFree(pWriter);
115138   sqlite3Fts3SegReaderFree(p, pReader);
115139
115140   if( rc==SQLITE_OK ){
115141     sqlite3Fts3PendingTermsClear(p);
115142   }
115143   return rc;
115144 }
115145
115146 /*
115147 ** Encode N integers as varints into a blob.
115148 */
115149 static void fts3EncodeIntArray(
115150   int N,             /* The number of integers to encode */
115151   u32 *a,            /* The integer values */
115152   char *zBuf,        /* Write the BLOB here */
115153   int *pNBuf         /* Write number of bytes if zBuf[] used here */
115154 ){
115155   int i, j;
115156   for(i=j=0; i<N; i++){
115157     j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
115158   }
115159   *pNBuf = j;
115160 }
115161
115162 /*
115163 ** Decode a blob of varints into N integers
115164 */
115165 static void fts3DecodeIntArray(
115166   int N,             /* The number of integers to decode */
115167   u32 *a,            /* Write the integer values */
115168   const char *zBuf,  /* The BLOB containing the varints */
115169   int nBuf           /* size of the BLOB */
115170 ){
115171   int i, j;
115172   UNUSED_PARAMETER(nBuf);
115173   for(i=j=0; i<N; i++){
115174     sqlite3_int64 x;
115175     j += sqlite3Fts3GetVarint(&zBuf[j], &x);
115176     assert(j<=nBuf);
115177     a[i] = (u32)(x & 0xffffffff);
115178   }
115179 }
115180
115181 /*
115182 ** Fill in the document size auxiliary information for the matchinfo
115183 ** structure.  The auxiliary information is:
115184 **
115185 **    N     Total number of documents in the full-text index
115186 **    a0    Average length of column 0 over the whole index
115187 **    n0    Length of column 0 on the matching row
115188 **    ...
115189 **    aM    Average length of column M over the whole index
115190 **    nM    Length of column M on the matching row
115191 **
115192 ** The fts3MatchinfoDocsizeLocal() routine fills in the nX values.
115193 ** The fts3MatchinfoDocsizeGlobal() routine fills in N and the aX values.
115194 */
115195 SQLITE_PRIVATE int sqlite3Fts3MatchinfoDocsizeLocal(Fts3Cursor *pCur, u32 *a){
115196   const char *pBlob;       /* The BLOB holding %_docsize info */
115197   int nBlob;               /* Size of the BLOB */
115198   sqlite3_stmt *pStmt;     /* Statement for reading and writing */
115199   int i, j;                /* Loop counters */
115200   sqlite3_int64 x;         /* Varint value */
115201   int rc;                  /* Result code from subfunctions */
115202   Fts3Table *p;            /* The FTS table */
115203
115204   p = (Fts3Table*)pCur->base.pVtab;
115205   rc = fts3SqlStmt(p, SQL_SELECT_DOCSIZE, &pStmt, 0);
115206   if( rc ){
115207     return rc;
115208   }
115209   sqlite3_bind_int64(pStmt, 1, pCur->iPrevId);
115210   if( sqlite3_step(pStmt)==SQLITE_ROW ){
115211     nBlob = sqlite3_column_bytes(pStmt, 0);
115212     pBlob = (const char*)sqlite3_column_blob(pStmt, 0);
115213     for(i=j=0; i<p->nColumn && j<nBlob; i++){
115214       j = sqlite3Fts3GetVarint(&pBlob[j], &x);
115215       a[2+i*2] = (u32)(x & 0xffffffff);
115216     }
115217   }
115218   sqlite3_reset(pStmt);
115219   return SQLITE_OK; 
115220 }
115221 SQLITE_PRIVATE int sqlite3Fts3MatchinfoDocsizeGlobal(Fts3Cursor *pCur, u32 *a){
115222   const char *pBlob;       /* The BLOB holding %_stat info */
115223   int nBlob;               /* Size of the BLOB */
115224   sqlite3_stmt *pStmt;     /* Statement for reading and writing */
115225   int i, j;                /* Loop counters */
115226   sqlite3_int64 x;         /* Varint value */
115227   int nDoc;                /* Number of documents */
115228   int rc;                  /* Result code from subfunctions */
115229   Fts3Table *p;            /* The FTS table */
115230
115231   p = (Fts3Table*)pCur->base.pVtab;
115232   rc = fts3SqlStmt(p, SQL_SELECT_DOCTOTAL, &pStmt, 0);
115233   if( rc ){
115234     return rc;
115235   }
115236   if( sqlite3_step(pStmt)==SQLITE_ROW ){
115237     nBlob = sqlite3_column_bytes(pStmt, 0);
115238     pBlob = (const char*)sqlite3_column_blob(pStmt, 0);
115239     j = sqlite3Fts3GetVarint(pBlob, &x);
115240     a[0] = nDoc = (u32)(x & 0xffffffff);
115241     for(i=0; i<p->nColumn && j<nBlob; i++){
115242       j = sqlite3Fts3GetVarint(&pBlob[j], &x);
115243       a[1+i*2] = ((u32)(x & 0xffffffff) + nDoc/2)/nDoc;
115244     }
115245   }
115246   sqlite3_reset(pStmt);
115247   return SQLITE_OK; 
115248 }
115249
115250 /*
115251 ** Insert the sizes (in tokens) for each column of the document
115252 ** with docid equal to p->iPrevDocid.  The sizes are encoded as
115253 ** a blob of varints.
115254 */
115255 static void fts3InsertDocsize(
115256   int *pRC,         /* Result code */
115257   Fts3Table *p,     /* Table into which to insert */
115258   u32 *aSz          /* Sizes of each column */
115259 ){
115260   char *pBlob;             /* The BLOB encoding of the document size */
115261   int nBlob;               /* Number of bytes in the BLOB */
115262   sqlite3_stmt *pStmt;     /* Statement used to insert the encoding */
115263   int rc;                  /* Result code from subfunctions */
115264
115265   if( *pRC ) return;
115266   pBlob = sqlite3_malloc( 10*p->nColumn );
115267   if( pBlob==0 ){
115268     *pRC = SQLITE_NOMEM;
115269     return;
115270   }
115271   fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
115272   rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
115273   if( rc ){
115274     sqlite3_free(pBlob);
115275     *pRC = rc;
115276     return;
115277   }
115278   sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
115279   sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
115280   sqlite3_step(pStmt);
115281   *pRC = sqlite3_reset(pStmt);
115282 }
115283
115284 /*
115285 ** Update the 0 record of the %_stat table so that it holds a blob
115286 ** which contains the document count followed by the cumulative
115287 ** document sizes for all columns.
115288 */
115289 static void fts3UpdateDocTotals(
115290   int *pRC,       /* The result code */
115291   Fts3Table *p,   /* Table being updated */
115292   u32 *aSzIns,    /* Size increases */
115293   u32 *aSzDel,    /* Size decreases */
115294   int nChng       /* Change in the number of documents */
115295 ){
115296   char *pBlob;             /* Storage for BLOB written into %_stat */
115297   int nBlob;               /* Size of BLOB written into %_stat */
115298   u32 *a;                  /* Array of integers that becomes the BLOB */
115299   sqlite3_stmt *pStmt;     /* Statement for reading and writing */
115300   int i;                   /* Loop counter */
115301   int rc;                  /* Result code from subfunctions */
115302
115303   if( *pRC ) return;
115304   a = sqlite3_malloc( (sizeof(u32)+10)*(p->nColumn+1) );
115305   if( a==0 ){
115306     *pRC = SQLITE_NOMEM;
115307     return;
115308   }
115309   pBlob = (char*)&a[p->nColumn+1];
115310   rc = fts3SqlStmt(p, SQL_SELECT_DOCTOTAL, &pStmt, 0);
115311   if( rc ){
115312     sqlite3_free(a);
115313     *pRC = rc;
115314     return;
115315   }
115316   if( sqlite3_step(pStmt)==SQLITE_ROW ){
115317     fts3DecodeIntArray(p->nColumn+1, a,
115318          sqlite3_column_blob(pStmt, 0),
115319          sqlite3_column_bytes(pStmt, 0));
115320   }else{
115321     memset(a, 0, sizeof(u32)*(p->nColumn+1) );
115322   }
115323   sqlite3_reset(pStmt);
115324   if( nChng<0 && a[0]<(u32)(-nChng) ){
115325     a[0] = 0;
115326   }else{
115327     a[0] += nChng;
115328   }
115329   for(i=0; i<p->nColumn; i++){
115330     u32 x = a[i+1];
115331     if( x+aSzIns[i] < aSzDel[i] ){
115332       x = 0;
115333     }else{
115334       x = x + aSzIns[i] - aSzDel[i];
115335     }
115336     a[i+1] = x;
115337   }
115338   fts3EncodeIntArray(p->nColumn+1, a, pBlob, &nBlob);
115339   rc = fts3SqlStmt(p, SQL_REPLACE_DOCTOTAL, &pStmt, 0);
115340   if( rc ){
115341     sqlite3_free(a);
115342     *pRC = rc;
115343     return;
115344   }
115345   sqlite3_bind_blob(pStmt, 1, pBlob, nBlob, SQLITE_STATIC);
115346   sqlite3_step(pStmt);
115347   *pRC = sqlite3_reset(pStmt);
115348   sqlite3_free(a);
115349 }
115350
115351 /*
115352 ** Handle a 'special' INSERT of the form:
115353 **
115354 **   "INSERT INTO tbl(tbl) VALUES(<expr>)"
115355 **
115356 ** Argument pVal contains the result of <expr>. Currently the only 
115357 ** meaningful value to insert is the text 'optimize'.
115358 */
115359 static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
115360   int rc;                         /* Return Code */
115361   const char *zVal = (const char *)sqlite3_value_text(pVal);
115362   int nVal = sqlite3_value_bytes(pVal);
115363
115364   if( !zVal ){
115365     return SQLITE_NOMEM;
115366   }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
115367     rc = fts3SegmentMerge(p, -1);
115368     if( rc==SQLITE_DONE ){
115369       rc = SQLITE_OK;
115370     }else{
115371       sqlite3Fts3PendingTermsClear(p);
115372     }
115373 #ifdef SQLITE_TEST
115374   }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
115375     p->nNodeSize = atoi(&zVal[9]);
115376     rc = SQLITE_OK;
115377   }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
115378     p->nMaxPendingData = atoi(&zVal[11]);
115379     rc = SQLITE_OK;
115380 #endif
115381   }else{
115382     rc = SQLITE_ERROR;
115383   }
115384
115385   return rc;
115386 }
115387
115388 /*
115389 ** This function does the work for the xUpdate method of FTS3 virtual
115390 ** tables.
115391 */
115392 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
115393   sqlite3_vtab *pVtab,            /* FTS3 vtab object */
115394   int nArg,                       /* Size of argument array */
115395   sqlite3_value **apVal,          /* Array of arguments */
115396   sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
115397 ){
115398   Fts3Table *p = (Fts3Table *)pVtab;
115399   int rc = SQLITE_OK;             /* Return Code */
115400   int isRemove = 0;               /* True for an UPDATE or DELETE */
115401   sqlite3_int64 iRemove = 0;      /* Rowid removed by UPDATE or DELETE */
115402   u32 *aSzIns;                    /* Sizes of inserted documents */
115403   u32 *aSzDel;                    /* Sizes of deleted documents */
115404   int nChng = 0;                  /* Net change in number of documents */
115405
115406
115407   /* Allocate space to hold the change in document sizes */
115408   aSzIns = sqlite3_malloc( sizeof(aSzIns[0])*p->nColumn*2 );
115409   if( aSzIns==0 ) return SQLITE_NOMEM;
115410   aSzDel = &aSzIns[p->nColumn];
115411   memset(aSzIns, 0, sizeof(aSzIns[0])*p->nColumn*2);
115412
115413   /* If this is a DELETE or UPDATE operation, remove the old record. */
115414   if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
115415     int isEmpty;
115416     rc = fts3IsEmpty(p, apVal, &isEmpty);
115417     if( rc==SQLITE_OK ){
115418       if( isEmpty ){
115419         /* Deleting this row means the whole table is empty. In this case
115420         ** delete the contents of all three tables and throw away any
115421         ** data in the pendingTerms hash table.
115422         */
115423         rc = fts3DeleteAll(p);
115424       }else{
115425         isRemove = 1;
115426         iRemove = sqlite3_value_int64(apVal[0]);
115427         rc = fts3PendingTermsDocid(p, iRemove);
115428         fts3DeleteTerms(&rc, p, apVal, aSzDel);
115429         fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, apVal);
115430         if( p->bHasDocsize ){
115431           fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, apVal);
115432           nChng--;
115433         }
115434       }
115435     }
115436   }else if( sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL ){
115437     sqlite3_free(aSzIns);
115438     return fts3SpecialInsert(p, apVal[p->nColumn+2]);
115439   }
115440   
115441   /* If this is an INSERT or UPDATE operation, insert the new record. */
115442   if( nArg>1 && rc==SQLITE_OK ){
115443     rc = fts3InsertData(p, apVal, pRowid);
115444     if( rc==SQLITE_OK && (!isRemove || *pRowid!=iRemove) ){
115445       rc = fts3PendingTermsDocid(p, *pRowid);
115446     }
115447     if( rc==SQLITE_OK ){
115448       rc = fts3InsertTerms(p, apVal, aSzIns);
115449     }
115450     if( p->bHasDocsize ){
115451       nChng++;
115452       fts3InsertDocsize(&rc, p, aSzIns);
115453     }
115454   }
115455
115456   if( p->bHasDocsize ){
115457     fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
115458   }
115459
115460   sqlite3_free(aSzIns);
115461   return rc;
115462 }
115463
115464 /* 
115465 ** Flush any data in the pending-terms hash table to disk. If successful,
115466 ** merge all segments in the database (including the new segment, if 
115467 ** there was any data to flush) into a single segment. 
115468 */
115469 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
115470   int rc;
115471   rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
115472   if( rc==SQLITE_OK ){
115473     rc = fts3SegmentMerge(p, -1);
115474     if( rc==SQLITE_OK ){
115475       rc = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
115476       if( rc==SQLITE_OK ){
115477         sqlite3Fts3PendingTermsClear(p);
115478       }
115479     }else{
115480       sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
115481       sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
115482     }
115483   }
115484   return rc;
115485 }
115486
115487 #endif
115488
115489 /************** End of fts3_write.c ******************************************/
115490 /************** Begin file fts3_snippet.c ************************************/
115491 /*
115492 ** 2009 Oct 23
115493 **
115494 ** The author disclaims copyright to this source code.  In place of
115495 ** a legal notice, here is a blessing:
115496 **
115497 **    May you do good and not evil.
115498 **    May you find forgiveness for yourself and forgive others.
115499 **    May you share freely, never taking more than you give.
115500 **
115501 ******************************************************************************
115502 */
115503
115504 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
115505
115506
115507
115508 /*
115509 ** Used as an fts3ExprIterate() context when loading phrase doclists to
115510 ** Fts3Expr.aDoclist[]/nDoclist.
115511 */
115512 typedef struct LoadDoclistCtx LoadDoclistCtx;
115513 struct LoadDoclistCtx {
115514   Fts3Table *pTab;                /* FTS3 Table */
115515   int nPhrase;                    /* Number of phrases seen so far */
115516   int nToken;                     /* Number of tokens seen so far */
115517 };
115518
115519 /*
115520 ** The following types are used as part of the implementation of the 
115521 ** fts3BestSnippet() routine.
115522 */
115523 typedef struct SnippetIter SnippetIter;
115524 typedef struct SnippetPhrase SnippetPhrase;
115525 typedef struct SnippetFragment SnippetFragment;
115526
115527 struct SnippetIter {
115528   Fts3Cursor *pCsr;               /* Cursor snippet is being generated from */
115529   int iCol;                       /* Extract snippet from this column */
115530   int nSnippet;                   /* Requested snippet length (in tokens) */
115531   int nPhrase;                    /* Number of phrases in query */
115532   SnippetPhrase *aPhrase;         /* Array of size nPhrase */
115533   int iCurrent;                   /* First token of current snippet */
115534 };
115535
115536 struct SnippetPhrase {
115537   int nToken;                     /* Number of tokens in phrase */
115538   char *pList;                    /* Pointer to start of phrase position list */
115539   int iHead;                      /* Next value in position list */
115540   char *pHead;                    /* Position list data following iHead */
115541   int iTail;                      /* Next value in trailing position list */
115542   char *pTail;                    /* Position list data following iTail */
115543 };
115544
115545 struct SnippetFragment {
115546   int iCol;                       /* Column snippet is extracted from */
115547   int iPos;                       /* Index of first token in snippet */
115548   u64 covered;                    /* Mask of query phrases covered */
115549   u64 hlmask;                     /* Mask of snippet terms to highlight */
115550 };
115551
115552 /*
115553 ** This type is used as an fts3ExprIterate() context object while 
115554 ** accumulating the data returned by the matchinfo() function.
115555 */
115556 typedef struct MatchInfo MatchInfo;
115557 struct MatchInfo {
115558   Fts3Cursor *pCursor;            /* FTS3 Cursor */
115559   int nCol;                       /* Number of columns in table */
115560   u32 *aMatchinfo;                /* Pre-allocated buffer */
115561 };
115562
115563
115564
115565 /*
115566 ** The snippet() and offsets() functions both return text values. An instance
115567 ** of the following structure is used to accumulate those values while the
115568 ** functions are running. See fts3StringAppend() for details.
115569 */
115570 typedef struct StrBuffer StrBuffer;
115571 struct StrBuffer {
115572   char *z;                        /* Pointer to buffer containing string */
115573   int n;                          /* Length of z in bytes (excl. nul-term) */
115574   int nAlloc;                     /* Allocated size of buffer z in bytes */
115575 };
115576
115577
115578 /*
115579 ** This function is used to help iterate through a position-list. A position
115580 ** list is a list of unique integers, sorted from smallest to largest. Each
115581 ** element of the list is represented by an FTS3 varint that takes the value
115582 ** of the difference between the current element and the previous one plus
115583 ** two. For example, to store the position-list:
115584 **
115585 **     4 9 113
115586 **
115587 ** the three varints:
115588 **
115589 **     6 7 106
115590 **
115591 ** are encoded.
115592 **
115593 ** When this function is called, *pp points to the start of an element of
115594 ** the list. *piPos contains the value of the previous entry in the list.
115595 ** After it returns, *piPos contains the value of the next element of the
115596 ** list and *pp is advanced to the following varint.
115597 */
115598 static void fts3GetDeltaPosition(char **pp, int *piPos){
115599   int iVal;
115600   *pp += sqlite3Fts3GetVarint32(*pp, &iVal);
115601   *piPos += (iVal-2);
115602 }
115603
115604 /*
115605 ** Helper function for fts3ExprIterate() (see below).
115606 */
115607 static int fts3ExprIterate2(
115608   Fts3Expr *pExpr,                /* Expression to iterate phrases of */
115609   int *piPhrase,                  /* Pointer to phrase counter */
115610   int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
115611   void *pCtx                      /* Second argument to pass to callback */
115612 ){
115613   int rc;                         /* Return code */
115614   int eType = pExpr->eType;       /* Type of expression node pExpr */
115615
115616   if( eType!=FTSQUERY_PHRASE ){
115617     assert( pExpr->pLeft && pExpr->pRight );
115618     rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
115619     if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
115620       rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
115621     }
115622   }else{
115623     rc = x(pExpr, *piPhrase, pCtx);
115624     (*piPhrase)++;
115625   }
115626   return rc;
115627 }
115628
115629 /*
115630 ** Iterate through all phrase nodes in an FTS3 query, except those that
115631 ** are part of a sub-tree that is the right-hand-side of a NOT operator.
115632 ** For each phrase node found, the supplied callback function is invoked.
115633 **
115634 ** If the callback function returns anything other than SQLITE_OK, 
115635 ** the iteration is abandoned and the error code returned immediately.
115636 ** Otherwise, SQLITE_OK is returned after a callback has been made for
115637 ** all eligible phrase nodes.
115638 */
115639 static int fts3ExprIterate(
115640   Fts3Expr *pExpr,                /* Expression to iterate phrases of */
115641   int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
115642   void *pCtx                      /* Second argument to pass to callback */
115643 ){
115644   int iPhrase = 0;                /* Variable used as the phrase counter */
115645   return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
115646 }
115647
115648 /*
115649 ** The argument to this function is always a phrase node. Its doclist 
115650 ** (Fts3Expr.aDoclist[]) and the doclists associated with all phrase nodes
115651 ** to the left of this one in the query tree have already been loaded.
115652 **
115653 ** If this phrase node is part of a series of phrase nodes joined by 
115654 ** NEAR operators (and is not the left-most of said series), then elements are
115655 ** removed from the phrases doclist consistent with the NEAR restriction. If
115656 ** required, elements may be removed from the doclists of phrases to the
115657 ** left of this one that are part of the same series of NEAR operator 
115658 ** connected phrases.
115659 **
115660 ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
115661 */
115662 static int fts3ExprNearTrim(Fts3Expr *pExpr){
115663   int rc = SQLITE_OK;
115664   Fts3Expr *pParent = pExpr->pParent;
115665
115666   assert( pExpr->eType==FTSQUERY_PHRASE );
115667   while( rc==SQLITE_OK
115668    && pParent 
115669    && pParent->eType==FTSQUERY_NEAR 
115670    && pParent->pRight==pExpr 
115671   ){
115672     /* This expression (pExpr) is the right-hand-side of a NEAR operator. 
115673     ** Find the expression to the left of the same operator.
115674     */
115675     int nNear = pParent->nNear;
115676     Fts3Expr *pLeft = pParent->pLeft;
115677
115678     if( pLeft->eType!=FTSQUERY_PHRASE ){
115679       assert( pLeft->eType==FTSQUERY_NEAR );
115680       assert( pLeft->pRight->eType==FTSQUERY_PHRASE );
115681       pLeft = pLeft->pRight;
115682     }
115683
115684     rc = sqlite3Fts3ExprNearTrim(pLeft, pExpr, nNear);
115685
115686     pExpr = pLeft;
115687     pParent = pExpr->pParent;
115688   }
115689
115690   return rc;
115691 }
115692
115693 /*
115694 ** This is an fts3ExprIterate() callback used while loading the doclists
115695 ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
115696 ** fts3ExprLoadDoclists().
115697 */
115698 static int fts3ExprLoadDoclistsCb1(Fts3Expr *pExpr, int iPhrase, void *ctx){
115699   int rc = SQLITE_OK;
115700   LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
115701
115702   UNUSED_PARAMETER(iPhrase);
115703
115704   p->nPhrase++;
115705   p->nToken += pExpr->pPhrase->nToken;
115706
115707   if( pExpr->isLoaded==0 ){
115708     rc = sqlite3Fts3ExprLoadDoclist(p->pTab, pExpr);
115709     pExpr->isLoaded = 1;
115710     if( rc==SQLITE_OK ){
115711       rc = fts3ExprNearTrim(pExpr);
115712     }
115713   }
115714
115715   return rc;
115716 }
115717
115718 /*
115719 ** This is an fts3ExprIterate() callback used while loading the doclists
115720 ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
115721 ** fts3ExprLoadDoclists().
115722 */
115723 static int fts3ExprLoadDoclistsCb2(Fts3Expr *pExpr, int iPhrase, void *ctx){
115724   UNUSED_PARAMETER(iPhrase);
115725   UNUSED_PARAMETER(ctx);
115726   if( pExpr->aDoclist ){
115727     pExpr->pCurrent = pExpr->aDoclist;
115728     pExpr->iCurrent = 0;
115729     pExpr->pCurrent += sqlite3Fts3GetVarint(pExpr->pCurrent, &pExpr->iCurrent);
115730   }
115731   return SQLITE_OK;
115732 }
115733
115734 /*
115735 ** Load the doclists for each phrase in the query associated with FTS3 cursor
115736 ** pCsr. 
115737 **
115738 ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable 
115739 ** phrases in the expression (all phrases except those directly or 
115740 ** indirectly descended from the right-hand-side of a NOT operator). If 
115741 ** pnToken is not NULL, then it is set to the number of tokens in all
115742 ** matchable phrases of the expression.
115743 */
115744 static int fts3ExprLoadDoclists(
115745   Fts3Cursor *pCsr,               /* Fts3 cursor for current query */
115746   int *pnPhrase,                  /* OUT: Number of phrases in query */
115747   int *pnToken                    /* OUT: Number of tokens in query */
115748 ){
115749   int rc;                         /* Return Code */
115750   LoadDoclistCtx sCtx = {0,0,0};  /* Context for fts3ExprIterate() */
115751   sCtx.pTab = (Fts3Table *)pCsr->base.pVtab;
115752   rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb1, (void *)&sCtx);
115753   if( rc==SQLITE_OK ){
115754     (void)fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb2, 0);
115755   }
115756   if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
115757   if( pnToken ) *pnToken = sCtx.nToken;
115758   return rc;
115759 }
115760
115761 /*
115762 ** Advance the position list iterator specified by the first two 
115763 ** arguments so that it points to the first element with a value greater
115764 ** than or equal to parameter iNext.
115765 */
115766 static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
115767   char *pIter = *ppIter;
115768   if( pIter ){
115769     int iIter = *piIter;
115770
115771     while( iIter<iNext ){
115772       if( 0==(*pIter & 0xFE) ){
115773         iIter = -1;
115774         pIter = 0;
115775         break;
115776       }
115777       fts3GetDeltaPosition(&pIter, &iIter);
115778     }
115779
115780     *piIter = iIter;
115781     *ppIter = pIter;
115782   }
115783 }
115784
115785 /*
115786 ** Advance the snippet iterator to the next candidate snippet.
115787 */
115788 static int fts3SnippetNextCandidate(SnippetIter *pIter){
115789   int i;                          /* Loop counter */
115790
115791   if( pIter->iCurrent<0 ){
115792     /* The SnippetIter object has just been initialized. The first snippet
115793     ** candidate always starts at offset 0 (even if this candidate has a
115794     ** score of 0.0).
115795     */
115796     pIter->iCurrent = 0;
115797
115798     /* Advance the 'head' iterator of each phrase to the first offset that
115799     ** is greater than or equal to (iNext+nSnippet).
115800     */
115801     for(i=0; i<pIter->nPhrase; i++){
115802       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
115803       fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
115804     }
115805   }else{
115806     int iStart;
115807     int iEnd = 0x7FFFFFFF;
115808
115809     for(i=0; i<pIter->nPhrase; i++){
115810       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
115811       if( pPhrase->pHead && pPhrase->iHead<iEnd ){
115812         iEnd = pPhrase->iHead;
115813       }
115814     }
115815     if( iEnd==0x7FFFFFFF ){
115816       return 1;
115817     }
115818
115819     pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
115820     for(i=0; i<pIter->nPhrase; i++){
115821       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
115822       fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
115823       fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
115824     }
115825   }
115826
115827   return 0;
115828 }
115829
115830 /*
115831 ** Retrieve information about the current candidate snippet of snippet 
115832 ** iterator pIter.
115833 */
115834 static void fts3SnippetDetails(
115835   SnippetIter *pIter,             /* Snippet iterator */
115836   u64 mCovered,                   /* Bitmask of phrases already covered */
115837   int *piToken,                   /* OUT: First token of proposed snippet */
115838   int *piScore,                   /* OUT: "Score" for this snippet */
115839   u64 *pmCover,                   /* OUT: Bitmask of phrases covered */
115840   u64 *pmHighlight                /* OUT: Bitmask of terms to highlight */
115841 ){
115842   int iStart = pIter->iCurrent;   /* First token of snippet */
115843   int iScore = 0;                 /* Score of this snippet */
115844   int i;                          /* Loop counter */
115845   u64 mCover = 0;                 /* Mask of phrases covered by this snippet */
115846   u64 mHighlight = 0;             /* Mask of tokens to highlight in snippet */
115847
115848   for(i=0; i<pIter->nPhrase; i++){
115849     SnippetPhrase *pPhrase = &pIter->aPhrase[i];
115850     if( pPhrase->pTail ){
115851       char *pCsr = pPhrase->pTail;
115852       int iCsr = pPhrase->iTail;
115853
115854       while( iCsr<(iStart+pIter->nSnippet) ){
115855         int j;
115856         u64 mPhrase = (u64)1 << i;
115857         u64 mPos = (u64)1 << (iCsr - iStart);
115858         assert( iCsr>=iStart );
115859         if( (mCover|mCovered)&mPhrase ){
115860           iScore++;
115861         }else{
115862           iScore += 1000;
115863         }
115864         mCover |= mPhrase;
115865
115866         for(j=0; j<pPhrase->nToken; j++){
115867           mHighlight |= (mPos>>j);
115868         }
115869
115870         if( 0==(*pCsr & 0x0FE) ) break;
115871         fts3GetDeltaPosition(&pCsr, &iCsr);
115872       }
115873     }
115874   }
115875
115876   /* Set the output variables before returning. */
115877   *piToken = iStart;
115878   *piScore = iScore;
115879   *pmCover = mCover;
115880   *pmHighlight = mHighlight;
115881 }
115882
115883 /*
115884 ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
115885 ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
115886 */
115887 static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
115888   SnippetIter *p = (SnippetIter *)ctx;
115889   SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
115890   char *pCsr;
115891
115892   pPhrase->nToken = pExpr->pPhrase->nToken;
115893
115894   pCsr = sqlite3Fts3FindPositions(pExpr, p->pCsr->iPrevId, p->iCol);
115895   if( pCsr ){
115896     int iFirst = 0;
115897     pPhrase->pList = pCsr;
115898     fts3GetDeltaPosition(&pCsr, &iFirst);
115899     pPhrase->pHead = pCsr;
115900     pPhrase->pTail = pCsr;
115901     pPhrase->iHead = iFirst;
115902     pPhrase->iTail = iFirst;
115903   }else{
115904     assert( pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0 );
115905   }
115906
115907   return SQLITE_OK;
115908 }
115909
115910 /*
115911 ** Select the fragment of text consisting of nFragment contiguous tokens 
115912 ** from column iCol that represent the "best" snippet. The best snippet
115913 ** is the snippet with the highest score, where scores are calculated
115914 ** by adding:
115915 **
115916 **   (a) +1 point for each occurence of a matchable phrase in the snippet.
115917 **
115918 **   (b) +1000 points for the first occurence of each matchable phrase in 
115919 **       the snippet for which the corresponding mCovered bit is not set.
115920 **
115921 ** The selected snippet parameters are stored in structure *pFragment before
115922 ** returning. The score of the selected snippet is stored in *piScore
115923 ** before returning.
115924 */
115925 static int fts3BestSnippet(
115926   int nSnippet,                   /* Desired snippet length */
115927   Fts3Cursor *pCsr,               /* Cursor to create snippet for */
115928   int iCol,                       /* Index of column to create snippet from */
115929   u64 mCovered,                   /* Mask of phrases already covered */
115930   u64 *pmSeen,                    /* IN/OUT: Mask of phrases seen */
115931   SnippetFragment *pFragment,     /* OUT: Best snippet found */
115932   int *piScore                    /* OUT: Score of snippet pFragment */
115933 ){
115934   int rc;                         /* Return Code */
115935   int nList;                      /* Number of phrases in expression */
115936   SnippetIter sIter;              /* Iterates through snippet candidates */
115937   int nByte;                      /* Number of bytes of space to allocate */
115938   int iBestScore = -1;            /* Best snippet score found so far */
115939   int i;                          /* Loop counter */
115940
115941   memset(&sIter, 0, sizeof(sIter));
115942
115943   /* Iterate through the phrases in the expression to count them. The same
115944   ** callback makes sure the doclists are loaded for each phrase.
115945   */
115946   rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
115947   if( rc!=SQLITE_OK ){
115948     return rc;
115949   }
115950
115951   /* Now that it is known how many phrases there are, allocate and zero
115952   ** the required space using malloc().
115953   */
115954   nByte = sizeof(SnippetPhrase) * nList;
115955   sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
115956   if( !sIter.aPhrase ){
115957     return SQLITE_NOMEM;
115958   }
115959   memset(sIter.aPhrase, 0, nByte);
115960
115961   /* Initialize the contents of the SnippetIter object. Then iterate through
115962   ** the set of phrases in the expression to populate the aPhrase[] array.
115963   */
115964   sIter.pCsr = pCsr;
115965   sIter.iCol = iCol;
115966   sIter.nSnippet = nSnippet;
115967   sIter.nPhrase = nList;
115968   sIter.iCurrent = -1;
115969   (void)fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void *)&sIter);
115970
115971   /* Set the *pmSeen output variable. */
115972   for(i=0; i<nList; i++){
115973     if( sIter.aPhrase[i].pHead ){
115974       *pmSeen |= (u64)1 << i;
115975     }
115976   }
115977
115978   /* Loop through all candidate snippets. Store the best snippet in 
115979   ** *pFragment. Store its associated 'score' in iBestScore.
115980   */
115981   pFragment->iCol = iCol;
115982   while( !fts3SnippetNextCandidate(&sIter) ){
115983     int iPos;
115984     int iScore;
115985     u64 mCover;
115986     u64 mHighlight;
115987     fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover, &mHighlight);
115988     assert( iScore>=0 );
115989     if( iScore>iBestScore ){
115990       pFragment->iPos = iPos;
115991       pFragment->hlmask = mHighlight;
115992       pFragment->covered = mCover;
115993       iBestScore = iScore;
115994     }
115995   }
115996
115997   sqlite3_free(sIter.aPhrase);
115998   *piScore = iBestScore;
115999   return SQLITE_OK;
116000 }
116001
116002
116003 /*
116004 ** Append a string to the string-buffer passed as the first argument.
116005 **
116006 ** If nAppend is negative, then the length of the string zAppend is
116007 ** determined using strlen().
116008 */
116009 static int fts3StringAppend(
116010   StrBuffer *pStr,                /* Buffer to append to */
116011   const char *zAppend,            /* Pointer to data to append to buffer */
116012   int nAppend                     /* Size of zAppend in bytes (or -1) */
116013 ){
116014   if( nAppend<0 ){
116015     nAppend = (int)strlen(zAppend);
116016   }
116017
116018   /* If there is insufficient space allocated at StrBuffer.z, use realloc()
116019   ** to grow the buffer until so that it is big enough to accomadate the
116020   ** appended data.
116021   */
116022   if( pStr->n+nAppend+1>=pStr->nAlloc ){
116023     int nAlloc = pStr->nAlloc+nAppend+100;
116024     char *zNew = sqlite3_realloc(pStr->z, nAlloc);
116025     if( !zNew ){
116026       return SQLITE_NOMEM;
116027     }
116028     pStr->z = zNew;
116029     pStr->nAlloc = nAlloc;
116030   }
116031
116032   /* Append the data to the string buffer. */
116033   memcpy(&pStr->z[pStr->n], zAppend, nAppend);
116034   pStr->n += nAppend;
116035   pStr->z[pStr->n] = '\0';
116036
116037   return SQLITE_OK;
116038 }
116039
116040 /*
116041 ** The fts3BestSnippet() function often selects snippets that end with a
116042 ** query term. That is, the final term of the snippet is always a term
116043 ** that requires highlighting. For example, if 'X' is a highlighted term
116044 ** and '.' is a non-highlighted term, BestSnippet() may select:
116045 **
116046 **     ........X.....X
116047 **
116048 ** This function "shifts" the beginning of the snippet forward in the 
116049 ** document so that there are approximately the same number of 
116050 ** non-highlighted terms to the right of the final highlighted term as there
116051 ** are to the left of the first highlighted term. For example, to this:
116052 **
116053 **     ....X.....X....
116054 **
116055 ** This is done as part of extracting the snippet text, not when selecting
116056 ** the snippet. Snippet selection is done based on doclists only, so there
116057 ** is no way for fts3BestSnippet() to know whether or not the document 
116058 ** actually contains terms that follow the final highlighted term. 
116059 */
116060 static int fts3SnippetShift(
116061   Fts3Table *pTab,                /* FTS3 table snippet comes from */
116062   int nSnippet,                   /* Number of tokens desired for snippet */
116063   const char *zDoc,               /* Document text to extract snippet from */
116064   int nDoc,                       /* Size of buffer zDoc in bytes */
116065   int *piPos,                     /* IN/OUT: First token of snippet */
116066   u64 *pHlmask                    /* IN/OUT: Mask of tokens to highlight */
116067 ){
116068   u64 hlmask = *pHlmask;          /* Local copy of initial highlight-mask */
116069
116070   if( hlmask ){
116071     int nLeft;                    /* Tokens to the left of first highlight */
116072     int nRight;                   /* Tokens to the right of last highlight */
116073     int nDesired;                 /* Ideal number of tokens to shift forward */
116074
116075     for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
116076     for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
116077     nDesired = (nLeft-nRight)/2;
116078
116079     /* Ideally, the start of the snippet should be pushed forward in the
116080     ** document nDesired tokens. This block checks if there are actually
116081     ** nDesired tokens to the right of the snippet. If so, *piPos and
116082     ** *pHlMask are updated to shift the snippet nDesired tokens to the
116083     ** right. Otherwise, the snippet is shifted by the number of tokens
116084     ** available.
116085     */
116086     if( nDesired>0 ){
116087       int nShift;                 /* Number of tokens to shift snippet by */
116088       int iCurrent = 0;           /* Token counter */
116089       int rc;                     /* Return Code */
116090       sqlite3_tokenizer_module *pMod;
116091       sqlite3_tokenizer_cursor *pC;
116092       pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
116093
116094       /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
116095       ** or more tokens in zDoc/nDoc.
116096       */
116097       rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
116098       if( rc!=SQLITE_OK ){
116099         return rc;
116100       }
116101       pC->pTokenizer = pTab->pTokenizer;
116102       while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
116103         const char *ZDUMMY; int DUMMY1, DUMMY2, DUMMY3;
116104         rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
116105       }
116106       pMod->xClose(pC);
116107       if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
116108
116109       nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
116110       assert( nShift<=nDesired );
116111       if( nShift>0 ){
116112         *piPos += nShift;
116113         *pHlmask = hlmask >> nShift;
116114       }
116115     }
116116   }
116117   return SQLITE_OK;
116118 }
116119
116120 /*
116121 ** Extract the snippet text for fragment pFragment from cursor pCsr and
116122 ** append it to string buffer pOut.
116123 */
116124 static int fts3SnippetText(
116125   Fts3Cursor *pCsr,               /* FTS3 Cursor */
116126   SnippetFragment *pFragment,     /* Snippet to extract */
116127   int iFragment,                  /* Fragment number */
116128   int isLast,                     /* True for final fragment in snippet */
116129   int nSnippet,                   /* Number of tokens in extracted snippet */
116130   const char *zOpen,              /* String inserted before highlighted term */
116131   const char *zClose,             /* String inserted after highlighted term */
116132   const char *zEllipsis,          /* String inserted between snippets */
116133   StrBuffer *pOut                 /* Write output here */
116134 ){
116135   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
116136   int rc;                         /* Return code */
116137   const char *zDoc;               /* Document text to extract snippet from */
116138   int nDoc;                       /* Size of zDoc in bytes */
116139   int iCurrent = 0;               /* Current token number of document */
116140   int iEnd = 0;                   /* Byte offset of end of current token */
116141   int isShiftDone = 0;            /* True after snippet is shifted */
116142   int iPos = pFragment->iPos;     /* First token of snippet */
116143   u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
116144   int iCol = pFragment->iCol+1;   /* Query column to extract text from */
116145   sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
116146   sqlite3_tokenizer_cursor *pC;   /* Tokenizer cursor open on zDoc/nDoc */
116147   const char *ZDUMMY;             /* Dummy argument used with tokenizer */
116148   int DUMMY1;                     /* Dummy argument used with tokenizer */
116149   
116150   zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
116151   if( zDoc==0 ){
116152     if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
116153       return SQLITE_NOMEM;
116154     }
116155     return SQLITE_OK;
116156   }
116157   nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
116158
116159   /* Open a token cursor on the document. */
116160   pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
116161   rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
116162   if( rc!=SQLITE_OK ){
116163     return rc;
116164   }
116165   pC->pTokenizer = pTab->pTokenizer;
116166
116167   while( rc==SQLITE_OK ){
116168     int iBegin;                   /* Offset in zDoc of start of token */
116169     int iFin;                     /* Offset in zDoc of end of token */
116170     int isHighlight;              /* True for highlighted terms */
116171
116172     rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
116173     if( rc!=SQLITE_OK ){
116174       if( rc==SQLITE_DONE ){
116175         /* Special case - the last token of the snippet is also the last token
116176         ** of the column. Append any punctuation that occurred between the end
116177         ** of the previous token and the end of the document to the output. 
116178         ** Then break out of the loop. */
116179         rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
116180       }
116181       break;
116182     }
116183     if( iCurrent<iPos ){ continue; }
116184
116185     if( !isShiftDone ){
116186       int n = nDoc - iBegin;
116187       rc = fts3SnippetShift(pTab, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask);
116188       isShiftDone = 1;
116189
116190       /* Now that the shift has been done, check if the initial "..." are
116191       ** required. They are required if (a) this is not the first fragment,
116192       ** or (b) this fragment does not begin at position 0 of its column. 
116193       */
116194       if( rc==SQLITE_OK && (iPos>0 || iFragment>0) ){
116195         rc = fts3StringAppend(pOut, zEllipsis, -1);
116196       }
116197       if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
116198     }
116199
116200     if( iCurrent>=(iPos+nSnippet) ){
116201       if( isLast ){
116202         rc = fts3StringAppend(pOut, zEllipsis, -1);
116203       }
116204       break;
116205     }
116206
116207     /* Set isHighlight to true if this term should be highlighted. */
116208     isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
116209
116210     if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
116211     if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
116212     if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
116213     if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
116214
116215     iEnd = iFin;
116216   }
116217
116218   pMod->xClose(pC);
116219   return rc;
116220 }
116221
116222
116223 /*
116224 ** This function is used to count the entries in a column-list (a 
116225 ** delta-encoded list of term offsets within a single column of a single 
116226 ** row). When this function is called, *ppCollist should point to the
116227 ** beginning of the first varint in the column-list (the varint that
116228 ** contains the position of the first matching term in the column data).
116229 ** Before returning, *ppCollist is set to point to the first byte after
116230 ** the last varint in the column-list (either the 0x00 signifying the end
116231 ** of the position-list, or the 0x01 that precedes the column number of
116232 ** the next column in the position-list).
116233 **
116234 ** The number of elements in the column-list is returned.
116235 */
116236 static int fts3ColumnlistCount(char **ppCollist){
116237   char *pEnd = *ppCollist;
116238   char c = 0;
116239   int nEntry = 0;
116240
116241   /* A column-list is terminated by either a 0x01 or 0x00. */
116242   while( 0xFE & (*pEnd | c) ){
116243     c = *pEnd++ & 0x80;
116244     if( !c ) nEntry++;
116245   }
116246
116247   *ppCollist = pEnd;
116248   return nEntry;
116249 }
116250
116251 static void fts3LoadColumnlistCounts(char **pp, u32 *aOut, int isGlobal){
116252   char *pCsr = *pp;
116253   while( *pCsr ){
116254     int nHit;
116255     sqlite3_int64 iCol = 0;
116256     if( *pCsr==0x01 ){
116257       pCsr++;
116258       pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
116259     }
116260     nHit = fts3ColumnlistCount(&pCsr);
116261     assert( nHit>0 );
116262     if( isGlobal ){
116263       aOut[iCol*3+1]++;
116264     }
116265     aOut[iCol*3] += nHit;
116266   }
116267   pCsr++;
116268   *pp = pCsr;
116269 }
116270
116271 /*
116272 ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
116273 ** for a single query. The "global" stats are those elements of the matchinfo
116274 ** array that are constant for all rows returned by the current query.
116275 */
116276 static int fts3ExprGlobalMatchinfoCb(
116277   Fts3Expr *pExpr,                /* Phrase expression node */
116278   int iPhrase,                    /* Phrase number (numbered from zero) */
116279   void *pCtx                      /* Pointer to MatchInfo structure */
116280 ){
116281   MatchInfo *p = (MatchInfo *)pCtx;
116282   char *pCsr;
116283   char *pEnd;
116284   const int iStart = 2 + (iPhrase * p->nCol * 3) + 1;
116285
116286   assert( pExpr->isLoaded );
116287
116288   /* Fill in the global hit count matrix row for this phrase. */
116289   pCsr = pExpr->aDoclist;
116290   pEnd = &pExpr->aDoclist[pExpr->nDoclist];
116291   while( pCsr<pEnd ){
116292     while( *pCsr++ & 0x80 );      /* Skip past docid. */
116293     fts3LoadColumnlistCounts(&pCsr, &p->aMatchinfo[iStart], 1);
116294   }
116295
116296   return SQLITE_OK;
116297 }
116298
116299 /*
116300 ** fts3ExprIterate() callback used to collect the "local" matchinfo stats
116301 ** for a single query. The "local" stats are those elements of the matchinfo
116302 ** array that are different for each row returned by the query.
116303 */
116304 static int fts3ExprLocalMatchinfoCb(
116305   Fts3Expr *pExpr,                /* Phrase expression node */
116306   int iPhrase,                    /* Phrase number */
116307   void *pCtx                      /* Pointer to MatchInfo structure */
116308 ){
116309   MatchInfo *p = (MatchInfo *)pCtx;
116310
116311   if( pExpr->aDoclist ){
116312     char *pCsr;
116313     int iStart = 2 + (iPhrase * p->nCol * 3);
116314     int i;
116315
116316     for(i=0; i<p->nCol; i++) p->aMatchinfo[iStart+i*3] = 0;
116317
116318     pCsr = sqlite3Fts3FindPositions(pExpr, p->pCursor->iPrevId, -1);
116319     if( pCsr ){
116320       fts3LoadColumnlistCounts(&pCsr, &p->aMatchinfo[iStart], 0);
116321     }
116322   }
116323
116324   return SQLITE_OK;
116325 }
116326
116327 /*
116328 ** Populate pCsr->aMatchinfo[] with data for the current row. The 
116329 ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
116330 */
116331 static int fts3GetMatchinfo(Fts3Cursor *pCsr){
116332   MatchInfo sInfo;
116333   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
116334   int rc = SQLITE_OK;
116335
116336   sInfo.pCursor = pCsr;
116337   sInfo.nCol = pTab->nColumn;
116338
116339   if( pCsr->aMatchinfo==0 ){
116340     /* If Fts3Cursor.aMatchinfo[] is NULL, then this is the first time the
116341     ** matchinfo function has been called for this query. In this case 
116342     ** allocate the array used to accumulate the matchinfo data and
116343     ** initialize those elements that are constant for every row.
116344     */
116345     int nPhrase;                  /* Number of phrases */
116346     int nMatchinfo;               /* Number of u32 elements in match-info */
116347
116348     /* Load doclists for each phrase in the query. */
116349     rc = fts3ExprLoadDoclists(pCsr, &nPhrase, 0);
116350     if( rc!=SQLITE_OK ){
116351       return rc;
116352     }
116353     nMatchinfo = 2 + 3*sInfo.nCol*nPhrase;
116354     if( pTab->bHasDocsize ){
116355       nMatchinfo += 1 + 2*pTab->nColumn;
116356     }
116357
116358     sInfo.aMatchinfo = (u32 *)sqlite3_malloc(sizeof(u32)*nMatchinfo);
116359     if( !sInfo.aMatchinfo ){ 
116360       return SQLITE_NOMEM;
116361     }
116362     memset(sInfo.aMatchinfo, 0, sizeof(u32)*nMatchinfo);
116363
116364
116365     /* First element of match-info is the number of phrases in the query */
116366     sInfo.aMatchinfo[0] = nPhrase;
116367     sInfo.aMatchinfo[1] = sInfo.nCol;
116368     (void)fts3ExprIterate(pCsr->pExpr, fts3ExprGlobalMatchinfoCb,(void*)&sInfo);
116369     if( pTab->bHasDocsize ){
116370       int ofst = 2 + 3*sInfo.aMatchinfo[0]*sInfo.aMatchinfo[1];
116371       rc = sqlite3Fts3MatchinfoDocsizeGlobal(pCsr, &sInfo.aMatchinfo[ofst]);
116372     }
116373     pCsr->aMatchinfo = sInfo.aMatchinfo;
116374     pCsr->isMatchinfoNeeded = 1;
116375   }
116376
116377   sInfo.aMatchinfo = pCsr->aMatchinfo;
116378   if( rc==SQLITE_OK && pCsr->isMatchinfoNeeded ){
116379     (void)fts3ExprIterate(pCsr->pExpr, fts3ExprLocalMatchinfoCb, (void*)&sInfo);
116380     if( pTab->bHasDocsize ){
116381       int ofst = 2 + 3*sInfo.aMatchinfo[0]*sInfo.aMatchinfo[1];
116382       rc = sqlite3Fts3MatchinfoDocsizeLocal(pCsr, &sInfo.aMatchinfo[ofst]);
116383     }
116384     pCsr->isMatchinfoNeeded = 0;
116385   }
116386
116387   return SQLITE_OK;
116388 }
116389
116390 /*
116391 ** Implementation of snippet() function.
116392 */
116393 SQLITE_PRIVATE void sqlite3Fts3Snippet(
116394   sqlite3_context *pCtx,          /* SQLite function call context */
116395   Fts3Cursor *pCsr,               /* Cursor object */
116396   const char *zStart,             /* Snippet start text - "<b>" */
116397   const char *zEnd,               /* Snippet end text - "</b>" */
116398   const char *zEllipsis,          /* Snippet ellipsis text - "<b>...</b>" */
116399   int iCol,                       /* Extract snippet from this column */
116400   int nToken                      /* Approximate number of tokens in snippet */
116401 ){
116402   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
116403   int rc = SQLITE_OK;
116404   int i;
116405   StrBuffer res = {0, 0, 0};
116406
116407   /* The returned text includes up to four fragments of text extracted from
116408   ** the data in the current row. The first iteration of the for(...) loop
116409   ** below attempts to locate a single fragment of text nToken tokens in 
116410   ** size that contains at least one instance of all phrases in the query
116411   ** expression that appear in the current row. If such a fragment of text
116412   ** cannot be found, the second iteration of the loop attempts to locate
116413   ** a pair of fragments, and so on.
116414   */
116415   int nSnippet = 0;               /* Number of fragments in this snippet */
116416   SnippetFragment aSnippet[4];    /* Maximum of 4 fragments per snippet */
116417   int nFToken = -1;               /* Number of tokens in each fragment */
116418
116419   if( !pCsr->pExpr ){
116420     sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
116421     return;
116422   }
116423
116424   for(nSnippet=1; 1; nSnippet++){
116425
116426     int iSnip;                    /* Loop counter 0..nSnippet-1 */
116427     u64 mCovered = 0;             /* Bitmask of phrases covered by snippet */
116428     u64 mSeen = 0;                /* Bitmask of phrases seen by BestSnippet() */
116429
116430     if( nToken>=0 ){
116431       nFToken = (nToken+nSnippet-1) / nSnippet;
116432     }else{
116433       nFToken = -1 * nToken;
116434     }
116435
116436     for(iSnip=0; iSnip<nSnippet; iSnip++){
116437       int iBestScore = -1;        /* Best score of columns checked so far */
116438       int iRead;                  /* Used to iterate through columns */
116439       SnippetFragment *pFragment = &aSnippet[iSnip];
116440
116441       memset(pFragment, 0, sizeof(*pFragment));
116442
116443       /* Loop through all columns of the table being considered for snippets.
116444       ** If the iCol argument to this function was negative, this means all
116445       ** columns of the FTS3 table. Otherwise, only column iCol is considered.
116446       */
116447       for(iRead=0; iRead<pTab->nColumn; iRead++){
116448         SnippetFragment sF;
116449         int iS;
116450         if( iCol>=0 && iRead!=iCol ) continue;
116451
116452         /* Find the best snippet of nFToken tokens in column iRead. */
116453         rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
116454         if( rc!=SQLITE_OK ){
116455           goto snippet_out;
116456         }
116457         if( iS>iBestScore ){
116458           *pFragment = sF;
116459           iBestScore = iS;
116460         }
116461       }
116462
116463       mCovered |= pFragment->covered;
116464     }
116465
116466     /* If all query phrases seen by fts3BestSnippet() are present in at least
116467     ** one of the nSnippet snippet fragments, break out of the loop.
116468     */
116469     assert( (mCovered&mSeen)==mCovered );
116470     if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
116471   }
116472
116473   assert( nFToken>0 );
116474
116475   for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
116476     rc = fts3SnippetText(pCsr, &aSnippet[i], 
116477         i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
116478     );
116479   }
116480
116481  snippet_out:
116482   if( rc!=SQLITE_OK ){
116483     sqlite3_result_error_code(pCtx, rc);
116484     sqlite3_free(res.z);
116485   }else{
116486     sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
116487   }
116488 }
116489
116490
116491 typedef struct TermOffset TermOffset;
116492 typedef struct TermOffsetCtx TermOffsetCtx;
116493
116494 struct TermOffset {
116495   char *pList;                    /* Position-list */
116496   int iPos;                       /* Position just read from pList */
116497   int iOff;                       /* Offset of this term from read positions */
116498 };
116499
116500 struct TermOffsetCtx {
116501   int iCol;                       /* Column of table to populate aTerm for */
116502   int iTerm;
116503   sqlite3_int64 iDocid;
116504   TermOffset *aTerm;
116505 };
116506
116507 /*
116508 ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
116509 */
116510 static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
116511   TermOffsetCtx *p = (TermOffsetCtx *)ctx;
116512   int nTerm;                      /* Number of tokens in phrase */
116513   int iTerm;                      /* For looping through nTerm phrase terms */
116514   char *pList;                    /* Pointer to position list for phrase */
116515   int iPos = 0;                   /* First position in position-list */
116516
116517   UNUSED_PARAMETER(iPhrase);
116518   pList = sqlite3Fts3FindPositions(pExpr, p->iDocid, p->iCol);
116519   nTerm = pExpr->pPhrase->nToken;
116520   if( pList ){
116521     fts3GetDeltaPosition(&pList, &iPos);
116522     assert( iPos>=0 );
116523   }
116524
116525   for(iTerm=0; iTerm<nTerm; iTerm++){
116526     TermOffset *pT = &p->aTerm[p->iTerm++];
116527     pT->iOff = nTerm-iTerm-1;
116528     pT->pList = pList;
116529     pT->iPos = iPos;
116530   }
116531
116532   return SQLITE_OK;
116533 }
116534
116535 /*
116536 ** Implementation of offsets() function.
116537 */
116538 SQLITE_PRIVATE void sqlite3Fts3Offsets(
116539   sqlite3_context *pCtx,          /* SQLite function call context */
116540   Fts3Cursor *pCsr                /* Cursor object */
116541 ){
116542   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
116543   sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
116544   const char *ZDUMMY;             /* Dummy argument used with xNext() */
116545   int NDUMMY;                     /* Dummy argument used with xNext() */
116546   int rc;                         /* Return Code */
116547   int nToken;                     /* Number of tokens in query */
116548   int iCol;                       /* Column currently being processed */
116549   StrBuffer res = {0, 0, 0};      /* Result string */
116550   TermOffsetCtx sCtx;             /* Context for fts3ExprTermOffsetInit() */
116551
116552   if( !pCsr->pExpr ){
116553     sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
116554     return;
116555   }
116556
116557   memset(&sCtx, 0, sizeof(sCtx));
116558   assert( pCsr->isRequireSeek==0 );
116559
116560   /* Count the number of terms in the query */
116561   rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
116562   if( rc!=SQLITE_OK ) goto offsets_out;
116563
116564   /* Allocate the array of TermOffset iterators. */
116565   sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
116566   if( 0==sCtx.aTerm ){
116567     rc = SQLITE_NOMEM;
116568     goto offsets_out;
116569   }
116570   sCtx.iDocid = pCsr->iPrevId;
116571
116572   /* Loop through the table columns, appending offset information to 
116573   ** string-buffer res for each column.
116574   */
116575   for(iCol=0; iCol<pTab->nColumn; iCol++){
116576     sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
116577     int iStart;
116578     int iEnd;
116579     int iCurrent;
116580     const char *zDoc;
116581     int nDoc;
116582
116583     /* Initialize the contents of sCtx.aTerm[] for column iCol. There is 
116584     ** no way that this operation can fail, so the return code from
116585     ** fts3ExprIterate() can be discarded.
116586     */
116587     sCtx.iCol = iCol;
116588     sCtx.iTerm = 0;
116589     (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void *)&sCtx);
116590
116591     /* Retreive the text stored in column iCol. If an SQL NULL is stored 
116592     ** in column iCol, jump immediately to the next iteration of the loop.
116593     ** If an OOM occurs while retrieving the data (this can happen if SQLite
116594     ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM 
116595     ** to the caller. 
116596     */
116597     zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
116598     nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
116599     if( zDoc==0 ){
116600       if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
116601         continue;
116602       }
116603       rc = SQLITE_NOMEM;
116604       goto offsets_out;
116605     }
116606
116607     /* Initialize a tokenizer iterator to iterate through column iCol. */
116608     rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
116609     if( rc!=SQLITE_OK ) goto offsets_out;
116610     pC->pTokenizer = pTab->pTokenizer;
116611
116612     rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
116613     while( rc==SQLITE_OK ){
116614       int i;                      /* Used to loop through terms */
116615       int iMinPos = 0x7FFFFFFF;   /* Position of next token */
116616       TermOffset *pTerm = 0;      /* TermOffset associated with next token */
116617
116618       for(i=0; i<nToken; i++){
116619         TermOffset *pT = &sCtx.aTerm[i];
116620         if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
116621           iMinPos = pT->iPos-pT->iOff;
116622           pTerm = pT;
116623         }
116624       }
116625
116626       if( !pTerm ){
116627         /* All offsets for this column have been gathered. */
116628         break;
116629       }else{
116630         assert( iCurrent<=iMinPos );
116631         if( 0==(0xFE&*pTerm->pList) ){
116632           pTerm->pList = 0;
116633         }else{
116634           fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
116635         }
116636         while( rc==SQLITE_OK && iCurrent<iMinPos ){
116637           rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
116638         }
116639         if( rc==SQLITE_OK ){
116640           char aBuffer[64];
116641           sqlite3_snprintf(sizeof(aBuffer), aBuffer, 
116642               "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
116643           );
116644           rc = fts3StringAppend(&res, aBuffer, -1);
116645         }else if( rc==SQLITE_DONE ){
116646           rc = SQLITE_CORRUPT;
116647         }
116648       }
116649     }
116650     if( rc==SQLITE_DONE ){
116651       rc = SQLITE_OK;
116652     }
116653
116654     pMod->xClose(pC);
116655     if( rc!=SQLITE_OK ) goto offsets_out;
116656   }
116657
116658  offsets_out:
116659   sqlite3_free(sCtx.aTerm);
116660   assert( rc!=SQLITE_DONE );
116661   if( rc!=SQLITE_OK ){
116662     sqlite3_result_error_code(pCtx,  rc);
116663     sqlite3_free(res.z);
116664   }else{
116665     sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
116666   }
116667   return;
116668 }
116669
116670 /*
116671 ** Implementation of matchinfo() function.
116672 */
116673 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *pContext, Fts3Cursor *pCsr){
116674   int rc;
116675   if( !pCsr->pExpr ){
116676     sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
116677     return;
116678   }
116679   rc = fts3GetMatchinfo(pCsr);
116680   if( rc!=SQLITE_OK ){
116681     sqlite3_result_error_code(pContext, rc);
116682   }else{
116683     Fts3Table *pTab = (Fts3Table*)pCsr->base.pVtab;
116684     int n = sizeof(u32)*(2+pCsr->aMatchinfo[0]*pCsr->aMatchinfo[1]*3);
116685     if( pTab->bHasDocsize ){
116686       n += sizeof(u32)*(1 + 2*pTab->nColumn);
116687     }
116688     sqlite3_result_blob(pContext, pCsr->aMatchinfo, n, SQLITE_TRANSIENT);
116689   }
116690 }
116691
116692 #endif
116693
116694 /************** End of fts3_snippet.c ****************************************/
116695 /************** Begin file rtree.c *******************************************/
116696 /*
116697 ** 2001 September 15
116698 **
116699 ** The author disclaims copyright to this source code.  In place of
116700 ** a legal notice, here is a blessing:
116701 **
116702 **    May you do good and not evil.
116703 **    May you find forgiveness for yourself and forgive others.
116704 **    May you share freely, never taking more than you give.
116705 **
116706 *************************************************************************
116707 ** This file contains code for implementations of the r-tree and r*-tree
116708 ** algorithms packaged as an SQLite virtual table module.
116709 */
116710
116711 /*
116712 ** Database Format of R-Tree Tables
116713 ** --------------------------------
116714 **
116715 ** The data structure for a single virtual r-tree table is stored in three 
116716 ** native SQLite tables declared as follows. In each case, the '%' character
116717 ** in the table name is replaced with the user-supplied name of the r-tree
116718 ** table.
116719 **
116720 **   CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
116721 **   CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
116722 **   CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
116723 **
116724 ** The data for each node of the r-tree structure is stored in the %_node
116725 ** table. For each node that is not the root node of the r-tree, there is
116726 ** an entry in the %_parent table associating the node with its parent.
116727 ** And for each row of data in the table, there is an entry in the %_rowid
116728 ** table that maps from the entries rowid to the id of the node that it
116729 ** is stored on.
116730 **
116731 ** The root node of an r-tree always exists, even if the r-tree table is
116732 ** empty. The nodeno of the root node is always 1. All other nodes in the
116733 ** table must be the same size as the root node. The content of each node
116734 ** is formatted as follows:
116735 **
116736 **   1. If the node is the root node (node 1), then the first 2 bytes
116737 **      of the node contain the tree depth as a big-endian integer.
116738 **      For non-root nodes, the first 2 bytes are left unused.
116739 **
116740 **   2. The next 2 bytes contain the number of entries currently 
116741 **      stored in the node.
116742 **
116743 **   3. The remainder of the node contains the node entries. Each entry
116744 **      consists of a single 8-byte integer followed by an even number
116745 **      of 4-byte coordinates. For leaf nodes the integer is the rowid
116746 **      of a record. For internal nodes it is the node number of a
116747 **      child page.
116748 */
116749
116750 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
116751
116752 /*
116753 ** This file contains an implementation of a couple of different variants
116754 ** of the r-tree algorithm. See the README file for further details. The 
116755 ** same data-structure is used for all, but the algorithms for insert and
116756 ** delete operations vary. The variants used are selected at compile time 
116757 ** by defining the following symbols:
116758 */
116759
116760 /* Either, both or none of the following may be set to activate 
116761 ** r*tree variant algorithms.
116762 */
116763 #define VARIANT_RSTARTREE_CHOOSESUBTREE 0
116764 #define VARIANT_RSTARTREE_REINSERT      1
116765
116766 /* 
116767 ** Exactly one of the following must be set to 1.
116768 */
116769 #define VARIANT_GUTTMAN_QUADRATIC_SPLIT 0
116770 #define VARIANT_GUTTMAN_LINEAR_SPLIT    0
116771 #define VARIANT_RSTARTREE_SPLIT         1
116772
116773 #define VARIANT_GUTTMAN_SPLIT \
116774         (VARIANT_GUTTMAN_LINEAR_SPLIT||VARIANT_GUTTMAN_QUADRATIC_SPLIT)
116775
116776 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
116777   #define PickNext QuadraticPickNext
116778   #define PickSeeds QuadraticPickSeeds
116779   #define AssignCells splitNodeGuttman
116780 #endif
116781 #if VARIANT_GUTTMAN_LINEAR_SPLIT
116782   #define PickNext LinearPickNext
116783   #define PickSeeds LinearPickSeeds
116784   #define AssignCells splitNodeGuttman
116785 #endif
116786 #if VARIANT_RSTARTREE_SPLIT
116787   #define AssignCells splitNodeStartree
116788 #endif
116789
116790 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
116791 # define NDEBUG 1
116792 #endif
116793
116794 #ifndef SQLITE_CORE
116795   SQLITE_EXTENSION_INIT1
116796 #else
116797 #endif
116798
116799
116800 #ifndef SQLITE_AMALGAMATION
116801 #include "sqlite3rtree.h"
116802 typedef sqlite3_int64 i64;
116803 typedef unsigned char u8;
116804 typedef unsigned int u32;
116805 #endif
116806
116807 typedef struct Rtree Rtree;
116808 typedef struct RtreeCursor RtreeCursor;
116809 typedef struct RtreeNode RtreeNode;
116810 typedef struct RtreeCell RtreeCell;
116811 typedef struct RtreeConstraint RtreeConstraint;
116812 typedef struct RtreeMatchArg RtreeMatchArg;
116813 typedef struct RtreeGeomCallback RtreeGeomCallback;
116814 typedef union RtreeCoord RtreeCoord;
116815
116816 /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
116817 #define RTREE_MAX_DIMENSIONS 5
116818
116819 /* Size of hash table Rtree.aHash. This hash table is not expected to
116820 ** ever contain very many entries, so a fixed number of buckets is 
116821 ** used.
116822 */
116823 #define HASHSIZE 128
116824
116825 /* 
116826 ** An rtree virtual-table object.
116827 */
116828 struct Rtree {
116829   sqlite3_vtab base;
116830   sqlite3 *db;                /* Host database connection */
116831   int iNodeSize;              /* Size in bytes of each node in the node table */
116832   int nDim;                   /* Number of dimensions */
116833   int nBytesPerCell;          /* Bytes consumed per cell */
116834   int iDepth;                 /* Current depth of the r-tree structure */
116835   char *zDb;                  /* Name of database containing r-tree table */
116836   char *zName;                /* Name of r-tree table */ 
116837   RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */ 
116838   int nBusy;                  /* Current number of users of this structure */
116839
116840   /* List of nodes removed during a CondenseTree operation. List is
116841   ** linked together via the pointer normally used for hash chains -
116842   ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree 
116843   ** headed by the node (leaf nodes have RtreeNode.iNode==0).
116844   */
116845   RtreeNode *pDeleted;
116846   int iReinsertHeight;        /* Height of sub-trees Reinsert() has run on */
116847
116848   /* Statements to read/write/delete a record from xxx_node */
116849   sqlite3_stmt *pReadNode;
116850   sqlite3_stmt *pWriteNode;
116851   sqlite3_stmt *pDeleteNode;
116852
116853   /* Statements to read/write/delete a record from xxx_rowid */
116854   sqlite3_stmt *pReadRowid;
116855   sqlite3_stmt *pWriteRowid;
116856   sqlite3_stmt *pDeleteRowid;
116857
116858   /* Statements to read/write/delete a record from xxx_parent */
116859   sqlite3_stmt *pReadParent;
116860   sqlite3_stmt *pWriteParent;
116861   sqlite3_stmt *pDeleteParent;
116862
116863   int eCoordType;
116864 };
116865
116866 /* Possible values for eCoordType: */
116867 #define RTREE_COORD_REAL32 0
116868 #define RTREE_COORD_INT32  1
116869
116870 /*
116871 ** The minimum number of cells allowed for a node is a third of the 
116872 ** maximum. In Gutman's notation:
116873 **
116874 **     m = M/3
116875 **
116876 ** If an R*-tree "Reinsert" operation is required, the same number of
116877 ** cells are removed from the overfull node and reinserted into the tree.
116878 */
116879 #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
116880 #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
116881 #define RTREE_MAXCELLS 51
116882
116883 /*
116884 ** The smallest possible node-size is (512-64)==448 bytes. And the largest
116885 ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
116886 ** Therefore all non-root nodes must contain at least 3 entries. Since 
116887 ** 2^40 is greater than 2^64, an r-tree structure always has a depth of
116888 ** 40 or less.
116889 */
116890 #define RTREE_MAX_DEPTH 40
116891
116892 /* 
116893 ** An rtree cursor object.
116894 */
116895 struct RtreeCursor {
116896   sqlite3_vtab_cursor base;
116897   RtreeNode *pNode;                 /* Node cursor is currently pointing at */
116898   int iCell;                        /* Index of current cell in pNode */
116899   int iStrategy;                    /* Copy of idxNum search parameter */
116900   int nConstraint;                  /* Number of entries in aConstraint */
116901   RtreeConstraint *aConstraint;     /* Search constraints. */
116902 };
116903
116904 union RtreeCoord {
116905   float f;
116906   int i;
116907 };
116908
116909 /*
116910 ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
116911 ** formatted as a double. This macro assumes that local variable pRtree points
116912 ** to the Rtree structure associated with the RtreeCoord.
116913 */
116914 #define DCOORD(coord) (                           \
116915   (pRtree->eCoordType==RTREE_COORD_REAL32) ?      \
116916     ((double)coord.f) :                           \
116917     ((double)coord.i)                             \
116918 )
116919
116920 /*
116921 ** A search constraint.
116922 */
116923 struct RtreeConstraint {
116924   int iCoord;                     /* Index of constrained coordinate */
116925   int op;                         /* Constraining operation */
116926   double rValue;                  /* Constraint value. */
116927   int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *);
116928   sqlite3_rtree_geometry *pGeom;  /* Constraint callback argument for a MATCH */
116929 };
116930
116931 /* Possible values for RtreeConstraint.op */
116932 #define RTREE_EQ    0x41
116933 #define RTREE_LE    0x42
116934 #define RTREE_LT    0x43
116935 #define RTREE_GE    0x44
116936 #define RTREE_GT    0x45
116937 #define RTREE_MATCH 0x46
116938
116939 /* 
116940 ** An rtree structure node.
116941 */
116942 struct RtreeNode {
116943   RtreeNode *pParent;               /* Parent node */
116944   i64 iNode;
116945   int nRef;
116946   int isDirty;
116947   u8 *zData;
116948   RtreeNode *pNext;                 /* Next node in this hash chain */
116949 };
116950 #define NCELL(pNode) readInt16(&(pNode)->zData[2])
116951
116952 /* 
116953 ** Structure to store a deserialized rtree record.
116954 */
116955 struct RtreeCell {
116956   i64 iRowid;
116957   RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];
116958 };
116959
116960
116961 /*
116962 ** Value for the first field of every RtreeMatchArg object. The MATCH
116963 ** operator tests that the first field of a blob operand matches this
116964 ** value to avoid operating on invalid blobs (which could cause a segfault).
116965 */
116966 #define RTREE_GEOMETRY_MAGIC 0x891245AB
116967
116968 /*
116969 ** An instance of this structure must be supplied as a blob argument to
116970 ** the right-hand-side of an SQL MATCH operator used to constrain an
116971 ** r-tree query.
116972 */
116973 struct RtreeMatchArg {
116974   u32 magic;                      /* Always RTREE_GEOMETRY_MAGIC */
116975   int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *);
116976   void *pContext;
116977   int nParam;
116978   double aParam[1];
116979 };
116980
116981 /*
116982 ** When a geometry callback is created (see sqlite3_rtree_geometry_callback),
116983 ** a single instance of the following structure is allocated. It is used
116984 ** as the context for the user-function created by by s_r_g_c(). The object
116985 ** is eventually deleted by the destructor mechanism provided by
116986 ** sqlite3_create_function_v2() (which is called by s_r_g_c() to create
116987 ** the geometry callback function).
116988 */
116989 struct RtreeGeomCallback {
116990   int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *);
116991   void *pContext;
116992 };
116993
116994 #ifndef MAX
116995 # define MAX(x,y) ((x) < (y) ? (y) : (x))
116996 #endif
116997 #ifndef MIN
116998 # define MIN(x,y) ((x) > (y) ? (y) : (x))
116999 #endif
117000
117001 /*
117002 ** Functions to deserialize a 16 bit integer, 32 bit real number and
117003 ** 64 bit integer. The deserialized value is returned.
117004 */
117005 static int readInt16(u8 *p){
117006   return (p[0]<<8) + p[1];
117007 }
117008 static void readCoord(u8 *p, RtreeCoord *pCoord){
117009   u32 i = (
117010     (((u32)p[0]) << 24) + 
117011     (((u32)p[1]) << 16) + 
117012     (((u32)p[2]) <<  8) + 
117013     (((u32)p[3]) <<  0)
117014   );
117015   *(u32 *)pCoord = i;
117016 }
117017 static i64 readInt64(u8 *p){
117018   return (
117019     (((i64)p[0]) << 56) + 
117020     (((i64)p[1]) << 48) + 
117021     (((i64)p[2]) << 40) + 
117022     (((i64)p[3]) << 32) + 
117023     (((i64)p[4]) << 24) + 
117024     (((i64)p[5]) << 16) + 
117025     (((i64)p[6]) <<  8) + 
117026     (((i64)p[7]) <<  0)
117027   );
117028 }
117029
117030 /*
117031 ** Functions to serialize a 16 bit integer, 32 bit real number and
117032 ** 64 bit integer. The value returned is the number of bytes written
117033 ** to the argument buffer (always 2, 4 and 8 respectively).
117034 */
117035 static int writeInt16(u8 *p, int i){
117036   p[0] = (i>> 8)&0xFF;
117037   p[1] = (i>> 0)&0xFF;
117038   return 2;
117039 }
117040 static int writeCoord(u8 *p, RtreeCoord *pCoord){
117041   u32 i;
117042   assert( sizeof(RtreeCoord)==4 );
117043   assert( sizeof(u32)==4 );
117044   i = *(u32 *)pCoord;
117045   p[0] = (i>>24)&0xFF;
117046   p[1] = (i>>16)&0xFF;
117047   p[2] = (i>> 8)&0xFF;
117048   p[3] = (i>> 0)&0xFF;
117049   return 4;
117050 }
117051 static int writeInt64(u8 *p, i64 i){
117052   p[0] = (i>>56)&0xFF;
117053   p[1] = (i>>48)&0xFF;
117054   p[2] = (i>>40)&0xFF;
117055   p[3] = (i>>32)&0xFF;
117056   p[4] = (i>>24)&0xFF;
117057   p[5] = (i>>16)&0xFF;
117058   p[6] = (i>> 8)&0xFF;
117059   p[7] = (i>> 0)&0xFF;
117060   return 8;
117061 }
117062
117063 /*
117064 ** Increment the reference count of node p.
117065 */
117066 static void nodeReference(RtreeNode *p){
117067   if( p ){
117068     p->nRef++;
117069   }
117070 }
117071
117072 /*
117073 ** Clear the content of node p (set all bytes to 0x00).
117074 */
117075 static void nodeZero(Rtree *pRtree, RtreeNode *p){
117076   memset(&p->zData[2], 0, pRtree->iNodeSize-2);
117077   p->isDirty = 1;
117078 }
117079
117080 /*
117081 ** Given a node number iNode, return the corresponding key to use
117082 ** in the Rtree.aHash table.
117083 */
117084 static int nodeHash(i64 iNode){
117085   return (
117086     (iNode>>56) ^ (iNode>>48) ^ (iNode>>40) ^ (iNode>>32) ^ 
117087     (iNode>>24) ^ (iNode>>16) ^ (iNode>> 8) ^ (iNode>> 0)
117088   ) % HASHSIZE;
117089 }
117090
117091 /*
117092 ** Search the node hash table for node iNode. If found, return a pointer
117093 ** to it. Otherwise, return 0.
117094 */
117095 static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
117096   RtreeNode *p;
117097   for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
117098   return p;
117099 }
117100
117101 /*
117102 ** Add node pNode to the node hash table.
117103 */
117104 static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
117105   int iHash;
117106   assert( pNode->pNext==0 );
117107   iHash = nodeHash(pNode->iNode);
117108   pNode->pNext = pRtree->aHash[iHash];
117109   pRtree->aHash[iHash] = pNode;
117110 }
117111
117112 /*
117113 ** Remove node pNode from the node hash table.
117114 */
117115 static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
117116   RtreeNode **pp;
117117   if( pNode->iNode!=0 ){
117118     pp = &pRtree->aHash[nodeHash(pNode->iNode)];
117119     for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
117120     *pp = pNode->pNext;
117121     pNode->pNext = 0;
117122   }
117123 }
117124
117125 /*
117126 ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
117127 ** indicating that node has not yet been assigned a node number. It is
117128 ** assigned a node number when nodeWrite() is called to write the
117129 ** node contents out to the database.
117130 */
117131 static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
117132   RtreeNode *pNode;
117133   pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
117134   if( pNode ){
117135     memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
117136     pNode->zData = (u8 *)&pNode[1];
117137     pNode->nRef = 1;
117138     pNode->pParent = pParent;
117139     pNode->isDirty = 1;
117140     nodeReference(pParent);
117141   }
117142   return pNode;
117143 }
117144
117145 /*
117146 ** Obtain a reference to an r-tree node.
117147 */
117148 static int
117149 nodeAcquire(
117150   Rtree *pRtree,             /* R-tree structure */
117151   i64 iNode,                 /* Node number to load */
117152   RtreeNode *pParent,        /* Either the parent node or NULL */
117153   RtreeNode **ppNode         /* OUT: Acquired node */
117154 ){
117155   int rc;
117156   int rc2 = SQLITE_OK;
117157   RtreeNode *pNode;
117158
117159   /* Check if the requested node is already in the hash table. If so,
117160   ** increase its reference count and return it.
117161   */
117162   if( (pNode = nodeHashLookup(pRtree, iNode)) ){
117163     assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
117164     if( pParent && !pNode->pParent ){
117165       nodeReference(pParent);
117166       pNode->pParent = pParent;
117167     }
117168     pNode->nRef++;
117169     *ppNode = pNode;
117170     return SQLITE_OK;
117171   }
117172
117173   sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
117174   rc = sqlite3_step(pRtree->pReadNode);
117175   if( rc==SQLITE_ROW ){
117176     const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
117177     if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){
117178       pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
117179       if( !pNode ){
117180         rc2 = SQLITE_NOMEM;
117181       }else{
117182         pNode->pParent = pParent;
117183         pNode->zData = (u8 *)&pNode[1];
117184         pNode->nRef = 1;
117185         pNode->iNode = iNode;
117186         pNode->isDirty = 0;
117187         pNode->pNext = 0;
117188         memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
117189         nodeReference(pParent);
117190       }
117191     }
117192   }
117193   rc = sqlite3_reset(pRtree->pReadNode);
117194   if( rc==SQLITE_OK ) rc = rc2;
117195
117196   /* If the root node was just loaded, set pRtree->iDepth to the height
117197   ** of the r-tree structure. A height of zero means all data is stored on
117198   ** the root node. A height of one means the children of the root node
117199   ** are the leaves, and so on. If the depth as specified on the root node
117200   ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
117201   */
117202   if( pNode && iNode==1 ){
117203     pRtree->iDepth = readInt16(pNode->zData);
117204     if( pRtree->iDepth>RTREE_MAX_DEPTH ){
117205       rc = SQLITE_CORRUPT;
117206     }
117207   }
117208
117209   /* If no error has occurred so far, check if the "number of entries"
117210   ** field on the node is too large. If so, set the return code to 
117211   ** SQLITE_CORRUPT.
117212   */
117213   if( pNode && rc==SQLITE_OK ){
117214     if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
117215       rc = SQLITE_CORRUPT;
117216     }
117217   }
117218
117219   if( rc==SQLITE_OK ){
117220     if( pNode!=0 ){
117221       nodeHashInsert(pRtree, pNode);
117222     }else{
117223       rc = SQLITE_CORRUPT;
117224     }
117225     *ppNode = pNode;
117226   }else{
117227     sqlite3_free(pNode);
117228     *ppNode = 0;
117229   }
117230
117231   return rc;
117232 }
117233
117234 /*
117235 ** Overwrite cell iCell of node pNode with the contents of pCell.
117236 */
117237 static void nodeOverwriteCell(
117238   Rtree *pRtree, 
117239   RtreeNode *pNode,  
117240   RtreeCell *pCell, 
117241   int iCell
117242 ){
117243   int ii;
117244   u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
117245   p += writeInt64(p, pCell->iRowid);
117246   for(ii=0; ii<(pRtree->nDim*2); ii++){
117247     p += writeCoord(p, &pCell->aCoord[ii]);
117248   }
117249   pNode->isDirty = 1;
117250 }
117251
117252 /*
117253 ** Remove cell the cell with index iCell from node pNode.
117254 */
117255 static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
117256   u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
117257   u8 *pSrc = &pDst[pRtree->nBytesPerCell];
117258   int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
117259   memmove(pDst, pSrc, nByte);
117260   writeInt16(&pNode->zData[2], NCELL(pNode)-1);
117261   pNode->isDirty = 1;
117262 }
117263
117264 /*
117265 ** Insert the contents of cell pCell into node pNode. If the insert
117266 ** is successful, return SQLITE_OK.
117267 **
117268 ** If there is not enough free space in pNode, return SQLITE_FULL.
117269 */
117270 static int
117271 nodeInsertCell(
117272   Rtree *pRtree, 
117273   RtreeNode *pNode, 
117274   RtreeCell *pCell 
117275 ){
117276   int nCell;                    /* Current number of cells in pNode */
117277   int nMaxCell;                 /* Maximum number of cells for pNode */
117278
117279   nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
117280   nCell = NCELL(pNode);
117281
117282   assert( nCell<=nMaxCell );
117283   if( nCell<nMaxCell ){
117284     nodeOverwriteCell(pRtree, pNode, pCell, nCell);
117285     writeInt16(&pNode->zData[2], nCell+1);
117286     pNode->isDirty = 1;
117287   }
117288
117289   return (nCell==nMaxCell);
117290 }
117291
117292 /*
117293 ** If the node is dirty, write it out to the database.
117294 */
117295 static int
117296 nodeWrite(Rtree *pRtree, RtreeNode *pNode){
117297   int rc = SQLITE_OK;
117298   if( pNode->isDirty ){
117299     sqlite3_stmt *p = pRtree->pWriteNode;
117300     if( pNode->iNode ){
117301       sqlite3_bind_int64(p, 1, pNode->iNode);
117302     }else{
117303       sqlite3_bind_null(p, 1);
117304     }
117305     sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
117306     sqlite3_step(p);
117307     pNode->isDirty = 0;
117308     rc = sqlite3_reset(p);
117309     if( pNode->iNode==0 && rc==SQLITE_OK ){
117310       pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
117311       nodeHashInsert(pRtree, pNode);
117312     }
117313   }
117314   return rc;
117315 }
117316
117317 /*
117318 ** Release a reference to a node. If the node is dirty and the reference
117319 ** count drops to zero, the node data is written to the database.
117320 */
117321 static int
117322 nodeRelease(Rtree *pRtree, RtreeNode *pNode){
117323   int rc = SQLITE_OK;
117324   if( pNode ){
117325     assert( pNode->nRef>0 );
117326     pNode->nRef--;
117327     if( pNode->nRef==0 ){
117328       if( pNode->iNode==1 ){
117329         pRtree->iDepth = -1;
117330       }
117331       if( pNode->pParent ){
117332         rc = nodeRelease(pRtree, pNode->pParent);
117333       }
117334       if( rc==SQLITE_OK ){
117335         rc = nodeWrite(pRtree, pNode);
117336       }
117337       nodeHashDelete(pRtree, pNode);
117338       sqlite3_free(pNode);
117339     }
117340   }
117341   return rc;
117342 }
117343
117344 /*
117345 ** Return the 64-bit integer value associated with cell iCell of
117346 ** node pNode. If pNode is a leaf node, this is a rowid. If it is
117347 ** an internal node, then the 64-bit integer is a child page number.
117348 */
117349 static i64 nodeGetRowid(
117350   Rtree *pRtree, 
117351   RtreeNode *pNode, 
117352   int iCell
117353 ){
117354   assert( iCell<NCELL(pNode) );
117355   return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
117356 }
117357
117358 /*
117359 ** Return coordinate iCoord from cell iCell in node pNode.
117360 */
117361 static void nodeGetCoord(
117362   Rtree *pRtree, 
117363   RtreeNode *pNode, 
117364   int iCell,
117365   int iCoord,
117366   RtreeCoord *pCoord           /* Space to write result to */
117367 ){
117368   readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
117369 }
117370
117371 /*
117372 ** Deserialize cell iCell of node pNode. Populate the structure pointed
117373 ** to by pCell with the results.
117374 */
117375 static void nodeGetCell(
117376   Rtree *pRtree, 
117377   RtreeNode *pNode, 
117378   int iCell,
117379   RtreeCell *pCell
117380 ){
117381   int ii;
117382   pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
117383   for(ii=0; ii<pRtree->nDim*2; ii++){
117384     nodeGetCoord(pRtree, pNode, iCell, ii, &pCell->aCoord[ii]);
117385   }
117386 }
117387
117388
117389 /* Forward declaration for the function that does the work of
117390 ** the virtual table module xCreate() and xConnect() methods.
117391 */
117392 static int rtreeInit(
117393   sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
117394 );
117395
117396 /* 
117397 ** Rtree virtual table module xCreate method.
117398 */
117399 static int rtreeCreate(
117400   sqlite3 *db,
117401   void *pAux,
117402   int argc, const char *const*argv,
117403   sqlite3_vtab **ppVtab,
117404   char **pzErr
117405 ){
117406   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
117407 }
117408
117409 /* 
117410 ** Rtree virtual table module xConnect method.
117411 */
117412 static int rtreeConnect(
117413   sqlite3 *db,
117414   void *pAux,
117415   int argc, const char *const*argv,
117416   sqlite3_vtab **ppVtab,
117417   char **pzErr
117418 ){
117419   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
117420 }
117421
117422 /*
117423 ** Increment the r-tree reference count.
117424 */
117425 static void rtreeReference(Rtree *pRtree){
117426   pRtree->nBusy++;
117427 }
117428
117429 /*
117430 ** Decrement the r-tree reference count. When the reference count reaches
117431 ** zero the structure is deleted.
117432 */
117433 static void rtreeRelease(Rtree *pRtree){
117434   pRtree->nBusy--;
117435   if( pRtree->nBusy==0 ){
117436     sqlite3_finalize(pRtree->pReadNode);
117437     sqlite3_finalize(pRtree->pWriteNode);
117438     sqlite3_finalize(pRtree->pDeleteNode);
117439     sqlite3_finalize(pRtree->pReadRowid);
117440     sqlite3_finalize(pRtree->pWriteRowid);
117441     sqlite3_finalize(pRtree->pDeleteRowid);
117442     sqlite3_finalize(pRtree->pReadParent);
117443     sqlite3_finalize(pRtree->pWriteParent);
117444     sqlite3_finalize(pRtree->pDeleteParent);
117445     sqlite3_free(pRtree);
117446   }
117447 }
117448
117449 /* 
117450 ** Rtree virtual table module xDisconnect method.
117451 */
117452 static int rtreeDisconnect(sqlite3_vtab *pVtab){
117453   rtreeRelease((Rtree *)pVtab);
117454   return SQLITE_OK;
117455 }
117456
117457 /* 
117458 ** Rtree virtual table module xDestroy method.
117459 */
117460 static int rtreeDestroy(sqlite3_vtab *pVtab){
117461   Rtree *pRtree = (Rtree *)pVtab;
117462   int rc;
117463   char *zCreate = sqlite3_mprintf(
117464     "DROP TABLE '%q'.'%q_node';"
117465     "DROP TABLE '%q'.'%q_rowid';"
117466     "DROP TABLE '%q'.'%q_parent';",
117467     pRtree->zDb, pRtree->zName, 
117468     pRtree->zDb, pRtree->zName,
117469     pRtree->zDb, pRtree->zName
117470   );
117471   if( !zCreate ){
117472     rc = SQLITE_NOMEM;
117473   }else{
117474     rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
117475     sqlite3_free(zCreate);
117476   }
117477   if( rc==SQLITE_OK ){
117478     rtreeRelease(pRtree);
117479   }
117480
117481   return rc;
117482 }
117483
117484 /* 
117485 ** Rtree virtual table module xOpen method.
117486 */
117487 static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
117488   int rc = SQLITE_NOMEM;
117489   RtreeCursor *pCsr;
117490
117491   pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
117492   if( pCsr ){
117493     memset(pCsr, 0, sizeof(RtreeCursor));
117494     pCsr->base.pVtab = pVTab;
117495     rc = SQLITE_OK;
117496   }
117497   *ppCursor = (sqlite3_vtab_cursor *)pCsr;
117498
117499   return rc;
117500 }
117501
117502
117503 /*
117504 ** Free the RtreeCursor.aConstraint[] array and its contents.
117505 */
117506 static void freeCursorConstraints(RtreeCursor *pCsr){
117507   if( pCsr->aConstraint ){
117508     int i;                        /* Used to iterate through constraint array */
117509     for(i=0; i<pCsr->nConstraint; i++){
117510       sqlite3_rtree_geometry *pGeom = pCsr->aConstraint[i].pGeom;
117511       if( pGeom ){
117512         if( pGeom->xDelUser ) pGeom->xDelUser(pGeom->pUser);
117513         sqlite3_free(pGeom);
117514       }
117515     }
117516     sqlite3_free(pCsr->aConstraint);
117517     pCsr->aConstraint = 0;
117518   }
117519 }
117520
117521 /* 
117522 ** Rtree virtual table module xClose method.
117523 */
117524 static int rtreeClose(sqlite3_vtab_cursor *cur){
117525   Rtree *pRtree = (Rtree *)(cur->pVtab);
117526   int rc;
117527   RtreeCursor *pCsr = (RtreeCursor *)cur;
117528   freeCursorConstraints(pCsr);
117529   rc = nodeRelease(pRtree, pCsr->pNode);
117530   sqlite3_free(pCsr);
117531   return rc;
117532 }
117533
117534 /*
117535 ** Rtree virtual table module xEof method.
117536 **
117537 ** Return non-zero if the cursor does not currently point to a valid 
117538 ** record (i.e if the scan has finished), or zero otherwise.
117539 */
117540 static int rtreeEof(sqlite3_vtab_cursor *cur){
117541   RtreeCursor *pCsr = (RtreeCursor *)cur;
117542   return (pCsr->pNode==0);
117543 }
117544
117545 /*
117546 ** The r-tree constraint passed as the second argument to this function is
117547 ** guaranteed to be a MATCH constraint.
117548 */
117549 static int testRtreeGeom(
117550   Rtree *pRtree,                  /* R-Tree object */
117551   RtreeConstraint *pConstraint,   /* MATCH constraint to test */
117552   RtreeCell *pCell,               /* Cell to test */
117553   int *pbRes                      /* OUT: Test result */
117554 ){
117555   int i;
117556   double aCoord[RTREE_MAX_DIMENSIONS*2];
117557   int nCoord = pRtree->nDim*2;
117558
117559   assert( pConstraint->op==RTREE_MATCH );
117560   assert( pConstraint->pGeom );
117561
117562   for(i=0; i<nCoord; i++){
117563     aCoord[i] = DCOORD(pCell->aCoord[i]);
117564   }
117565   return pConstraint->xGeom(pConstraint->pGeom, nCoord, aCoord, pbRes);
117566 }
117567
117568 /* 
117569 ** Cursor pCursor currently points to a cell in a non-leaf page.
117570 ** Set *pbEof to true if the sub-tree headed by the cell is filtered
117571 ** (excluded) by the constraints in the pCursor->aConstraint[] 
117572 ** array, or false otherwise.
117573 **
117574 ** Return SQLITE_OK if successful or an SQLite error code if an error
117575 ** occurs within a geometry callback.
117576 */
117577 static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
117578   RtreeCell cell;
117579   int ii;
117580   int bRes = 0;
117581
117582   nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
117583   for(ii=0; bRes==0 && ii<pCursor->nConstraint; ii++){
117584     RtreeConstraint *p = &pCursor->aConstraint[ii];
117585     double cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]);
117586     double cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]);
117587
117588     assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE 
117589         || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
117590     );
117591
117592     switch( p->op ){
117593       case RTREE_LE: case RTREE_LT: 
117594         bRes = p->rValue<cell_min; 
117595         break;
117596
117597       case RTREE_GE: case RTREE_GT: 
117598         bRes = p->rValue>cell_max; 
117599         break;
117600
117601       case RTREE_EQ:
117602         bRes = (p->rValue>cell_max || p->rValue<cell_min);
117603         break;
117604
117605       default: {
117606         int rc;
117607         assert( p->op==RTREE_MATCH );
117608         rc = testRtreeGeom(pRtree, p, &cell, &bRes);
117609         if( rc!=SQLITE_OK ){
117610           return rc;
117611         }
117612         bRes = !bRes;
117613         break;
117614       }
117615     }
117616   }
117617
117618   *pbEof = bRes;
117619   return SQLITE_OK;
117620 }
117621
117622 /* 
117623 ** Test if the cell that cursor pCursor currently points to
117624 ** would be filtered (excluded) by the constraints in the 
117625 ** pCursor->aConstraint[] array. If so, set *pbEof to true before
117626 ** returning. If the cell is not filtered (excluded) by the constraints,
117627 ** set pbEof to zero.
117628 **
117629 ** Return SQLITE_OK if successful or an SQLite error code if an error
117630 ** occurs within a geometry callback.
117631 **
117632 ** This function assumes that the cell is part of a leaf node.
117633 */
117634 static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
117635   RtreeCell cell;
117636   int ii;
117637   *pbEof = 0;
117638
117639   nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
117640   for(ii=0; ii<pCursor->nConstraint; ii++){
117641     RtreeConstraint *p = &pCursor->aConstraint[ii];
117642     double coord = DCOORD(cell.aCoord[p->iCoord]);
117643     int res;
117644     assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE 
117645         || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
117646     );
117647     switch( p->op ){
117648       case RTREE_LE: res = (coord<=p->rValue); break;
117649       case RTREE_LT: res = (coord<p->rValue);  break;
117650       case RTREE_GE: res = (coord>=p->rValue); break;
117651       case RTREE_GT: res = (coord>p->rValue);  break;
117652       case RTREE_EQ: res = (coord==p->rValue); break;
117653       default: {
117654         int rc;
117655         assert( p->op==RTREE_MATCH );
117656         rc = testRtreeGeom(pRtree, p, &cell, &res);
117657         if( rc!=SQLITE_OK ){
117658           return rc;
117659         }
117660         break;
117661       }
117662     }
117663
117664     if( !res ){
117665       *pbEof = 1;
117666       return SQLITE_OK;
117667     }
117668   }
117669
117670   return SQLITE_OK;
117671 }
117672
117673 /*
117674 ** Cursor pCursor currently points at a node that heads a sub-tree of
117675 ** height iHeight (if iHeight==0, then the node is a leaf). Descend
117676 ** to point to the left-most cell of the sub-tree that matches the 
117677 ** configured constraints.
117678 */
117679 static int descendToCell(
117680   Rtree *pRtree, 
117681   RtreeCursor *pCursor, 
117682   int iHeight,
117683   int *pEof                 /* OUT: Set to true if cannot descend */
117684 ){
117685   int isEof;
117686   int rc;
117687   int ii;
117688   RtreeNode *pChild;
117689   sqlite3_int64 iRowid;
117690
117691   RtreeNode *pSavedNode = pCursor->pNode;
117692   int iSavedCell = pCursor->iCell;
117693
117694   assert( iHeight>=0 );
117695
117696   if( iHeight==0 ){
117697     rc = testRtreeEntry(pRtree, pCursor, &isEof);
117698   }else{
117699     rc = testRtreeCell(pRtree, pCursor, &isEof);
117700   }
117701   if( rc!=SQLITE_OK || isEof || iHeight==0 ){
117702     *pEof = isEof;
117703     return rc;
117704   }
117705
117706   iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell);
117707   rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild);
117708   if( rc!=SQLITE_OK ){
117709     return rc;
117710   }
117711
117712   nodeRelease(pRtree, pCursor->pNode);
117713   pCursor->pNode = pChild;
117714   isEof = 1;
117715   for(ii=0; isEof && ii<NCELL(pChild); ii++){
117716     pCursor->iCell = ii;
117717     rc = descendToCell(pRtree, pCursor, iHeight-1, &isEof);
117718     if( rc!=SQLITE_OK ){
117719       return rc;
117720     }
117721   }
117722
117723   if( isEof ){
117724     assert( pCursor->pNode==pChild );
117725     nodeReference(pSavedNode);
117726     nodeRelease(pRtree, pChild);
117727     pCursor->pNode = pSavedNode;
117728     pCursor->iCell = iSavedCell;
117729   }
117730
117731   *pEof = isEof;
117732   return SQLITE_OK;
117733 }
117734
117735 /*
117736 ** One of the cells in node pNode is guaranteed to have a 64-bit 
117737 ** integer value equal to iRowid. Return the index of this cell.
117738 */
117739 static int nodeRowidIndex(
117740   Rtree *pRtree, 
117741   RtreeNode *pNode, 
117742   i64 iRowid,
117743   int *piIndex
117744 ){
117745   int ii;
117746   int nCell = NCELL(pNode);
117747   for(ii=0; ii<nCell; ii++){
117748     if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
117749       *piIndex = ii;
117750       return SQLITE_OK;
117751     }
117752   }
117753   return SQLITE_CORRUPT;
117754 }
117755
117756 /*
117757 ** Return the index of the cell containing a pointer to node pNode
117758 ** in its parent. If pNode is the root node, return -1.
117759 */
117760 static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
117761   RtreeNode *pParent = pNode->pParent;
117762   if( pParent ){
117763     return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
117764   }
117765   *piIndex = -1;
117766   return SQLITE_OK;
117767 }
117768
117769 /* 
117770 ** Rtree virtual table module xNext method.
117771 */
117772 static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
117773   Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab);
117774   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
117775   int rc = SQLITE_OK;
117776
117777   /* RtreeCursor.pNode must not be NULL. If is is NULL, then this cursor is
117778   ** already at EOF. It is against the rules to call the xNext() method of
117779   ** a cursor that has already reached EOF.
117780   */
117781   assert( pCsr->pNode );
117782
117783   if( pCsr->iStrategy==1 ){
117784     /* This "scan" is a direct lookup by rowid. There is no next entry. */
117785     nodeRelease(pRtree, pCsr->pNode);
117786     pCsr->pNode = 0;
117787   }else{
117788     /* Move to the next entry that matches the configured constraints. */
117789     int iHeight = 0;
117790     while( pCsr->pNode ){
117791       RtreeNode *pNode = pCsr->pNode;
117792       int nCell = NCELL(pNode);
117793       for(pCsr->iCell++; pCsr->iCell<nCell; pCsr->iCell++){
117794         int isEof;
117795         rc = descendToCell(pRtree, pCsr, iHeight, &isEof);
117796         if( rc!=SQLITE_OK || !isEof ){
117797           return rc;
117798         }
117799       }
117800       pCsr->pNode = pNode->pParent;
117801       rc = nodeParentIndex(pRtree, pNode, &pCsr->iCell);
117802       if( rc!=SQLITE_OK ){
117803         return rc;
117804       }
117805       nodeReference(pCsr->pNode);
117806       nodeRelease(pRtree, pNode);
117807       iHeight++;
117808     }
117809   }
117810
117811   return rc;
117812 }
117813
117814 /* 
117815 ** Rtree virtual table module xRowid method.
117816 */
117817 static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
117818   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
117819   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
117820
117821   assert(pCsr->pNode);
117822   *pRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
117823
117824   return SQLITE_OK;
117825 }
117826
117827 /* 
117828 ** Rtree virtual table module xColumn method.
117829 */
117830 static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
117831   Rtree *pRtree = (Rtree *)cur->pVtab;
117832   RtreeCursor *pCsr = (RtreeCursor *)cur;
117833
117834   if( i==0 ){
117835     i64 iRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
117836     sqlite3_result_int64(ctx, iRowid);
117837   }else{
117838     RtreeCoord c;
117839     nodeGetCoord(pRtree, pCsr->pNode, pCsr->iCell, i-1, &c);
117840     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
117841       sqlite3_result_double(ctx, c.f);
117842     }else{
117843       assert( pRtree->eCoordType==RTREE_COORD_INT32 );
117844       sqlite3_result_int(ctx, c.i);
117845     }
117846   }
117847
117848   return SQLITE_OK;
117849 }
117850
117851 /* 
117852 ** Use nodeAcquire() to obtain the leaf node containing the record with 
117853 ** rowid iRowid. If successful, set *ppLeaf to point to the node and
117854 ** return SQLITE_OK. If there is no such record in the table, set
117855 ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
117856 ** to zero and return an SQLite error code.
117857 */
117858 static int findLeafNode(Rtree *pRtree, i64 iRowid, RtreeNode **ppLeaf){
117859   int rc;
117860   *ppLeaf = 0;
117861   sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
117862   if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
117863     i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
117864     rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
117865     sqlite3_reset(pRtree->pReadRowid);
117866   }else{
117867     rc = sqlite3_reset(pRtree->pReadRowid);
117868   }
117869   return rc;
117870 }
117871
117872 /*
117873 ** This function is called to configure the RtreeConstraint object passed
117874 ** as the second argument for a MATCH constraint. The value passed as the
117875 ** first argument to this function is the right-hand operand to the MATCH
117876 ** operator.
117877 */
117878 static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
117879   RtreeMatchArg *p;
117880   sqlite3_rtree_geometry *pGeom;
117881   int nBlob;
117882
117883   /* Check that value is actually a blob. */
117884   if( !sqlite3_value_type(pValue)==SQLITE_BLOB ) return SQLITE_ERROR;
117885
117886   /* Check that the blob is roughly the right size. */
117887   nBlob = sqlite3_value_bytes(pValue);
117888   if( nBlob<sizeof(RtreeMatchArg) 
117889    || ((nBlob-sizeof(RtreeMatchArg))%sizeof(double))!=0
117890   ){
117891     return SQLITE_ERROR;
117892   }
117893
117894   pGeom = (sqlite3_rtree_geometry *)sqlite3_malloc(
117895       sizeof(sqlite3_rtree_geometry) + nBlob
117896   );
117897   if( !pGeom ) return SQLITE_NOMEM;
117898   memset(pGeom, 0, sizeof(sqlite3_rtree_geometry));
117899   p = (RtreeMatchArg *)&pGeom[1];
117900
117901   memcpy(p, sqlite3_value_blob(pValue), nBlob);
117902   if( p->magic!=RTREE_GEOMETRY_MAGIC 
117903    || nBlob!=(sizeof(RtreeMatchArg) + (p->nParam-1)*sizeof(double))
117904   ){
117905     sqlite3_free(pGeom);
117906     return SQLITE_ERROR;
117907   }
117908
117909   pGeom->pContext = p->pContext;
117910   pGeom->nParam = p->nParam;
117911   pGeom->aParam = p->aParam;
117912
117913   pCons->xGeom = p->xGeom;
117914   pCons->pGeom = pGeom;
117915   return SQLITE_OK;
117916 }
117917
117918 /* 
117919 ** Rtree virtual table module xFilter method.
117920 */
117921 static int rtreeFilter(
117922   sqlite3_vtab_cursor *pVtabCursor, 
117923   int idxNum, const char *idxStr,
117924   int argc, sqlite3_value **argv
117925 ){
117926   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
117927   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
117928
117929   RtreeNode *pRoot = 0;
117930   int ii;
117931   int rc = SQLITE_OK;
117932
117933   rtreeReference(pRtree);
117934
117935   freeCursorConstraints(pCsr);
117936   pCsr->iStrategy = idxNum;
117937
117938   if( idxNum==1 ){
117939     /* Special case - lookup by rowid. */
117940     RtreeNode *pLeaf;        /* Leaf on which the required cell resides */
117941     i64 iRowid = sqlite3_value_int64(argv[0]);
117942     rc = findLeafNode(pRtree, iRowid, &pLeaf);
117943     pCsr->pNode = pLeaf; 
117944     if( pLeaf ){
117945       assert( rc==SQLITE_OK );
117946       rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &pCsr->iCell);
117947     }
117948   }else{
117949     /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array 
117950     ** with the configured constraints. 
117951     */
117952     if( argc>0 ){
117953       pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
117954       pCsr->nConstraint = argc;
117955       if( !pCsr->aConstraint ){
117956         rc = SQLITE_NOMEM;
117957       }else{
117958         memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
117959         assert( (idxStr==0 && argc==0) || strlen(idxStr)==argc*2 );
117960         for(ii=0; ii<argc; ii++){
117961           RtreeConstraint *p = &pCsr->aConstraint[ii];
117962           p->op = idxStr[ii*2];
117963           p->iCoord = idxStr[ii*2+1]-'a';
117964           if( p->op==RTREE_MATCH ){
117965             /* A MATCH operator. The right-hand-side must be a blob that
117966             ** can be cast into an RtreeMatchArg object. One created using
117967             ** an sqlite3_rtree_geometry_callback() SQL user function.
117968             */
117969             rc = deserializeGeometry(argv[ii], p);
117970             if( rc!=SQLITE_OK ){
117971               break;
117972             }
117973           }else{
117974             p->rValue = sqlite3_value_double(argv[ii]);
117975           }
117976         }
117977       }
117978     }
117979   
117980     if( rc==SQLITE_OK ){
117981       pCsr->pNode = 0;
117982       rc = nodeAcquire(pRtree, 1, 0, &pRoot);
117983     }
117984     if( rc==SQLITE_OK ){
117985       int isEof = 1;
117986       int nCell = NCELL(pRoot);
117987       pCsr->pNode = pRoot;
117988       for(pCsr->iCell=0; rc==SQLITE_OK && pCsr->iCell<nCell; pCsr->iCell++){
117989         assert( pCsr->pNode==pRoot );
117990         rc = descendToCell(pRtree, pCsr, pRtree->iDepth, &isEof);
117991         if( !isEof ){
117992           break;
117993         }
117994       }
117995       if( rc==SQLITE_OK && isEof ){
117996         assert( pCsr->pNode==pRoot );
117997         nodeRelease(pRtree, pRoot);
117998         pCsr->pNode = 0;
117999       }
118000       assert( rc!=SQLITE_OK || !pCsr->pNode || pCsr->iCell<NCELL(pCsr->pNode) );
118001     }
118002   }
118003
118004   rtreeRelease(pRtree);
118005   return rc;
118006 }
118007
118008 /*
118009 ** Rtree virtual table module xBestIndex method. There are three
118010 ** table scan strategies to choose from (in order from most to 
118011 ** least desirable):
118012 **
118013 **   idxNum     idxStr        Strategy
118014 **   ------------------------------------------------
118015 **     1        Unused        Direct lookup by rowid.
118016 **     2        See below     R-tree query or full-table scan.
118017 **   ------------------------------------------------
118018 **
118019 ** If strategy 1 is used, then idxStr is not meaningful. If strategy
118020 ** 2 is used, idxStr is formatted to contain 2 bytes for each 
118021 ** constraint used. The first two bytes of idxStr correspond to 
118022 ** the constraint in sqlite3_index_info.aConstraintUsage[] with
118023 ** (argvIndex==1) etc.
118024 **
118025 ** The first of each pair of bytes in idxStr identifies the constraint
118026 ** operator as follows:
118027 **
118028 **   Operator    Byte Value
118029 **   ----------------------
118030 **      =        0x41 ('A')
118031 **     <=        0x42 ('B')
118032 **      <        0x43 ('C')
118033 **     >=        0x44 ('D')
118034 **      >        0x45 ('E')
118035 **   MATCH       0x46 ('F')
118036 **   ----------------------
118037 **
118038 ** The second of each pair of bytes identifies the coordinate column
118039 ** to which the constraint applies. The leftmost coordinate column
118040 ** is 'a', the second from the left 'b' etc.
118041 */
118042 static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
118043   int rc = SQLITE_OK;
118044   int ii, cCol;
118045
118046   int iIdx = 0;
118047   char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
118048   memset(zIdxStr, 0, sizeof(zIdxStr));
118049
118050   assert( pIdxInfo->idxStr==0 );
118051   for(ii=0; ii<pIdxInfo->nConstraint; ii++){
118052     struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
118053
118054     if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
118055       /* We have an equality constraint on the rowid. Use strategy 1. */
118056       int jj;
118057       for(jj=0; jj<ii; jj++){
118058         pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
118059         pIdxInfo->aConstraintUsage[jj].omit = 0;
118060       }
118061       pIdxInfo->idxNum = 1;
118062       pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
118063       pIdxInfo->aConstraintUsage[jj].omit = 1;
118064
118065       /* This strategy involves a two rowid lookups on an B-Tree structures
118066       ** and then a linear search of an R-Tree node. This should be 
118067       ** considered almost as quick as a direct rowid lookup (for which 
118068       ** sqlite uses an internal cost of 0.0).
118069       */ 
118070       pIdxInfo->estimatedCost = 10.0;
118071       return SQLITE_OK;
118072     }
118073
118074     if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
118075       int j, opmsk;
118076       static const unsigned char compatible[] = { 0, 0, 1, 1, 2, 2 };
118077       u8 op = 0;
118078       switch( p->op ){
118079         case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
118080         case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
118081         case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
118082         case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
118083         case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
118084         default:
118085           assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
118086           op = RTREE_MATCH; 
118087           break;
118088       }
118089       assert( op!=0 );
118090
118091       /* Make sure this particular constraint has not been used before.
118092       ** If it has been used before, ignore it.
118093       **
118094       ** A <= or < can be used if there is a prior >= or >.
118095       ** A >= or > can be used if there is a prior < or <=.
118096       ** A <= or < is disqualified if there is a prior <=, <, or ==.
118097       ** A >= or > is disqualified if there is a prior >=, >, or ==.
118098       ** A == is disqualifed if there is any prior constraint.
118099       */
118100       assert( compatible[RTREE_EQ & 7]==0 );
118101       assert( compatible[RTREE_LT & 7]==1 );
118102       assert( compatible[RTREE_LE & 7]==1 );
118103       assert( compatible[RTREE_GT & 7]==2 );
118104       assert( compatible[RTREE_GE & 7]==2 );
118105       cCol = p->iColumn - 1 + 'a';
118106       opmsk = compatible[op & 7];
118107       for(j=0; j<iIdx; j+=2){
118108         if( zIdxStr[j+1]==cCol && (compatible[zIdxStr[j] & 7] & opmsk)!=0 ){
118109           op = 0;
118110           break;
118111         }
118112       }
118113       if( op ){
118114         assert( iIdx<sizeof(zIdxStr)-1 );
118115         zIdxStr[iIdx++] = op;
118116         zIdxStr[iIdx++] = cCol;
118117         pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
118118         pIdxInfo->aConstraintUsage[ii].omit = 1;
118119       }
118120     }
118121   }
118122
118123   pIdxInfo->idxNum = 2;
118124   pIdxInfo->needToFreeIdxStr = 1;
118125   if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
118126     return SQLITE_NOMEM;
118127   }
118128   assert( iIdx>=0 );
118129   pIdxInfo->estimatedCost = (2000000.0 / (double)(iIdx + 1));
118130   return rc;
118131 }
118132
118133 /*
118134 ** Return the N-dimensional volumn of the cell stored in *p.
118135 */
118136 static float cellArea(Rtree *pRtree, RtreeCell *p){
118137   float area = 1.0;
118138   int ii;
118139   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
118140     area = area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
118141   }
118142   return area;
118143 }
118144
118145 /*
118146 ** Return the margin length of cell p. The margin length is the sum
118147 ** of the objects size in each dimension.
118148 */
118149 static float cellMargin(Rtree *pRtree, RtreeCell *p){
118150   float margin = 0.0;
118151   int ii;
118152   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
118153     margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
118154   }
118155   return margin;
118156 }
118157
118158 /*
118159 ** Store the union of cells p1 and p2 in p1.
118160 */
118161 static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
118162   int ii;
118163   if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
118164     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
118165       p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
118166       p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
118167     }
118168   }else{
118169     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
118170       p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
118171       p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
118172     }
118173   }
118174 }
118175
118176 /*
118177 ** Return true if the area covered by p2 is a subset of the area covered
118178 ** by p1. False otherwise.
118179 */
118180 static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
118181   int ii;
118182   int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
118183   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
118184     RtreeCoord *a1 = &p1->aCoord[ii];
118185     RtreeCoord *a2 = &p2->aCoord[ii];
118186     if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f)) 
118187      || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i)) 
118188     ){
118189       return 0;
118190     }
118191   }
118192   return 1;
118193 }
118194
118195 /*
118196 ** Return the amount cell p would grow by if it were unioned with pCell.
118197 */
118198 static float cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
118199   float area;
118200   RtreeCell cell;
118201   memcpy(&cell, p, sizeof(RtreeCell));
118202   area = cellArea(pRtree, &cell);
118203   cellUnion(pRtree, &cell, pCell);
118204   return (cellArea(pRtree, &cell)-area);
118205 }
118206
118207 #if VARIANT_RSTARTREE_CHOOSESUBTREE || VARIANT_RSTARTREE_SPLIT
118208 static float cellOverlap(
118209   Rtree *pRtree, 
118210   RtreeCell *p, 
118211   RtreeCell *aCell, 
118212   int nCell, 
118213   int iExclude
118214 ){
118215   int ii;
118216   float overlap = 0.0;
118217   for(ii=0; ii<nCell; ii++){
118218 #if VARIANT_RSTARTREE_CHOOSESUBTREE
118219     if( ii!=iExclude )
118220 #else
118221     assert( iExclude==-1 );
118222 #endif
118223     {
118224       int jj;
118225       float o = 1.0;
118226       for(jj=0; jj<(pRtree->nDim*2); jj+=2){
118227         double x1;
118228         double x2;
118229
118230         x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
118231         x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
118232
118233         if( x2<x1 ){
118234           o = 0.0;
118235           break;
118236         }else{
118237           o = o * (x2-x1);
118238         }
118239       }
118240       overlap += o;
118241     }
118242   }
118243   return overlap;
118244 }
118245 #endif
118246
118247 #if VARIANT_RSTARTREE_CHOOSESUBTREE
118248 static float cellOverlapEnlargement(
118249   Rtree *pRtree, 
118250   RtreeCell *p, 
118251   RtreeCell *pInsert, 
118252   RtreeCell *aCell, 
118253   int nCell, 
118254   int iExclude
118255 ){
118256   float before;
118257   float after;
118258   before = cellOverlap(pRtree, p, aCell, nCell, iExclude);
118259   cellUnion(pRtree, p, pInsert);
118260   after = cellOverlap(pRtree, p, aCell, nCell, iExclude);
118261   return after-before;
118262 }
118263 #endif
118264
118265
118266 /*
118267 ** This function implements the ChooseLeaf algorithm from Gutman[84].
118268 ** ChooseSubTree in r*tree terminology.
118269 */
118270 static int ChooseLeaf(
118271   Rtree *pRtree,               /* Rtree table */
118272   RtreeCell *pCell,            /* Cell to insert into rtree */
118273   int iHeight,                 /* Height of sub-tree rooted at pCell */
118274   RtreeNode **ppLeaf           /* OUT: Selected leaf page */
118275 ){
118276   int rc;
118277   int ii;
118278   RtreeNode *pNode;
118279   rc = nodeAcquire(pRtree, 1, 0, &pNode);
118280
118281   for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
118282     int iCell;
118283     sqlite3_int64 iBest;
118284
118285     float fMinGrowth;
118286     float fMinArea;
118287     float fMinOverlap;
118288
118289     int nCell = NCELL(pNode);
118290     RtreeCell cell;
118291     RtreeNode *pChild;
118292
118293     RtreeCell *aCell = 0;
118294
118295 #if VARIANT_RSTARTREE_CHOOSESUBTREE
118296     if( ii==(pRtree->iDepth-1) ){
118297       int jj;
118298       aCell = sqlite3_malloc(sizeof(RtreeCell)*nCell);
118299       if( !aCell ){
118300         rc = SQLITE_NOMEM;
118301         nodeRelease(pRtree, pNode);
118302         pNode = 0;
118303         continue;
118304       }
118305       for(jj=0; jj<nCell; jj++){
118306         nodeGetCell(pRtree, pNode, jj, &aCell[jj]);
118307       }
118308     }
118309 #endif
118310
118311     /* Select the child node which will be enlarged the least if pCell
118312     ** is inserted into it. Resolve ties by choosing the entry with
118313     ** the smallest area.
118314     */
118315     for(iCell=0; iCell<nCell; iCell++){
118316       int bBest = 0;
118317       float growth;
118318       float area;
118319       float overlap = 0.0;
118320       nodeGetCell(pRtree, pNode, iCell, &cell);
118321       growth = cellGrowth(pRtree, &cell, pCell);
118322       area = cellArea(pRtree, &cell);
118323
118324 #if VARIANT_RSTARTREE_CHOOSESUBTREE
118325       if( ii==(pRtree->iDepth-1) ){
118326         overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell);
118327       }
118328       if( (iCell==0) 
118329        || (overlap<fMinOverlap) 
118330        || (overlap==fMinOverlap && growth<fMinGrowth)
118331        || (overlap==fMinOverlap && growth==fMinGrowth && area<fMinArea)
118332       ){
118333         bBest = 1;
118334       }
118335 #else
118336       if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
118337         bBest = 1;
118338       }
118339 #endif
118340       if( bBest ){
118341         fMinOverlap = overlap;
118342         fMinGrowth = growth;
118343         fMinArea = area;
118344         iBest = cell.iRowid;
118345       }
118346     }
118347
118348     sqlite3_free(aCell);
118349     rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
118350     nodeRelease(pRtree, pNode);
118351     pNode = pChild;
118352   }
118353
118354   *ppLeaf = pNode;
118355   return rc;
118356 }
118357
118358 /*
118359 ** A cell with the same content as pCell has just been inserted into
118360 ** the node pNode. This function updates the bounding box cells in
118361 ** all ancestor elements.
118362 */
118363 static int AdjustTree(
118364   Rtree *pRtree,                    /* Rtree table */
118365   RtreeNode *pNode,                 /* Adjust ancestry of this node. */
118366   RtreeCell *pCell                  /* This cell was just inserted */
118367 ){
118368   RtreeNode *p = pNode;
118369   while( p->pParent ){
118370     RtreeNode *pParent = p->pParent;
118371     RtreeCell cell;
118372     int iCell;
118373
118374     if( nodeParentIndex(pRtree, p, &iCell) ){
118375       return SQLITE_CORRUPT;
118376     }
118377
118378     nodeGetCell(pRtree, pParent, iCell, &cell);
118379     if( !cellContains(pRtree, &cell, pCell) ){
118380       cellUnion(pRtree, &cell, pCell);
118381       nodeOverwriteCell(pRtree, pParent, &cell, iCell);
118382     }
118383  
118384     p = pParent;
118385   }
118386   return SQLITE_OK;
118387 }
118388
118389 /*
118390 ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
118391 */
118392 static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
118393   sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
118394   sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
118395   sqlite3_step(pRtree->pWriteRowid);
118396   return sqlite3_reset(pRtree->pWriteRowid);
118397 }
118398
118399 /*
118400 ** Write mapping (iNode->iPar) to the <rtree>_parent table.
118401 */
118402 static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
118403   sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
118404   sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
118405   sqlite3_step(pRtree->pWriteParent);
118406   return sqlite3_reset(pRtree->pWriteParent);
118407 }
118408
118409 static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
118410
118411 #if VARIANT_GUTTMAN_LINEAR_SPLIT
118412 /*
118413 ** Implementation of the linear variant of the PickNext() function from
118414 ** Guttman[84].
118415 */
118416 static RtreeCell *LinearPickNext(
118417   Rtree *pRtree,
118418   RtreeCell *aCell, 
118419   int nCell, 
118420   RtreeCell *pLeftBox, 
118421   RtreeCell *pRightBox,
118422   int *aiUsed
118423 ){
118424   int ii;
118425   for(ii=0; aiUsed[ii]; ii++);
118426   aiUsed[ii] = 1;
118427   return &aCell[ii];
118428 }
118429
118430 /*
118431 ** Implementation of the linear variant of the PickSeeds() function from
118432 ** Guttman[84].
118433 */
118434 static void LinearPickSeeds(
118435   Rtree *pRtree,
118436   RtreeCell *aCell, 
118437   int nCell, 
118438   int *piLeftSeed, 
118439   int *piRightSeed
118440 ){
118441   int i;
118442   int iLeftSeed = 0;
118443   int iRightSeed = 1;
118444   float maxNormalInnerWidth = 0.0;
118445
118446   /* Pick two "seed" cells from the array of cells. The algorithm used
118447   ** here is the LinearPickSeeds algorithm from Gutman[1984]. The 
118448   ** indices of the two seed cells in the array are stored in local
118449   ** variables iLeftSeek and iRightSeed.
118450   */
118451   for(i=0; i<pRtree->nDim; i++){
118452     float x1 = DCOORD(aCell[0].aCoord[i*2]);
118453     float x2 = DCOORD(aCell[0].aCoord[i*2+1]);
118454     float x3 = x1;
118455     float x4 = x2;
118456     int jj;
118457
118458     int iCellLeft = 0;
118459     int iCellRight = 0;
118460
118461     for(jj=1; jj<nCell; jj++){
118462       float left = DCOORD(aCell[jj].aCoord[i*2]);
118463       float right = DCOORD(aCell[jj].aCoord[i*2+1]);
118464
118465       if( left<x1 ) x1 = left;
118466       if( right>x4 ) x4 = right;
118467       if( left>x3 ){
118468         x3 = left;
118469         iCellRight = jj;
118470       }
118471       if( right<x2 ){
118472         x2 = right;
118473         iCellLeft = jj;
118474       }
118475     }
118476
118477     if( x4!=x1 ){
118478       float normalwidth = (x3 - x2) / (x4 - x1);
118479       if( normalwidth>maxNormalInnerWidth ){
118480         iLeftSeed = iCellLeft;
118481         iRightSeed = iCellRight;
118482       }
118483     }
118484   }
118485
118486   *piLeftSeed = iLeftSeed;
118487   *piRightSeed = iRightSeed;
118488 }
118489 #endif /* VARIANT_GUTTMAN_LINEAR_SPLIT */
118490
118491 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
118492 /*
118493 ** Implementation of the quadratic variant of the PickNext() function from
118494 ** Guttman[84].
118495 */
118496 static RtreeCell *QuadraticPickNext(
118497   Rtree *pRtree,
118498   RtreeCell *aCell, 
118499   int nCell, 
118500   RtreeCell *pLeftBox, 
118501   RtreeCell *pRightBox,
118502   int *aiUsed
118503 ){
118504   #define FABS(a) ((a)<0.0?-1.0*(a):(a))
118505
118506   int iSelect = -1;
118507   float fDiff;
118508   int ii;
118509   for(ii=0; ii<nCell; ii++){
118510     if( aiUsed[ii]==0 ){
118511       float left = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
118512       float right = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
118513       float diff = FABS(right-left);
118514       if( iSelect<0 || diff>fDiff ){
118515         fDiff = diff;
118516         iSelect = ii;
118517       }
118518     }
118519   }
118520   aiUsed[iSelect] = 1;
118521   return &aCell[iSelect];
118522 }
118523
118524 /*
118525 ** Implementation of the quadratic variant of the PickSeeds() function from
118526 ** Guttman[84].
118527 */
118528 static void QuadraticPickSeeds(
118529   Rtree *pRtree,
118530   RtreeCell *aCell, 
118531   int nCell, 
118532   int *piLeftSeed, 
118533   int *piRightSeed
118534 ){
118535   int ii;
118536   int jj;
118537
118538   int iLeftSeed = 0;
118539   int iRightSeed = 1;
118540   float fWaste = 0.0;
118541
118542   for(ii=0; ii<nCell; ii++){
118543     for(jj=ii+1; jj<nCell; jj++){
118544       float right = cellArea(pRtree, &aCell[jj]);
118545       float growth = cellGrowth(pRtree, &aCell[ii], &aCell[jj]);
118546       float waste = growth - right;
118547
118548       if( waste>fWaste ){
118549         iLeftSeed = ii;
118550         iRightSeed = jj;
118551         fWaste = waste;
118552       }
118553     }
118554   }
118555
118556   *piLeftSeed = iLeftSeed;
118557   *piRightSeed = iRightSeed;
118558 }
118559 #endif /* VARIANT_GUTTMAN_QUADRATIC_SPLIT */
118560
118561 /*
118562 ** Arguments aIdx, aDistance and aSpare all point to arrays of size
118563 ** nIdx. The aIdx array contains the set of integers from 0 to 
118564 ** (nIdx-1) in no particular order. This function sorts the values
118565 ** in aIdx according to the indexed values in aDistance. For
118566 ** example, assuming the inputs:
118567 **
118568 **   aIdx      = { 0,   1,   2,   3 }
118569 **   aDistance = { 5.0, 2.0, 7.0, 6.0 }
118570 **
118571 ** this function sets the aIdx array to contain:
118572 **
118573 **   aIdx      = { 0,   1,   2,   3 }
118574 **
118575 ** The aSpare array is used as temporary working space by the
118576 ** sorting algorithm.
118577 */
118578 static void SortByDistance(
118579   int *aIdx, 
118580   int nIdx, 
118581   float *aDistance, 
118582   int *aSpare
118583 ){
118584   if( nIdx>1 ){
118585     int iLeft = 0;
118586     int iRight = 0;
118587
118588     int nLeft = nIdx/2;
118589     int nRight = nIdx-nLeft;
118590     int *aLeft = aIdx;
118591     int *aRight = &aIdx[nLeft];
118592
118593     SortByDistance(aLeft, nLeft, aDistance, aSpare);
118594     SortByDistance(aRight, nRight, aDistance, aSpare);
118595
118596     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
118597     aLeft = aSpare;
118598
118599     while( iLeft<nLeft || iRight<nRight ){
118600       if( iLeft==nLeft ){
118601         aIdx[iLeft+iRight] = aRight[iRight];
118602         iRight++;
118603       }else if( iRight==nRight ){
118604         aIdx[iLeft+iRight] = aLeft[iLeft];
118605         iLeft++;
118606       }else{
118607         float fLeft = aDistance[aLeft[iLeft]];
118608         float fRight = aDistance[aRight[iRight]];
118609         if( fLeft<fRight ){
118610           aIdx[iLeft+iRight] = aLeft[iLeft];
118611           iLeft++;
118612         }else{
118613           aIdx[iLeft+iRight] = aRight[iRight];
118614           iRight++;
118615         }
118616       }
118617     }
118618
118619 #if 0
118620     /* Check that the sort worked */
118621     {
118622       int jj;
118623       for(jj=1; jj<nIdx; jj++){
118624         float left = aDistance[aIdx[jj-1]];
118625         float right = aDistance[aIdx[jj]];
118626         assert( left<=right );
118627       }
118628     }
118629 #endif
118630   }
118631 }
118632
118633 /*
118634 ** Arguments aIdx, aCell and aSpare all point to arrays of size
118635 ** nIdx. The aIdx array contains the set of integers from 0 to 
118636 ** (nIdx-1) in no particular order. This function sorts the values
118637 ** in aIdx according to dimension iDim of the cells in aCell. The
118638 ** minimum value of dimension iDim is considered first, the
118639 ** maximum used to break ties.
118640 **
118641 ** The aSpare array is used as temporary working space by the
118642 ** sorting algorithm.
118643 */
118644 static void SortByDimension(
118645   Rtree *pRtree,
118646   int *aIdx, 
118647   int nIdx, 
118648   int iDim, 
118649   RtreeCell *aCell, 
118650   int *aSpare
118651 ){
118652   if( nIdx>1 ){
118653
118654     int iLeft = 0;
118655     int iRight = 0;
118656
118657     int nLeft = nIdx/2;
118658     int nRight = nIdx-nLeft;
118659     int *aLeft = aIdx;
118660     int *aRight = &aIdx[nLeft];
118661
118662     SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
118663     SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
118664
118665     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
118666     aLeft = aSpare;
118667     while( iLeft<nLeft || iRight<nRight ){
118668       double xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
118669       double xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
118670       double xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
118671       double xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
118672       if( (iLeft!=nLeft) && ((iRight==nRight)
118673        || (xleft1<xright1)
118674        || (xleft1==xright1 && xleft2<xright2)
118675       )){
118676         aIdx[iLeft+iRight] = aLeft[iLeft];
118677         iLeft++;
118678       }else{
118679         aIdx[iLeft+iRight] = aRight[iRight];
118680         iRight++;
118681       }
118682     }
118683
118684 #if 0
118685     /* Check that the sort worked */
118686     {
118687       int jj;
118688       for(jj=1; jj<nIdx; jj++){
118689         float xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
118690         float xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
118691         float xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
118692         float xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
118693         assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
118694       }
118695     }
118696 #endif
118697   }
118698 }
118699
118700 #if VARIANT_RSTARTREE_SPLIT
118701 /*
118702 ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
118703 */
118704 static int splitNodeStartree(
118705   Rtree *pRtree,
118706   RtreeCell *aCell,
118707   int nCell,
118708   RtreeNode *pLeft,
118709   RtreeNode *pRight,
118710   RtreeCell *pBboxLeft,
118711   RtreeCell *pBboxRight
118712 ){
118713   int **aaSorted;
118714   int *aSpare;
118715   int ii;
118716
118717   int iBestDim;
118718   int iBestSplit;
118719   float fBestMargin;
118720
118721   int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
118722
118723   aaSorted = (int **)sqlite3_malloc(nByte);
118724   if( !aaSorted ){
118725     return SQLITE_NOMEM;
118726   }
118727
118728   aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
118729   memset(aaSorted, 0, nByte);
118730   for(ii=0; ii<pRtree->nDim; ii++){
118731     int jj;
118732     aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
118733     for(jj=0; jj<nCell; jj++){
118734       aaSorted[ii][jj] = jj;
118735     }
118736     SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
118737   }
118738
118739   for(ii=0; ii<pRtree->nDim; ii++){
118740     float margin = 0.0;
118741     float fBestOverlap;
118742     float fBestArea;
118743     int iBestLeft;
118744     int nLeft;
118745
118746     for(
118747       nLeft=RTREE_MINCELLS(pRtree); 
118748       nLeft<=(nCell-RTREE_MINCELLS(pRtree)); 
118749       nLeft++
118750     ){
118751       RtreeCell left;
118752       RtreeCell right;
118753       int kk;
118754       float overlap;
118755       float area;
118756
118757       memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
118758       memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
118759       for(kk=1; kk<(nCell-1); kk++){
118760         if( kk<nLeft ){
118761           cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
118762         }else{
118763           cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
118764         }
118765       }
118766       margin += cellMargin(pRtree, &left);
118767       margin += cellMargin(pRtree, &right);
118768       overlap = cellOverlap(pRtree, &left, &right, 1, -1);
118769       area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
118770       if( (nLeft==RTREE_MINCELLS(pRtree))
118771        || (overlap<fBestOverlap)
118772        || (overlap==fBestOverlap && area<fBestArea)
118773       ){
118774         iBestLeft = nLeft;
118775         fBestOverlap = overlap;
118776         fBestArea = area;
118777       }
118778     }
118779
118780     if( ii==0 || margin<fBestMargin ){
118781       iBestDim = ii;
118782       fBestMargin = margin;
118783       iBestSplit = iBestLeft;
118784     }
118785   }
118786
118787   memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
118788   memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
118789   for(ii=0; ii<nCell; ii++){
118790     RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
118791     RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
118792     RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
118793     nodeInsertCell(pRtree, pTarget, pCell);
118794     cellUnion(pRtree, pBbox, pCell);
118795   }
118796
118797   sqlite3_free(aaSorted);
118798   return SQLITE_OK;
118799 }
118800 #endif
118801
118802 #if VARIANT_GUTTMAN_SPLIT
118803 /*
118804 ** Implementation of the regular R-tree SplitNode from Guttman[1984].
118805 */
118806 static int splitNodeGuttman(
118807   Rtree *pRtree,
118808   RtreeCell *aCell,
118809   int nCell,
118810   RtreeNode *pLeft,
118811   RtreeNode *pRight,
118812   RtreeCell *pBboxLeft,
118813   RtreeCell *pBboxRight
118814 ){
118815   int iLeftSeed = 0;
118816   int iRightSeed = 1;
118817   int *aiUsed;
118818   int i;
118819
118820   aiUsed = sqlite3_malloc(sizeof(int)*nCell);
118821   if( !aiUsed ){
118822     return SQLITE_NOMEM;
118823   }
118824   memset(aiUsed, 0, sizeof(int)*nCell);
118825
118826   PickSeeds(pRtree, aCell, nCell, &iLeftSeed, &iRightSeed);
118827
118828   memcpy(pBboxLeft, &aCell[iLeftSeed], sizeof(RtreeCell));
118829   memcpy(pBboxRight, &aCell[iRightSeed], sizeof(RtreeCell));
118830   nodeInsertCell(pRtree, pLeft, &aCell[iLeftSeed]);
118831   nodeInsertCell(pRtree, pRight, &aCell[iRightSeed]);
118832   aiUsed[iLeftSeed] = 1;
118833   aiUsed[iRightSeed] = 1;
118834
118835   for(i=nCell-2; i>0; i--){
118836     RtreeCell *pNext;
118837     pNext = PickNext(pRtree, aCell, nCell, pBboxLeft, pBboxRight, aiUsed);
118838     float diff =  
118839       cellGrowth(pRtree, pBboxLeft, pNext) - 
118840       cellGrowth(pRtree, pBboxRight, pNext)
118841     ;
118842     if( (RTREE_MINCELLS(pRtree)-NCELL(pRight)==i)
118843      || (diff>0.0 && (RTREE_MINCELLS(pRtree)-NCELL(pLeft)!=i))
118844     ){
118845       nodeInsertCell(pRtree, pRight, pNext);
118846       cellUnion(pRtree, pBboxRight, pNext);
118847     }else{
118848       nodeInsertCell(pRtree, pLeft, pNext);
118849       cellUnion(pRtree, pBboxLeft, pNext);
118850     }
118851   }
118852
118853   sqlite3_free(aiUsed);
118854   return SQLITE_OK;
118855 }
118856 #endif
118857
118858 static int updateMapping(
118859   Rtree *pRtree, 
118860   i64 iRowid, 
118861   RtreeNode *pNode, 
118862   int iHeight
118863 ){
118864   int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
118865   xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
118866   if( iHeight>0 ){
118867     RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
118868     if( pChild ){
118869       nodeRelease(pRtree, pChild->pParent);
118870       nodeReference(pNode);
118871       pChild->pParent = pNode;
118872     }
118873   }
118874   return xSetMapping(pRtree, iRowid, pNode->iNode);
118875 }
118876
118877 static int SplitNode(
118878   Rtree *pRtree,
118879   RtreeNode *pNode,
118880   RtreeCell *pCell,
118881   int iHeight
118882 ){
118883   int i;
118884   int newCellIsRight = 0;
118885
118886   int rc = SQLITE_OK;
118887   int nCell = NCELL(pNode);
118888   RtreeCell *aCell;
118889   int *aiUsed;
118890
118891   RtreeNode *pLeft = 0;
118892   RtreeNode *pRight = 0;
118893
118894   RtreeCell leftbbox;
118895   RtreeCell rightbbox;
118896
118897   /* Allocate an array and populate it with a copy of pCell and 
118898   ** all cells from node pLeft. Then zero the original node.
118899   */
118900   aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
118901   if( !aCell ){
118902     rc = SQLITE_NOMEM;
118903     goto splitnode_out;
118904   }
118905   aiUsed = (int *)&aCell[nCell+1];
118906   memset(aiUsed, 0, sizeof(int)*(nCell+1));
118907   for(i=0; i<nCell; i++){
118908     nodeGetCell(pRtree, pNode, i, &aCell[i]);
118909   }
118910   nodeZero(pRtree, pNode);
118911   memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
118912   nCell++;
118913
118914   if( pNode->iNode==1 ){
118915     pRight = nodeNew(pRtree, pNode);
118916     pLeft = nodeNew(pRtree, pNode);
118917     pRtree->iDepth++;
118918     pNode->isDirty = 1;
118919     writeInt16(pNode->zData, pRtree->iDepth);
118920   }else{
118921     pLeft = pNode;
118922     pRight = nodeNew(pRtree, pLeft->pParent);
118923     nodeReference(pLeft);
118924   }
118925
118926   if( !pLeft || !pRight ){
118927     rc = SQLITE_NOMEM;
118928     goto splitnode_out;
118929   }
118930
118931   memset(pLeft->zData, 0, pRtree->iNodeSize);
118932   memset(pRight->zData, 0, pRtree->iNodeSize);
118933
118934   rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox);
118935   if( rc!=SQLITE_OK ){
118936     goto splitnode_out;
118937   }
118938
118939   /* Ensure both child nodes have node numbers assigned to them by calling
118940   ** nodeWrite(). Node pRight always needs a node number, as it was created
118941   ** by nodeNew() above. But node pLeft sometimes already has a node number.
118942   ** In this case avoid the all to nodeWrite().
118943   */
118944   if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
118945    || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
118946   ){
118947     goto splitnode_out;
118948   }
118949
118950   rightbbox.iRowid = pRight->iNode;
118951   leftbbox.iRowid = pLeft->iNode;
118952
118953   if( pNode->iNode==1 ){
118954     rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
118955     if( rc!=SQLITE_OK ){
118956       goto splitnode_out;
118957     }
118958   }else{
118959     RtreeNode *pParent = pLeft->pParent;
118960     int iCell;
118961     rc = nodeParentIndex(pRtree, pLeft, &iCell);
118962     if( rc==SQLITE_OK ){
118963       nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
118964       rc = AdjustTree(pRtree, pParent, &leftbbox);
118965     }
118966     if( rc!=SQLITE_OK ){
118967       goto splitnode_out;
118968     }
118969   }
118970   if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
118971     goto splitnode_out;
118972   }
118973
118974   for(i=0; i<NCELL(pRight); i++){
118975     i64 iRowid = nodeGetRowid(pRtree, pRight, i);
118976     rc = updateMapping(pRtree, iRowid, pRight, iHeight);
118977     if( iRowid==pCell->iRowid ){
118978       newCellIsRight = 1;
118979     }
118980     if( rc!=SQLITE_OK ){
118981       goto splitnode_out;
118982     }
118983   }
118984   if( pNode->iNode==1 ){
118985     for(i=0; i<NCELL(pLeft); i++){
118986       i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
118987       rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
118988       if( rc!=SQLITE_OK ){
118989         goto splitnode_out;
118990       }
118991     }
118992   }else if( newCellIsRight==0 ){
118993     rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
118994   }
118995
118996   if( rc==SQLITE_OK ){
118997     rc = nodeRelease(pRtree, pRight);
118998     pRight = 0;
118999   }
119000   if( rc==SQLITE_OK ){
119001     rc = nodeRelease(pRtree, pLeft);
119002     pLeft = 0;
119003   }
119004
119005 splitnode_out:
119006   nodeRelease(pRtree, pRight);
119007   nodeRelease(pRtree, pLeft);
119008   sqlite3_free(aCell);
119009   return rc;
119010 }
119011
119012 /*
119013 ** If node pLeaf is not the root of the r-tree and its pParent pointer is 
119014 ** still NULL, load all ancestor nodes of pLeaf into memory and populate
119015 ** the pLeaf->pParent chain all the way up to the root node.
119016 **
119017 ** This operation is required when a row is deleted (or updated - an update
119018 ** is implemented as a delete followed by an insert). SQLite provides the
119019 ** rowid of the row to delete, which can be used to find the leaf on which
119020 ** the entry resides (argument pLeaf). Once the leaf is located, this 
119021 ** function is called to determine its ancestry.
119022 */
119023 static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
119024   int rc = SQLITE_OK;
119025   RtreeNode *pChild = pLeaf;
119026   while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
119027     int rc2 = SQLITE_OK;          /* sqlite3_reset() return code */
119028     sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
119029     rc = sqlite3_step(pRtree->pReadParent);
119030     if( rc==SQLITE_ROW ){
119031       RtreeNode *pTest;           /* Used to test for reference loops */
119032       i64 iNode;                  /* Node number of parent node */
119033
119034       /* Before setting pChild->pParent, test that we are not creating a
119035       ** loop of references (as we would if, say, pChild==pParent). We don't
119036       ** want to do this as it leads to a memory leak when trying to delete
119037       ** the referenced counted node structures.
119038       */
119039       iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
119040       for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
119041       if( !pTest ){
119042         rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
119043       }
119044     }
119045     rc = sqlite3_reset(pRtree->pReadParent);
119046     if( rc==SQLITE_OK ) rc = rc2;
119047     if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT;
119048     pChild = pChild->pParent;
119049   }
119050   return rc;
119051 }
119052
119053 static int deleteCell(Rtree *, RtreeNode *, int, int);
119054
119055 static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
119056   int rc;
119057   int rc2;
119058   RtreeNode *pParent;
119059   int iCell;
119060
119061   assert( pNode->nRef==1 );
119062
119063   /* Remove the entry in the parent cell. */
119064   rc = nodeParentIndex(pRtree, pNode, &iCell);
119065   if( rc==SQLITE_OK ){
119066     pParent = pNode->pParent;
119067     pNode->pParent = 0;
119068     rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
119069   }
119070   rc2 = nodeRelease(pRtree, pParent);
119071   if( rc==SQLITE_OK ){
119072     rc = rc2;
119073   }
119074   if( rc!=SQLITE_OK ){
119075     return rc;
119076   }
119077
119078   /* Remove the xxx_node entry. */
119079   sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
119080   sqlite3_step(pRtree->pDeleteNode);
119081   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
119082     return rc;
119083   }
119084
119085   /* Remove the xxx_parent entry. */
119086   sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
119087   sqlite3_step(pRtree->pDeleteParent);
119088   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
119089     return rc;
119090   }
119091   
119092   /* Remove the node from the in-memory hash table and link it into
119093   ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
119094   */
119095   nodeHashDelete(pRtree, pNode);
119096   pNode->iNode = iHeight;
119097   pNode->pNext = pRtree->pDeleted;
119098   pNode->nRef++;
119099   pRtree->pDeleted = pNode;
119100
119101   return SQLITE_OK;
119102 }
119103
119104 static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
119105   RtreeNode *pParent = pNode->pParent;
119106   int rc = SQLITE_OK; 
119107   if( pParent ){
119108     int ii; 
119109     int nCell = NCELL(pNode);
119110     RtreeCell box;                            /* Bounding box for pNode */
119111     nodeGetCell(pRtree, pNode, 0, &box);
119112     for(ii=1; ii<nCell; ii++){
119113       RtreeCell cell;
119114       nodeGetCell(pRtree, pNode, ii, &cell);
119115       cellUnion(pRtree, &box, &cell);
119116     }
119117     box.iRowid = pNode->iNode;
119118     rc = nodeParentIndex(pRtree, pNode, &ii);
119119     if( rc==SQLITE_OK ){
119120       nodeOverwriteCell(pRtree, pParent, &box, ii);
119121       rc = fixBoundingBox(pRtree, pParent);
119122     }
119123   }
119124   return rc;
119125 }
119126
119127 /*
119128 ** Delete the cell at index iCell of node pNode. After removing the
119129 ** cell, adjust the r-tree data structure if required.
119130 */
119131 static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
119132   RtreeNode *pParent;
119133   int rc;
119134
119135   if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
119136     return rc;
119137   }
119138
119139   /* Remove the cell from the node. This call just moves bytes around
119140   ** the in-memory node image, so it cannot fail.
119141   */
119142   nodeDeleteCell(pRtree, pNode, iCell);
119143
119144   /* If the node is not the tree root and now has less than the minimum
119145   ** number of cells, remove it from the tree. Otherwise, update the
119146   ** cell in the parent node so that it tightly contains the updated
119147   ** node.
119148   */
119149   pParent = pNode->pParent;
119150   assert( pParent || pNode->iNode==1 );
119151   if( pParent ){
119152     if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
119153       rc = removeNode(pRtree, pNode, iHeight);
119154     }else{
119155       rc = fixBoundingBox(pRtree, pNode);
119156     }
119157   }
119158
119159   return rc;
119160 }
119161
119162 static int Reinsert(
119163   Rtree *pRtree, 
119164   RtreeNode *pNode, 
119165   RtreeCell *pCell, 
119166   int iHeight
119167 ){
119168   int *aOrder;
119169   int *aSpare;
119170   RtreeCell *aCell;
119171   float *aDistance;
119172   int nCell;
119173   float aCenterCoord[RTREE_MAX_DIMENSIONS];
119174   int iDim;
119175   int ii;
119176   int rc = SQLITE_OK;
119177
119178   memset(aCenterCoord, 0, sizeof(float)*RTREE_MAX_DIMENSIONS);
119179
119180   nCell = NCELL(pNode)+1;
119181
119182   /* Allocate the buffers used by this operation. The allocation is
119183   ** relinquished before this function returns.
119184   */
119185   aCell = (RtreeCell *)sqlite3_malloc(nCell * (
119186     sizeof(RtreeCell) +         /* aCell array */
119187     sizeof(int)       +         /* aOrder array */
119188     sizeof(int)       +         /* aSpare array */
119189     sizeof(float)               /* aDistance array */
119190   ));
119191   if( !aCell ){
119192     return SQLITE_NOMEM;
119193   }
119194   aOrder    = (int *)&aCell[nCell];
119195   aSpare    = (int *)&aOrder[nCell];
119196   aDistance = (float *)&aSpare[nCell];
119197
119198   for(ii=0; ii<nCell; ii++){
119199     if( ii==(nCell-1) ){
119200       memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
119201     }else{
119202       nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
119203     }
119204     aOrder[ii] = ii;
119205     for(iDim=0; iDim<pRtree->nDim; iDim++){
119206       aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
119207       aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
119208     }
119209   }
119210   for(iDim=0; iDim<pRtree->nDim; iDim++){
119211     aCenterCoord[iDim] = aCenterCoord[iDim]/((float)nCell*2.0);
119212   }
119213
119214   for(ii=0; ii<nCell; ii++){
119215     aDistance[ii] = 0.0;
119216     for(iDim=0; iDim<pRtree->nDim; iDim++){
119217       float coord = DCOORD(aCell[ii].aCoord[iDim*2+1]) - 
119218           DCOORD(aCell[ii].aCoord[iDim*2]);
119219       aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
119220     }
119221   }
119222
119223   SortByDistance(aOrder, nCell, aDistance, aSpare);
119224   nodeZero(pRtree, pNode);
119225
119226   for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
119227     RtreeCell *p = &aCell[aOrder[ii]];
119228     nodeInsertCell(pRtree, pNode, p);
119229     if( p->iRowid==pCell->iRowid ){
119230       if( iHeight==0 ){
119231         rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
119232       }else{
119233         rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
119234       }
119235     }
119236   }
119237   if( rc==SQLITE_OK ){
119238     rc = fixBoundingBox(pRtree, pNode);
119239   }
119240   for(; rc==SQLITE_OK && ii<nCell; ii++){
119241     /* Find a node to store this cell in. pNode->iNode currently contains
119242     ** the height of the sub-tree headed by the cell.
119243     */
119244     RtreeNode *pInsert;
119245     RtreeCell *p = &aCell[aOrder[ii]];
119246     rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
119247     if( rc==SQLITE_OK ){
119248       int rc2;
119249       rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
119250       rc2 = nodeRelease(pRtree, pInsert);
119251       if( rc==SQLITE_OK ){
119252         rc = rc2;
119253       }
119254     }
119255   }
119256
119257   sqlite3_free(aCell);
119258   return rc;
119259 }
119260
119261 /*
119262 ** Insert cell pCell into node pNode. Node pNode is the head of a 
119263 ** subtree iHeight high (leaf nodes have iHeight==0).
119264 */
119265 static int rtreeInsertCell(
119266   Rtree *pRtree,
119267   RtreeNode *pNode,
119268   RtreeCell *pCell,
119269   int iHeight
119270 ){
119271   int rc = SQLITE_OK;
119272   if( iHeight>0 ){
119273     RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
119274     if( pChild ){
119275       nodeRelease(pRtree, pChild->pParent);
119276       nodeReference(pNode);
119277       pChild->pParent = pNode;
119278     }
119279   }
119280   if( nodeInsertCell(pRtree, pNode, pCell) ){
119281 #if VARIANT_RSTARTREE_REINSERT
119282     if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
119283       rc = SplitNode(pRtree, pNode, pCell, iHeight);
119284     }else{
119285       pRtree->iReinsertHeight = iHeight;
119286       rc = Reinsert(pRtree, pNode, pCell, iHeight);
119287     }
119288 #else
119289     rc = SplitNode(pRtree, pNode, pCell, iHeight);
119290 #endif
119291   }else{
119292     rc = AdjustTree(pRtree, pNode, pCell);
119293     if( rc==SQLITE_OK ){
119294       if( iHeight==0 ){
119295         rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
119296       }else{
119297         rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
119298       }
119299     }
119300   }
119301   return rc;
119302 }
119303
119304 static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
119305   int ii;
119306   int rc = SQLITE_OK;
119307   int nCell = NCELL(pNode);
119308
119309   for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
119310     RtreeNode *pInsert;
119311     RtreeCell cell;
119312     nodeGetCell(pRtree, pNode, ii, &cell);
119313
119314     /* Find a node to store this cell in. pNode->iNode currently contains
119315     ** the height of the sub-tree headed by the cell.
119316     */
119317     rc = ChooseLeaf(pRtree, &cell, pNode->iNode, &pInsert);
119318     if( rc==SQLITE_OK ){
119319       int rc2;
119320       rc = rtreeInsertCell(pRtree, pInsert, &cell, pNode->iNode);
119321       rc2 = nodeRelease(pRtree, pInsert);
119322       if( rc==SQLITE_OK ){
119323         rc = rc2;
119324       }
119325     }
119326   }
119327   return rc;
119328 }
119329
119330 /*
119331 ** Select a currently unused rowid for a new r-tree record.
119332 */
119333 static int newRowid(Rtree *pRtree, i64 *piRowid){
119334   int rc;
119335   sqlite3_bind_null(pRtree->pWriteRowid, 1);
119336   sqlite3_bind_null(pRtree->pWriteRowid, 2);
119337   sqlite3_step(pRtree->pWriteRowid);
119338   rc = sqlite3_reset(pRtree->pWriteRowid);
119339   *piRowid = sqlite3_last_insert_rowid(pRtree->db);
119340   return rc;
119341 }
119342
119343 #ifndef NDEBUG
119344 static int hashIsEmpty(Rtree *pRtree){
119345   int ii;
119346   for(ii=0; ii<HASHSIZE; ii++){
119347     assert( !pRtree->aHash[ii] );
119348   }
119349   return 1;
119350 }
119351 #endif
119352
119353 /*
119354 ** The xUpdate method for rtree module virtual tables.
119355 */
119356 static int rtreeUpdate(
119357   sqlite3_vtab *pVtab, 
119358   int nData, 
119359   sqlite3_value **azData, 
119360   sqlite_int64 *pRowid
119361 ){
119362   Rtree *pRtree = (Rtree *)pVtab;
119363   int rc = SQLITE_OK;
119364
119365   rtreeReference(pRtree);
119366
119367   assert(nData>=1);
119368
119369   /* If azData[0] is not an SQL NULL value, it is the rowid of a
119370   ** record to delete from the r-tree table. The following block does
119371   ** just that.
119372   */
119373   if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
119374     i64 iDelete;                /* The rowid to delete */
119375     RtreeNode *pLeaf;           /* Leaf node containing record iDelete */
119376     int iCell;                  /* Index of iDelete cell in pLeaf */
119377     RtreeNode *pRoot;
119378
119379     /* Obtain a reference to the root node to initialise Rtree.iDepth */
119380     rc = nodeAcquire(pRtree, 1, 0, &pRoot);
119381
119382     /* Obtain a reference to the leaf node that contains the entry 
119383     ** about to be deleted. 
119384     */
119385     if( rc==SQLITE_OK ){
119386       iDelete = sqlite3_value_int64(azData[0]);
119387       rc = findLeafNode(pRtree, iDelete, &pLeaf);
119388     }
119389
119390     /* Delete the cell in question from the leaf node. */
119391     if( rc==SQLITE_OK ){
119392       int rc2;
119393       rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
119394       if( rc==SQLITE_OK ){
119395         rc = deleteCell(pRtree, pLeaf, iCell, 0);
119396       }
119397       rc2 = nodeRelease(pRtree, pLeaf);
119398       if( rc==SQLITE_OK ){
119399         rc = rc2;
119400       }
119401     }
119402
119403     /* Delete the corresponding entry in the <rtree>_rowid table. */
119404     if( rc==SQLITE_OK ){
119405       sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
119406       sqlite3_step(pRtree->pDeleteRowid);
119407       rc = sqlite3_reset(pRtree->pDeleteRowid);
119408     }
119409
119410     /* Check if the root node now has exactly one child. If so, remove
119411     ** it, schedule the contents of the child for reinsertion and 
119412     ** reduce the tree height by one.
119413     **
119414     ** This is equivalent to copying the contents of the child into
119415     ** the root node (the operation that Gutman's paper says to perform 
119416     ** in this scenario).
119417     */
119418     if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
119419       int rc2;
119420       RtreeNode *pChild;
119421       i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
119422       rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
119423       if( rc==SQLITE_OK ){
119424         rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
119425       }
119426       rc2 = nodeRelease(pRtree, pChild);
119427       if( rc==SQLITE_OK ) rc = rc2;
119428       if( rc==SQLITE_OK ){
119429         pRtree->iDepth--;
119430         writeInt16(pRoot->zData, pRtree->iDepth);
119431         pRoot->isDirty = 1;
119432       }
119433     }
119434
119435     /* Re-insert the contents of any underfull nodes removed from the tree. */
119436     for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
119437       if( rc==SQLITE_OK ){
119438         rc = reinsertNodeContent(pRtree, pLeaf);
119439       }
119440       pRtree->pDeleted = pLeaf->pNext;
119441       sqlite3_free(pLeaf);
119442     }
119443
119444     /* Release the reference to the root node. */
119445     if( rc==SQLITE_OK ){
119446       rc = nodeRelease(pRtree, pRoot);
119447     }else{
119448       nodeRelease(pRtree, pRoot);
119449     }
119450   }
119451
119452   /* If the azData[] array contains more than one element, elements
119453   ** (azData[2]..azData[argc-1]) contain a new record to insert into
119454   ** the r-tree structure.
119455   */
119456   if( rc==SQLITE_OK && nData>1 ){
119457     /* Insert a new record into the r-tree */
119458     RtreeCell cell;
119459     int ii;
119460     RtreeNode *pLeaf;
119461
119462     /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
119463     assert( nData==(pRtree->nDim*2 + 3) );
119464     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
119465       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
119466         cell.aCoord[ii].f = (float)sqlite3_value_double(azData[ii+3]);
119467         cell.aCoord[ii+1].f = (float)sqlite3_value_double(azData[ii+4]);
119468         if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
119469           rc = SQLITE_CONSTRAINT;
119470           goto constraint;
119471         }
119472       }
119473     }else{
119474       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
119475         cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
119476         cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
119477         if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
119478           rc = SQLITE_CONSTRAINT;
119479           goto constraint;
119480         }
119481       }
119482     }
119483
119484     /* Figure out the rowid of the new row. */
119485     if( sqlite3_value_type(azData[2])==SQLITE_NULL ){
119486       rc = newRowid(pRtree, &cell.iRowid);
119487     }else{
119488       cell.iRowid = sqlite3_value_int64(azData[2]);
119489       sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
119490       if( SQLITE_ROW==sqlite3_step(pRtree->pReadRowid) ){
119491         sqlite3_reset(pRtree->pReadRowid);
119492         rc = SQLITE_CONSTRAINT;
119493         goto constraint;
119494       }
119495       rc = sqlite3_reset(pRtree->pReadRowid);
119496     }
119497     *pRowid = cell.iRowid;
119498
119499     if( rc==SQLITE_OK ){
119500       rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
119501     }
119502     if( rc==SQLITE_OK ){
119503       int rc2;
119504       pRtree->iReinsertHeight = -1;
119505       rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
119506       rc2 = nodeRelease(pRtree, pLeaf);
119507       if( rc==SQLITE_OK ){
119508         rc = rc2;
119509       }
119510     }
119511   }
119512
119513 constraint:
119514   rtreeRelease(pRtree);
119515   return rc;
119516 }
119517
119518 /*
119519 ** The xRename method for rtree module virtual tables.
119520 */
119521 static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
119522   Rtree *pRtree = (Rtree *)pVtab;
119523   int rc = SQLITE_NOMEM;
119524   char *zSql = sqlite3_mprintf(
119525     "ALTER TABLE %Q.'%q_node'   RENAME TO \"%w_node\";"
119526     "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
119527     "ALTER TABLE %Q.'%q_rowid'  RENAME TO \"%w_rowid\";"
119528     , pRtree->zDb, pRtree->zName, zNewName 
119529     , pRtree->zDb, pRtree->zName, zNewName 
119530     , pRtree->zDb, pRtree->zName, zNewName
119531   );
119532   if( zSql ){
119533     rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
119534     sqlite3_free(zSql);
119535   }
119536   return rc;
119537 }
119538
119539 static sqlite3_module rtreeModule = {
119540   0,                         /* iVersion */
119541   rtreeCreate,                /* xCreate - create a table */
119542   rtreeConnect,               /* xConnect - connect to an existing table */
119543   rtreeBestIndex,             /* xBestIndex - Determine search strategy */
119544   rtreeDisconnect,            /* xDisconnect - Disconnect from a table */
119545   rtreeDestroy,               /* xDestroy - Drop a table */
119546   rtreeOpen,                  /* xOpen - open a cursor */
119547   rtreeClose,                 /* xClose - close a cursor */
119548   rtreeFilter,                /* xFilter - configure scan constraints */
119549   rtreeNext,                  /* xNext - advance a cursor */
119550   rtreeEof,                   /* xEof */
119551   rtreeColumn,                /* xColumn - read data */
119552   rtreeRowid,                 /* xRowid - read data */
119553   rtreeUpdate,                /* xUpdate - write data */
119554   0,                          /* xBegin - begin transaction */
119555   0,                          /* xSync - sync transaction */
119556   0,                          /* xCommit - commit transaction */
119557   0,                          /* xRollback - rollback transaction */
119558   0,                          /* xFindFunction - function overloading */
119559   rtreeRename                 /* xRename - rename the table */
119560 };
119561
119562 static int rtreeSqlInit(
119563   Rtree *pRtree, 
119564   sqlite3 *db, 
119565   const char *zDb, 
119566   const char *zPrefix, 
119567   int isCreate
119568 ){
119569   int rc = SQLITE_OK;
119570
119571   #define N_STATEMENT 9
119572   static const char *azSql[N_STATEMENT] = {
119573     /* Read and write the xxx_node table */
119574     "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
119575     "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
119576     "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
119577
119578     /* Read and write the xxx_rowid table */
119579     "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
119580     "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
119581     "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
119582
119583     /* Read and write the xxx_parent table */
119584     "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
119585     "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
119586     "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
119587   };
119588   sqlite3_stmt **appStmt[N_STATEMENT];
119589   int i;
119590
119591   pRtree->db = db;
119592
119593   if( isCreate ){
119594     char *zCreate = sqlite3_mprintf(
119595 "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
119596 "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
119597 "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY, parentnode INTEGER);"
119598 "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
119599       zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
119600     );
119601     if( !zCreate ){
119602       return SQLITE_NOMEM;
119603     }
119604     rc = sqlite3_exec(db, zCreate, 0, 0, 0);
119605     sqlite3_free(zCreate);
119606     if( rc!=SQLITE_OK ){
119607       return rc;
119608     }
119609   }
119610
119611   appStmt[0] = &pRtree->pReadNode;
119612   appStmt[1] = &pRtree->pWriteNode;
119613   appStmt[2] = &pRtree->pDeleteNode;
119614   appStmt[3] = &pRtree->pReadRowid;
119615   appStmt[4] = &pRtree->pWriteRowid;
119616   appStmt[5] = &pRtree->pDeleteRowid;
119617   appStmt[6] = &pRtree->pReadParent;
119618   appStmt[7] = &pRtree->pWriteParent;
119619   appStmt[8] = &pRtree->pDeleteParent;
119620
119621   for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
119622     char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
119623     if( zSql ){
119624       rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0); 
119625     }else{
119626       rc = SQLITE_NOMEM;
119627     }
119628     sqlite3_free(zSql);
119629   }
119630
119631   return rc;
119632 }
119633
119634 /*
119635 ** The second argument to this function contains the text of an SQL statement
119636 ** that returns a single integer value. The statement is compiled and executed
119637 ** using database connection db. If successful, the integer value returned
119638 ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
119639 ** code is returned and the value of *piVal after returning is not defined.
119640 */
119641 static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
119642   int rc = SQLITE_NOMEM;
119643   if( zSql ){
119644     sqlite3_stmt *pStmt = 0;
119645     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
119646     if( rc==SQLITE_OK ){
119647       if( SQLITE_ROW==sqlite3_step(pStmt) ){
119648         *piVal = sqlite3_column_int(pStmt, 0);
119649       }
119650       rc = sqlite3_finalize(pStmt);
119651     }
119652   }
119653   return rc;
119654 }
119655
119656 /*
119657 ** This function is called from within the xConnect() or xCreate() method to
119658 ** determine the node-size used by the rtree table being created or connected
119659 ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
119660 ** Otherwise, an SQLite error code is returned.
119661 **
119662 ** If this function is being called as part of an xConnect(), then the rtree
119663 ** table already exists. In this case the node-size is determined by inspecting
119664 ** the root node of the tree.
119665 **
119666 ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size. 
119667 ** This ensures that each node is stored on a single database page. If the 
119668 ** database page-size is so large that more than RTREE_MAXCELLS entries 
119669 ** would fit in a single node, use a smaller node-size.
119670 */
119671 static int getNodeSize(
119672   sqlite3 *db,                    /* Database handle */
119673   Rtree *pRtree,                  /* Rtree handle */
119674   int isCreate                    /* True for xCreate, false for xConnect */
119675 ){
119676   int rc;
119677   char *zSql;
119678   if( isCreate ){
119679     int iPageSize;
119680     zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
119681     rc = getIntFromStmt(db, zSql, &iPageSize);
119682     if( rc==SQLITE_OK ){
119683       pRtree->iNodeSize = iPageSize-64;
119684       if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
119685         pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
119686       }
119687     }
119688   }else{
119689     zSql = sqlite3_mprintf(
119690         "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
119691         pRtree->zDb, pRtree->zName
119692     );
119693     rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
119694   }
119695
119696   sqlite3_free(zSql);
119697   return rc;
119698 }
119699
119700 /* 
119701 ** This function is the implementation of both the xConnect and xCreate
119702 ** methods of the r-tree virtual table.
119703 **
119704 **   argv[0]   -> module name
119705 **   argv[1]   -> database name
119706 **   argv[2]   -> table name
119707 **   argv[...] -> column names...
119708 */
119709 static int rtreeInit(
119710   sqlite3 *db,                        /* Database connection */
119711   void *pAux,                         /* One of the RTREE_COORD_* constants */
119712   int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */
119713   sqlite3_vtab **ppVtab,              /* OUT: New virtual table */
119714   char **pzErr,                       /* OUT: Error message, if any */
119715   int isCreate                        /* True for xCreate, false for xConnect */
119716 ){
119717   int rc = SQLITE_OK;
119718   Rtree *pRtree;
119719   int nDb;              /* Length of string argv[1] */
119720   int nName;            /* Length of string argv[2] */
119721   int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
119722
119723   const char *aErrMsg[] = {
119724     0,                                                    /* 0 */
119725     "Wrong number of columns for an rtree table",         /* 1 */
119726     "Too few columns for an rtree table",                 /* 2 */
119727     "Too many columns for an rtree table"                 /* 3 */
119728   };
119729
119730   int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
119731   if( aErrMsg[iErr] ){
119732     *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
119733     return SQLITE_ERROR;
119734   }
119735
119736   /* Allocate the sqlite3_vtab structure */
119737   nDb = strlen(argv[1]);
119738   nName = strlen(argv[2]);
119739   pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
119740   if( !pRtree ){
119741     return SQLITE_NOMEM;
119742   }
119743   memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
119744   pRtree->nBusy = 1;
119745   pRtree->base.pModule = &rtreeModule;
119746   pRtree->zDb = (char *)&pRtree[1];
119747   pRtree->zName = &pRtree->zDb[nDb+1];
119748   pRtree->nDim = (argc-4)/2;
119749   pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
119750   pRtree->eCoordType = eCoordType;
119751   memcpy(pRtree->zDb, argv[1], nDb);
119752   memcpy(pRtree->zName, argv[2], nName);
119753
119754   /* Figure out the node size to use. */
119755   rc = getNodeSize(db, pRtree, isCreate);
119756
119757   /* Create/Connect to the underlying relational database schema. If
119758   ** that is successful, call sqlite3_declare_vtab() to configure
119759   ** the r-tree table schema.
119760   */
119761   if( rc==SQLITE_OK ){
119762     if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
119763       *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
119764     }else{
119765       char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
119766       char *zTmp;
119767       int ii;
119768       for(ii=4; zSql && ii<argc; ii++){
119769         zTmp = zSql;
119770         zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
119771         sqlite3_free(zTmp);
119772       }
119773       if( zSql ){
119774         zTmp = zSql;
119775         zSql = sqlite3_mprintf("%s);", zTmp);
119776         sqlite3_free(zTmp);
119777       }
119778       if( !zSql ){
119779         rc = SQLITE_NOMEM;
119780       }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
119781         *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
119782       }
119783       sqlite3_free(zSql);
119784     }
119785   }
119786
119787   if( rc==SQLITE_OK ){
119788     *ppVtab = (sqlite3_vtab *)pRtree;
119789   }else{
119790     rtreeRelease(pRtree);
119791   }
119792   return rc;
119793 }
119794
119795
119796 /*
119797 ** Implementation of a scalar function that decodes r-tree nodes to
119798 ** human readable strings. This can be used for debugging and analysis.
119799 **
119800 ** The scalar function takes two arguments, a blob of data containing
119801 ** an r-tree node, and the number of dimensions the r-tree indexes.
119802 ** For a two-dimensional r-tree structure called "rt", to deserialize
119803 ** all nodes, a statement like:
119804 **
119805 **   SELECT rtreenode(2, data) FROM rt_node;
119806 **
119807 ** The human readable string takes the form of a Tcl list with one
119808 ** entry for each cell in the r-tree node. Each entry is itself a
119809 ** list, containing the 8-byte rowid/pageno followed by the 
119810 ** <num-dimension>*2 coordinates.
119811 */
119812 static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
119813   char *zText = 0;
119814   RtreeNode node;
119815   Rtree tree;
119816   int ii;
119817
119818   memset(&node, 0, sizeof(RtreeNode));
119819   memset(&tree, 0, sizeof(Rtree));
119820   tree.nDim = sqlite3_value_int(apArg[0]);
119821   tree.nBytesPerCell = 8 + 8 * tree.nDim;
119822   node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
119823
119824   for(ii=0; ii<NCELL(&node); ii++){
119825     char zCell[512];
119826     int nCell = 0;
119827     RtreeCell cell;
119828     int jj;
119829
119830     nodeGetCell(&tree, &node, ii, &cell);
119831     sqlite3_snprintf(512-nCell,&zCell[nCell],"%d", cell.iRowid);
119832     nCell = strlen(zCell);
119833     for(jj=0; jj<tree.nDim*2; jj++){
119834       sqlite3_snprintf(512-nCell,&zCell[nCell]," %f",(double)cell.aCoord[jj].f);
119835       nCell = strlen(zCell);
119836     }
119837
119838     if( zText ){
119839       char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
119840       sqlite3_free(zText);
119841       zText = zTextNew;
119842     }else{
119843       zText = sqlite3_mprintf("{%s}", zCell);
119844     }
119845   }
119846   
119847   sqlite3_result_text(ctx, zText, -1, sqlite3_free);
119848 }
119849
119850 static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
119851   if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB 
119852    || sqlite3_value_bytes(apArg[0])<2
119853   ){
119854     sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1); 
119855   }else{
119856     u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
119857     sqlite3_result_int(ctx, readInt16(zBlob));
119858   }
119859 }
119860
119861 /*
119862 ** Register the r-tree module with database handle db. This creates the
119863 ** virtual table module "rtree" and the debugging/analysis scalar 
119864 ** function "rtreenode".
119865 */
119866 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
119867   const int utf8 = SQLITE_UTF8;
119868   int rc;
119869
119870   rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
119871   if( rc==SQLITE_OK ){
119872     int utf8 = SQLITE_UTF8;
119873     rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
119874   }
119875   if( rc==SQLITE_OK ){
119876     void *c = (void *)RTREE_COORD_REAL32;
119877     rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
119878   }
119879   if( rc==SQLITE_OK ){
119880     void *c = (void *)RTREE_COORD_INT32;
119881     rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
119882   }
119883
119884   return rc;
119885 }
119886
119887 /*
119888 ** A version of sqlite3_free() that can be used as a callback. This is used
119889 ** in two places - as the destructor for the blob value returned by the
119890 ** invocation of a geometry function, and as the destructor for the geometry
119891 ** functions themselves.
119892 */
119893 static void doSqlite3Free(void *p){
119894   sqlite3_free(p);
119895 }
119896
119897 /*
119898 ** Each call to sqlite3_rtree_geometry_callback() creates an ordinary SQLite
119899 ** scalar user function. This C function is the callback used for all such
119900 ** registered SQL functions.
119901 **
119902 ** The scalar user functions return a blob that is interpreted by r-tree
119903 ** table MATCH operators.
119904 */
119905 static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
119906   RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
119907   RtreeMatchArg *pBlob;
119908   int nBlob;
119909
119910   nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(double);
119911   pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
119912   if( !pBlob ){
119913     sqlite3_result_error_nomem(ctx);
119914   }else{
119915     int i;
119916     pBlob->magic = RTREE_GEOMETRY_MAGIC;
119917     pBlob->xGeom = pGeomCtx->xGeom;
119918     pBlob->pContext = pGeomCtx->pContext;
119919     pBlob->nParam = nArg;
119920     for(i=0; i<nArg; i++){
119921       pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
119922     }
119923     sqlite3_result_blob(ctx, pBlob, nBlob, doSqlite3Free);
119924   }
119925 }
119926
119927 /*
119928 ** Register a new geometry function for use with the r-tree MATCH operator.
119929 */
119930 SQLITE_API int sqlite3_rtree_geometry_callback(
119931   sqlite3 *db,
119932   const char *zGeom,
119933   int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *),
119934   void *pContext
119935 ){
119936   RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */
119937
119938   /* Allocate and populate the context object. */
119939   pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
119940   if( !pGeomCtx ) return SQLITE_NOMEM;
119941   pGeomCtx->xGeom = xGeom;
119942   pGeomCtx->pContext = pContext;
119943
119944   /* Create the new user-function. Register a destructor function to delete
119945   ** the context object when it is no longer required.  */
119946   return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY, 
119947       (void *)pGeomCtx, geomCallback, 0, 0, doSqlite3Free
119948   );
119949 }
119950
119951 #if !SQLITE_CORE
119952 SQLITE_API int sqlite3_extension_init(
119953   sqlite3 *db,
119954   char **pzErrMsg,
119955   const sqlite3_api_routines *pApi
119956 ){
119957   SQLITE_EXTENSION_INIT2(pApi)
119958   return sqlite3RtreeInit(db);
119959 }
119960 #endif
119961
119962 #endif
119963
119964 /************** End of rtree.c ***********************************************/
119965 /************** Begin file icu.c *********************************************/
119966 /*
119967 ** 2007 May 6
119968 **
119969 ** The author disclaims copyright to this source code.  In place of
119970 ** a legal notice, here is a blessing:
119971 **
119972 **    May you do good and not evil.
119973 **    May you find forgiveness for yourself and forgive others.
119974 **    May you share freely, never taking more than you give.
119975 **
119976 *************************************************************************
119977 ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
119978 **
119979 ** This file implements an integration between the ICU library 
119980 ** ("International Components for Unicode", an open-source library 
119981 ** for handling unicode data) and SQLite. The integration uses 
119982 ** ICU to provide the following to SQLite:
119983 **
119984 **   * An implementation of the SQL regexp() function (and hence REGEXP
119985 **     operator) using the ICU uregex_XX() APIs.
119986 **
119987 **   * Implementations of the SQL scalar upper() and lower() functions
119988 **     for case mapping.
119989 **
119990 **   * Integration of ICU and SQLite collation seqences.
119991 **
119992 **   * An implementation of the LIKE operator that uses ICU to 
119993 **     provide case-independent matching.
119994 */
119995
119996 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
119997
119998 /* Include ICU headers */
119999 #include <unicode/utypes.h>
120000 #include <unicode/uregex.h>
120001 #include <unicode/ustring.h>
120002 #include <unicode/ucol.h>
120003
120004
120005 #ifndef SQLITE_CORE
120006   SQLITE_EXTENSION_INIT1
120007 #else
120008 #endif
120009
120010 /*
120011 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
120012 ** operator.
120013 */
120014 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
120015 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
120016 #endif
120017
120018 /*
120019 ** Version of sqlite3_free() that is always a function, never a macro.
120020 */
120021 static void xFree(void *p){
120022   sqlite3_free(p);
120023 }
120024
120025 /*
120026 ** Compare two UTF-8 strings for equality where the first string is
120027 ** a "LIKE" expression. Return true (1) if they are the same and 
120028 ** false (0) if they are different.
120029 */
120030 static int icuLikeCompare(
120031   const uint8_t *zPattern,   /* LIKE pattern */
120032   const uint8_t *zString,    /* The UTF-8 string to compare against */
120033   const UChar32 uEsc         /* The escape character */
120034 ){
120035   static const int MATCH_ONE = (UChar32)'_';
120036   static const int MATCH_ALL = (UChar32)'%';
120037
120038   int iPattern = 0;       /* Current byte index in zPattern */
120039   int iString = 0;        /* Current byte index in zString */
120040
120041   int prevEscape = 0;     /* True if the previous character was uEsc */
120042
120043   while( zPattern[iPattern]!=0 ){
120044
120045     /* Read (and consume) the next character from the input pattern. */
120046     UChar32 uPattern;
120047     U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
120048     assert(uPattern!=0);
120049
120050     /* There are now 4 possibilities:
120051     **
120052     **     1. uPattern is an unescaped match-all character "%",
120053     **     2. uPattern is an unescaped match-one character "_",
120054     **     3. uPattern is an unescaped escape character, or
120055     **     4. uPattern is to be handled as an ordinary character
120056     */
120057     if( !prevEscape && uPattern==MATCH_ALL ){
120058       /* Case 1. */
120059       uint8_t c;
120060
120061       /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
120062       ** MATCH_ALL. For each MATCH_ONE, skip one character in the 
120063       ** test string.
120064       */
120065       while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
120066         if( c==MATCH_ONE ){
120067           if( zString[iString]==0 ) return 0;
120068           U8_FWD_1_UNSAFE(zString, iString);
120069         }
120070         iPattern++;
120071       }
120072
120073       if( zPattern[iPattern]==0 ) return 1;
120074
120075       while( zString[iString] ){
120076         if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
120077           return 1;
120078         }
120079         U8_FWD_1_UNSAFE(zString, iString);
120080       }
120081       return 0;
120082
120083     }else if( !prevEscape && uPattern==MATCH_ONE ){
120084       /* Case 2. */
120085       if( zString[iString]==0 ) return 0;
120086       U8_FWD_1_UNSAFE(zString, iString);
120087
120088     }else if( !prevEscape && uPattern==uEsc){
120089       /* Case 3. */
120090       prevEscape = 1;
120091
120092     }else{
120093       /* Case 4. */
120094       UChar32 uString;
120095       U8_NEXT_UNSAFE(zString, iString, uString);
120096       uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
120097       uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
120098       if( uString!=uPattern ){
120099         return 0;
120100       }
120101       prevEscape = 0;
120102     }
120103   }
120104
120105   return zString[iString]==0;
120106 }
120107
120108 /*
120109 ** Implementation of the like() SQL function.  This function implements
120110 ** the build-in LIKE operator.  The first argument to the function is the
120111 ** pattern and the second argument is the string.  So, the SQL statements:
120112 **
120113 **       A LIKE B
120114 **
120115 ** is implemented as like(B, A). If there is an escape character E, 
120116 **
120117 **       A LIKE B ESCAPE E
120118 **
120119 ** is mapped to like(B, A, E).
120120 */
120121 static void icuLikeFunc(
120122   sqlite3_context *context, 
120123   int argc, 
120124   sqlite3_value **argv
120125 ){
120126   const unsigned char *zA = sqlite3_value_text(argv[0]);
120127   const unsigned char *zB = sqlite3_value_text(argv[1]);
120128   UChar32 uEsc = 0;
120129
120130   /* Limit the length of the LIKE or GLOB pattern to avoid problems
120131   ** of deep recursion and N*N behavior in patternCompare().
120132   */
120133   if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
120134     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
120135     return;
120136   }
120137
120138
120139   if( argc==3 ){
120140     /* The escape character string must consist of a single UTF-8 character.
120141     ** Otherwise, return an error.
120142     */
120143     int nE= sqlite3_value_bytes(argv[2]);
120144     const unsigned char *zE = sqlite3_value_text(argv[2]);
120145     int i = 0;
120146     if( zE==0 ) return;
120147     U8_NEXT(zE, i, nE, uEsc);
120148     if( i!=nE){
120149       sqlite3_result_error(context, 
120150           "ESCAPE expression must be a single character", -1);
120151       return;
120152     }
120153   }
120154
120155   if( zA && zB ){
120156     sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
120157   }
120158 }
120159
120160 /*
120161 ** This function is called when an ICU function called from within
120162 ** the implementation of an SQL scalar function returns an error.
120163 **
120164 ** The scalar function context passed as the first argument is 
120165 ** loaded with an error message based on the following two args.
120166 */
120167 static void icuFunctionError(
120168   sqlite3_context *pCtx,       /* SQLite scalar function context */
120169   const char *zName,           /* Name of ICU function that failed */
120170   UErrorCode e                 /* Error code returned by ICU function */
120171 ){
120172   char zBuf[128];
120173   sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
120174   zBuf[127] = '\0';
120175   sqlite3_result_error(pCtx, zBuf, -1);
120176 }
120177
120178 /*
120179 ** Function to delete compiled regexp objects. Registered as
120180 ** a destructor function with sqlite3_set_auxdata().
120181 */
120182 static void icuRegexpDelete(void *p){
120183   URegularExpression *pExpr = (URegularExpression *)p;
120184   uregex_close(pExpr);
120185 }
120186
120187 /*
120188 ** Implementation of SQLite REGEXP operator. This scalar function takes
120189 ** two arguments. The first is a regular expression pattern to compile
120190 ** the second is a string to match against that pattern. If either 
120191 ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
120192 ** is 1 if the string matches the pattern, or 0 otherwise.
120193 **
120194 ** SQLite maps the regexp() function to the regexp() operator such
120195 ** that the following two are equivalent:
120196 **
120197 **     zString REGEXP zPattern
120198 **     regexp(zPattern, zString)
120199 **
120200 ** Uses the following ICU regexp APIs:
120201 **
120202 **     uregex_open()
120203 **     uregex_matches()
120204 **     uregex_close()
120205 */
120206 static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
120207   UErrorCode status = U_ZERO_ERROR;
120208   URegularExpression *pExpr;
120209   UBool res;
120210   const UChar *zString = sqlite3_value_text16(apArg[1]);
120211
120212   /* If the left hand side of the regexp operator is NULL, 
120213   ** then the result is also NULL. 
120214   */
120215   if( !zString ){
120216     return;
120217   }
120218
120219   pExpr = sqlite3_get_auxdata(p, 0);
120220   if( !pExpr ){
120221     const UChar *zPattern = sqlite3_value_text16(apArg[0]);
120222     if( !zPattern ){
120223       return;
120224     }
120225     pExpr = uregex_open(zPattern, -1, 0, 0, &status);
120226
120227     if( U_SUCCESS(status) ){
120228       sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
120229     }else{
120230       assert(!pExpr);
120231       icuFunctionError(p, "uregex_open", status);
120232       return;
120233     }
120234   }
120235
120236   /* Configure the text that the regular expression operates on. */
120237   uregex_setText(pExpr, zString, -1, &status);
120238   if( !U_SUCCESS(status) ){
120239     icuFunctionError(p, "uregex_setText", status);
120240     return;
120241   }
120242
120243   /* Attempt the match */
120244   res = uregex_matches(pExpr, 0, &status);
120245   if( !U_SUCCESS(status) ){
120246     icuFunctionError(p, "uregex_matches", status);
120247     return;
120248   }
120249
120250   /* Set the text that the regular expression operates on to a NULL
120251   ** pointer. This is not really necessary, but it is tidier than 
120252   ** leaving the regular expression object configured with an invalid
120253   ** pointer after this function returns.
120254   */
120255   uregex_setText(pExpr, 0, 0, &status);
120256
120257   /* Return 1 or 0. */
120258   sqlite3_result_int(p, res ? 1 : 0);
120259 }
120260
120261 /*
120262 ** Implementations of scalar functions for case mapping - upper() and 
120263 ** lower(). Function upper() converts its input to upper-case (ABC).
120264 ** Function lower() converts to lower-case (abc).
120265 **
120266 ** ICU provides two types of case mapping, "general" case mapping and
120267 ** "language specific". Refer to ICU documentation for the differences
120268 ** between the two.
120269 **
120270 ** To utilise "general" case mapping, the upper() or lower() scalar 
120271 ** functions are invoked with one argument:
120272 **
120273 **     upper('ABC') -> 'abc'
120274 **     lower('abc') -> 'ABC'
120275 **
120276 ** To access ICU "language specific" case mapping, upper() or lower()
120277 ** should be invoked with two arguments. The second argument is the name
120278 ** of the locale to use. Passing an empty string ("") or SQL NULL value
120279 ** as the second argument is the same as invoking the 1 argument version
120280 ** of upper() or lower().
120281 **
120282 **     lower('I', 'en_us') -> 'i'
120283 **     lower('I', 'tr_tr') -> 'ı' (small dotless i)
120284 **
120285 ** http://www.icu-project.org/userguide/posix.html#case_mappings
120286 */
120287 static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
120288   const UChar *zInput;
120289   UChar *zOutput;
120290   int nInput;
120291   int nOutput;
120292
120293   UErrorCode status = U_ZERO_ERROR;
120294   const char *zLocale = 0;
120295
120296   assert(nArg==1 || nArg==2);
120297   if( nArg==2 ){
120298     zLocale = (const char *)sqlite3_value_text(apArg[1]);
120299   }
120300
120301   zInput = sqlite3_value_text16(apArg[0]);
120302   if( !zInput ){
120303     return;
120304   }
120305   nInput = sqlite3_value_bytes16(apArg[0]);
120306
120307   nOutput = nInput * 2 + 2;
120308   zOutput = sqlite3_malloc(nOutput);
120309   if( !zOutput ){
120310     return;
120311   }
120312
120313   if( sqlite3_user_data(p) ){
120314     u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
120315   }else{
120316     u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
120317   }
120318
120319   if( !U_SUCCESS(status) ){
120320     icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
120321     return;
120322   }
120323
120324   sqlite3_result_text16(p, zOutput, -1, xFree);
120325 }
120326
120327 /*
120328 ** Collation sequence destructor function. The pCtx argument points to
120329 ** a UCollator structure previously allocated using ucol_open().
120330 */
120331 static void icuCollationDel(void *pCtx){
120332   UCollator *p = (UCollator *)pCtx;
120333   ucol_close(p);
120334 }
120335
120336 /*
120337 ** Collation sequence comparison function. The pCtx argument points to
120338 ** a UCollator structure previously allocated using ucol_open().
120339 */
120340 static int icuCollationColl(
120341   void *pCtx,
120342   int nLeft,
120343   const void *zLeft,
120344   int nRight,
120345   const void *zRight
120346 ){
120347   UCollationResult res;
120348   UCollator *p = (UCollator *)pCtx;
120349   res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
120350   switch( res ){
120351     case UCOL_LESS:    return -1;
120352     case UCOL_GREATER: return +1;
120353     case UCOL_EQUAL:   return 0;
120354   }
120355   assert(!"Unexpected return value from ucol_strcoll()");
120356   return 0;
120357 }
120358
120359 /*
120360 ** Implementation of the scalar function icu_load_collation().
120361 **
120362 ** This scalar function is used to add ICU collation based collation 
120363 ** types to an SQLite database connection. It is intended to be called
120364 ** as follows:
120365 **
120366 **     SELECT icu_load_collation(<locale>, <collation-name>);
120367 **
120368 ** Where <locale> is a string containing an ICU locale identifier (i.e.
120369 ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
120370 ** collation sequence to create.
120371 */
120372 static void icuLoadCollation(
120373   sqlite3_context *p, 
120374   int nArg, 
120375   sqlite3_value **apArg
120376 ){
120377   sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
120378   UErrorCode status = U_ZERO_ERROR;
120379   const char *zLocale;      /* Locale identifier - (eg. "jp_JP") */
120380   const char *zName;        /* SQL Collation sequence name (eg. "japanese") */
120381   UCollator *pUCollator;    /* ICU library collation object */
120382   int rc;                   /* Return code from sqlite3_create_collation_x() */
120383
120384   assert(nArg==2);
120385   zLocale = (const char *)sqlite3_value_text(apArg[0]);
120386   zName = (const char *)sqlite3_value_text(apArg[1]);
120387
120388   if( !zLocale || !zName ){
120389     return;
120390   }
120391
120392   pUCollator = ucol_open(zLocale, &status);
120393   if( !U_SUCCESS(status) ){
120394     icuFunctionError(p, "ucol_open", status);
120395     return;
120396   }
120397   assert(p);
120398
120399   rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator, 
120400       icuCollationColl, icuCollationDel
120401   );
120402   if( rc!=SQLITE_OK ){
120403     ucol_close(pUCollator);
120404     sqlite3_result_error(p, "Error registering collation function", -1);
120405   }
120406 }
120407
120408 /*
120409 ** Register the ICU extension functions with database db.
120410 */
120411 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
120412   struct IcuScalar {
120413     const char *zName;                        /* Function name */
120414     int nArg;                                 /* Number of arguments */
120415     int enc;                                  /* Optimal text encoding */
120416     void *pContext;                           /* sqlite3_user_data() context */
120417     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
120418   } scalars[] = {
120419     {"regexp", 2, SQLITE_ANY,          0, icuRegexpFunc},
120420
120421     {"lower",  1, SQLITE_UTF16,        0, icuCaseFunc16},
120422     {"lower",  2, SQLITE_UTF16,        0, icuCaseFunc16},
120423     {"upper",  1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
120424     {"upper",  2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
120425
120426     {"lower",  1, SQLITE_UTF8,         0, icuCaseFunc16},
120427     {"lower",  2, SQLITE_UTF8,         0, icuCaseFunc16},
120428     {"upper",  1, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
120429     {"upper",  2, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
120430
120431     {"like",   2, SQLITE_UTF8,         0, icuLikeFunc},
120432     {"like",   3, SQLITE_UTF8,         0, icuLikeFunc},
120433
120434     {"icu_load_collation",  2, SQLITE_UTF8, (void*)db, icuLoadCollation},
120435   };
120436
120437   int rc = SQLITE_OK;
120438   int i;
120439
120440   for(i=0; rc==SQLITE_OK && i<(sizeof(scalars)/sizeof(struct IcuScalar)); i++){
120441     struct IcuScalar *p = &scalars[i];
120442     rc = sqlite3_create_function(
120443         db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
120444     );
120445   }
120446
120447   return rc;
120448 }
120449
120450 #if !SQLITE_CORE
120451 SQLITE_API int sqlite3_extension_init(
120452   sqlite3 *db, 
120453   char **pzErrMsg,
120454   const sqlite3_api_routines *pApi
120455 ){
120456   SQLITE_EXTENSION_INIT2(pApi)
120457   return sqlite3IcuInit(db);
120458 }
120459 #endif
120460
120461 #endif
120462
120463 /************** End of icu.c *************************************************/
120464 /************** Begin file fts3_icu.c ****************************************/
120465 /*
120466 ** 2007 June 22
120467 **
120468 ** The author disclaims copyright to this source code.  In place of
120469 ** a legal notice, here is a blessing:
120470 **
120471 **    May you do good and not evil.
120472 **    May you find forgiveness for yourself and forgive others.
120473 **    May you share freely, never taking more than you give.
120474 **
120475 *************************************************************************
120476 ** This file implements a tokenizer for fts3 based on the ICU library.
120477 ** 
120478 ** $Id: fts3_icu.c,v 1.3 2008/09/01 18:34:20 danielk1977 Exp $
120479 */
120480
120481 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
120482 #ifdef SQLITE_ENABLE_ICU
120483
120484
120485 #include <unicode/ubrk.h>
120486 #include <unicode/utf16.h>
120487
120488 typedef struct IcuTokenizer IcuTokenizer;
120489 typedef struct IcuCursor IcuCursor;
120490
120491 struct IcuTokenizer {
120492   sqlite3_tokenizer base;
120493   char *zLocale;
120494 };
120495
120496 struct IcuCursor {
120497   sqlite3_tokenizer_cursor base;
120498
120499   UBreakIterator *pIter;      /* ICU break-iterator object */
120500   int nChar;                  /* Number of UChar elements in pInput */
120501   UChar *aChar;               /* Copy of input using utf-16 encoding */
120502   int *aOffset;               /* Offsets of each character in utf-8 input */
120503
120504   int nBuffer;
120505   char *zBuffer;
120506
120507   int iToken;
120508 };
120509
120510 /*
120511 ** Create a new tokenizer instance.
120512 */
120513 static int icuCreate(
120514   int argc,                            /* Number of entries in argv[] */
120515   const char * const *argv,            /* Tokenizer creation arguments */
120516   sqlite3_tokenizer **ppTokenizer      /* OUT: Created tokenizer */
120517 ){
120518   IcuTokenizer *p;
120519   int n = 0;
120520
120521   if( argc>0 ){
120522     n = strlen(argv[0])+1;
120523   }
120524   p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
120525   if( !p ){
120526     return SQLITE_NOMEM;
120527   }
120528   memset(p, 0, sizeof(IcuTokenizer));
120529
120530   if( n ){
120531     p->zLocale = (char *)&p[1];
120532     memcpy(p->zLocale, argv[0], n);
120533   }
120534
120535   *ppTokenizer = (sqlite3_tokenizer *)p;
120536
120537   return SQLITE_OK;
120538 }
120539
120540 /*
120541 ** Destroy a tokenizer
120542 */
120543 static int icuDestroy(sqlite3_tokenizer *pTokenizer){
120544   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
120545   sqlite3_free(p);
120546   return SQLITE_OK;
120547 }
120548
120549 /*
120550 ** Prepare to begin tokenizing a particular string.  The input
120551 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
120552 ** used to incrementally tokenize this string is returned in 
120553 ** *ppCursor.
120554 */
120555 static int icuOpen(
120556   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
120557   const char *zInput,                    /* Input string */
120558   int nInput,                            /* Length of zInput in bytes */
120559   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
120560 ){
120561   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
120562   IcuCursor *pCsr;
120563
120564   const int32_t opt = U_FOLD_CASE_DEFAULT;
120565   UErrorCode status = U_ZERO_ERROR;
120566   int nChar;
120567
120568   UChar32 c;
120569   int iInput = 0;
120570   int iOut = 0;
120571
120572   *ppCursor = 0;
120573
120574   if( nInput<0 ){
120575     nInput = strlen(zInput);
120576   }
120577   nChar = nInput+1;
120578   pCsr = (IcuCursor *)sqlite3_malloc(
120579       sizeof(IcuCursor) +                /* IcuCursor */
120580       nChar * sizeof(UChar) +            /* IcuCursor.aChar[] */
120581       (nChar+1) * sizeof(int)            /* IcuCursor.aOffset[] */
120582   );
120583   if( !pCsr ){
120584     return SQLITE_NOMEM;
120585   }
120586   memset(pCsr, 0, sizeof(IcuCursor));
120587   pCsr->aChar = (UChar *)&pCsr[1];
120588   pCsr->aOffset = (int *)&pCsr->aChar[nChar];
120589
120590   pCsr->aOffset[iOut] = iInput;
120591   U8_NEXT(zInput, iInput, nInput, c); 
120592   while( c>0 ){
120593     int isError = 0;
120594     c = u_foldCase(c, opt);
120595     U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
120596     if( isError ){
120597       sqlite3_free(pCsr);
120598       return SQLITE_ERROR;
120599     }
120600     pCsr->aOffset[iOut] = iInput;
120601
120602     if( iInput<nInput ){
120603       U8_NEXT(zInput, iInput, nInput, c);
120604     }else{
120605       c = 0;
120606     }
120607   }
120608
120609   pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
120610   if( !U_SUCCESS(status) ){
120611     sqlite3_free(pCsr);
120612     return SQLITE_ERROR;
120613   }
120614   pCsr->nChar = iOut;
120615
120616   ubrk_first(pCsr->pIter);
120617   *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
120618   return SQLITE_OK;
120619 }
120620
120621 /*
120622 ** Close a tokenization cursor previously opened by a call to icuOpen().
120623 */
120624 static int icuClose(sqlite3_tokenizer_cursor *pCursor){
120625   IcuCursor *pCsr = (IcuCursor *)pCursor;
120626   ubrk_close(pCsr->pIter);
120627   sqlite3_free(pCsr->zBuffer);
120628   sqlite3_free(pCsr);
120629   return SQLITE_OK;
120630 }
120631
120632 /*
120633 ** Extract the next token from a tokenization cursor.
120634 */
120635 static int icuNext(
120636   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
120637   const char **ppToken,               /* OUT: *ppToken is the token text */
120638   int *pnBytes,                       /* OUT: Number of bytes in token */
120639   int *piStartOffset,                 /* OUT: Starting offset of token */
120640   int *piEndOffset,                   /* OUT: Ending offset of token */
120641   int *piPosition                     /* OUT: Position integer of token */
120642 ){
120643   IcuCursor *pCsr = (IcuCursor *)pCursor;
120644
120645   int iStart = 0;
120646   int iEnd = 0;
120647   int nByte = 0;
120648
120649   while( iStart==iEnd ){
120650     UChar32 c;
120651
120652     iStart = ubrk_current(pCsr->pIter);
120653     iEnd = ubrk_next(pCsr->pIter);
120654     if( iEnd==UBRK_DONE ){
120655       return SQLITE_DONE;
120656     }
120657
120658     while( iStart<iEnd ){
120659       int iWhite = iStart;
120660       U8_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
120661       if( u_isspace(c) ){
120662         iStart = iWhite;
120663       }else{
120664         break;
120665       }
120666     }
120667     assert(iStart<=iEnd);
120668   }
120669
120670   do {
120671     UErrorCode status = U_ZERO_ERROR;
120672     if( nByte ){
120673       char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
120674       if( !zNew ){
120675         return SQLITE_NOMEM;
120676       }
120677       pCsr->zBuffer = zNew;
120678       pCsr->nBuffer = nByte;
120679     }
120680
120681     u_strToUTF8(
120682         pCsr->zBuffer, pCsr->nBuffer, &nByte,    /* Output vars */
120683         &pCsr->aChar[iStart], iEnd-iStart,       /* Input vars */
120684         &status                                  /* Output success/failure */
120685     );
120686   } while( nByte>pCsr->nBuffer );
120687
120688   *ppToken = pCsr->zBuffer;
120689   *pnBytes = nByte;
120690   *piStartOffset = pCsr->aOffset[iStart];
120691   *piEndOffset = pCsr->aOffset[iEnd];
120692   *piPosition = pCsr->iToken++;
120693
120694   return SQLITE_OK;
120695 }
120696
120697 /*
120698 ** The set of routines that implement the simple tokenizer
120699 */
120700 static const sqlite3_tokenizer_module icuTokenizerModule = {
120701   0,                           /* iVersion */
120702   icuCreate,                   /* xCreate  */
120703   icuDestroy,                  /* xCreate  */
120704   icuOpen,                     /* xOpen    */
120705   icuClose,                    /* xClose   */
120706   icuNext,                     /* xNext    */
120707 };
120708
120709 /*
120710 ** Set *ppModule to point at the implementation of the ICU tokenizer.
120711 */
120712 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
120713   sqlite3_tokenizer_module const**ppModule
120714 ){
120715   *ppModule = &icuTokenizerModule;
120716 }
120717
120718 #endif /* defined(SQLITE_ENABLE_ICU) */
120719 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
120720
120721 /************** End of fts3_icu.c ********************************************/